묻고 답해요
164만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결워드프레스 제대로 개발하기 - 어드민 편
네임스페이스 중복을 회피하신다고 한부분이 궁금합니다.
(function () { }()); 이거 쓰면서 언급하신 부분이 궁금하네요. 정확히 왜 쓰는건지요?
-
미해결Vue.js 중급 강좌 - 웹앱 제작으로 배워보는 Vue.js, ES6, Vuex
git 권한 요청합니다.
id : jtyang0227@gmail.com
-
미해결OpenCV 를 활용한 명함인식 기능 구현 강좌
강의 마지막 예제에서 다음과 같은 에러가 발생합니다.
images/scannedImage.png only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices코드는 아래와 같습니다.# (참고) OpenCV - 이미지에서 텍스트 영역만 찾아내기 # 출처: http://www.danvk.org/2015/01/07/finding-blocks-of-text-in-an-image-using-python-opencv-and-numpy.html import glob import os import random import sys import random import math import json from collections import defaultdict import cv2 from PIL import Image, ImageDraw import numpy as np from scipy.ndimage.filters import rank_filter def dilate(ary, N, iterations): """Dilate using an NxN '+' sign shape. ary is np.uint8.""" kernel = np.zeros((N,N), dtype=np.uint8) kernel[(N-1)/2,:] = 1 dilated_image = cv2.dilate(ary / 255, kernel, iterations=iterations) kernel = np.zeros((N,N), dtype=np.uint8) kernel[:,(N-1)/2] = 1 dilated_image = cv2.dilate(dilated_image, kernel, iterations=iterations) dilated_image = cv2.convertScaleAbs(dilated_image) return dilated_image def props_for_contours(contours, ary): """Calculate bounding box & the number of set pixels for each contour.""" c_info = [] for c in contours: x,y,w,h = cv2.boundingRect(c) c_im = np.zeros(ary.shape) cv2.drawContours(c_im, [c], 0, 255, -1) c_info.append({ 'x1': x, 'y1': y, 'x2': x + w - 1, 'y2': y + h - 1, 'sum': np.sum(ary * (c_im > 0))/255 }) return c_info def union_crops(crop1, crop2): """Union two (x1, y1, x2, y2) rects.""" x11, y11, x21, y21 = crop1 x12, y12, x22, y22 = crop2 return min(x11, x12), min(y11, y12), max(x21, x22), max(y21, y22) def intersect_crops(crop1, crop2): x11, y11, x21, y21 = crop1 x12, y12, x22, y22 = crop2 return max(x11, x12), max(y11, y12), min(x21, x22), min(y21, y22) def crop_area(crop): x1, y1, x2, y2 = crop return max(0, x2 - x1) * max(0, y2 - y1) def find_border_components(contours, ary): borders = [] area = ary.shape[0] * ary.shape[1] for i, c in enumerate(contours): x,y,w,h = cv2.boundingRect(c) if w * h > 0.5 * area: borders.append((i, x, y, x + w - 1, y + h - 1)) return borders def angle_from_right(deg): return min(deg % 90, 90 - (deg % 90)) def remove_border(contour, ary): """Remove everything outside a border contour.""" # Use a rotated rectangle (should be a good approximation of a border). # If it's far from a right angle, it's probably two sides of a border and # we should use the bounding box instead. c_im = np.zeros(ary.shape) r = cv2.minAreaRect(contour) degs = r[2] if angle_from_right(degs) <= 10: box = cv2.boxPoints(r) box = np.int0(box) cv2.drawContours(c_im, [box], 0, 255, -1) cv2.drawContours(c_im, [box], 0, 0, 4) else: x1, y1, x2, y2 = cv2.boundingRect(contour) cv2.rectangle(c_im, (x1, y1), (x2, y2), 255, -1) cv2.rectangle(c_im, (x1, y1), (x2, y2), 0, 4) return np.minimum(c_im, ary) def find_components(edges, max_components=16): """Dilate the image until there are just a few connected components. Returns contours for these components.""" # Perform increasingly aggressive dilation until there are just a few # connected components. count = 21 dilation = 5 n = 1 while count > 16: n += 1 dilated_image = dilate(edges, N=3, iterations=n) #_, contours, hierarchy = cv2.findContours(dilated_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours, hierarchy = cv2.findContours(dilated_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) count = len(contours) #print dilation #Image.fromarray(edges).show() #Image.fromarray(255 * dilated_image).show() return contours def find_optimal_components_subset(contours, edges): """Find a crop which strikes a good balance of coverage/compactness. Returns an (x1, y1, x2, y2) tuple. """ c_info = props_for_contours(contours, edges) c_info.sort(key=lambda x: -x['sum']) total = np.sum(edges) / 255 area = edges.shape[0] * edges.shape[1] c = c_info[0] del c_info[0] this_crop = c['x1'], c['y1'], c['x2'], c['y2'] crop = this_crop covered_sum = c['sum'] while covered_sum < total: changed = False recall = 1 * covered_sum / total prec = 1 - 1 * crop_area(crop) / area f1 = 2 * (prec * recall / (prec + recall)) #print '----' for i, c in enumerate(c_info): this_crop = c['x1'], c['y1'], c['x2'], c['y2'] new_crop = union_crops(crop, this_crop) new_sum = covered_sum + c['sum'] new_recall = 1 * new_sum / total new_prec = 1 - 1 * crop_area(new_crop) / area new_f1 = 2 * new_prec * new_recall / (new_prec + new_recall) # Add this crop if it improves f1 score, # _or_ it adds 25% of the remaining pixels for <15% crop expansion. # ^^^ very ad-hoc! make this smoother remaining_frac = c['sum'] / (total - covered_sum) new_area_frac = 1 * crop_area(new_crop) / crop_area(crop) - 1 if new_f1 > f1 or ( remaining_frac > 0.25 and new_area_frac < 0.15): print('%d %s -> %s / %s (%s), %s -> %s / %s (%s), %s -> %s' % ( i, covered_sum, new_sum, total, remaining_frac, crop_area(crop), crop_area(new_crop), area, new_area_frac, f1, new_f1)) crop = new_crop covered_sum = new_sum del c_info[i] changed = True break if not changed: break return crop def pad_crop(crop, contours, edges, border_contour, pad_px=15): """Slightly expand the crop to get full contours. This will expand to include any contours it currently intersects, but will not expand past a border. """ bx1, by1, bx2, by2 = 0, 0, edges.shape[0], edges.shape[1] if border_contour is not None and len(border_contour) > 0: c = props_for_contours([border_contour], edges)[0] bx1, by1, bx2, by2 = c['x1'] + 5, c['y1'] + 5, c['x2'] - 5, c['y2'] - 5 def crop_in_border(crop): x1, y1, x2, y2 = crop x1 = max(x1 - pad_px, bx1) y1 = max(y1 - pad_px, by1) x2 = min(x2 + pad_px, bx2) y2 = min(y2 + pad_px, by2) return crop crop = crop_in_border(crop) c_info = props_for_contours(contours, edges) changed = False for c in c_info: this_crop = c['x1'], c['y1'], c['x2'], c['y2'] this_area = crop_area(this_crop) int_area = crop_area(intersect_crops(crop, this_crop)) new_crop = crop_in_border(union_crops(crop, this_crop)) if 0 < int_area < this_area and crop != new_crop: print('%s -> %s' % (str(crop), str(new_crop))) changed = True crop = new_crop if changed: return pad_crop(crop, contours, edges, border_contour, pad_px) else: return crop def downscale_image(im, max_dim=2048): """Shrink im until its longest dimension is <= max_dim. Returns new_image, scale (where scale <= 1). """ a = im.shape[0] b = im.shape[1] if max(a, b) <= max_dim: return 1, im scale = 1 * max_dim / max(a, b) dim = (int(a * scale), int(b * scale)) new_im = cv2.resize(im, dim, interpolation = cv2.INTER_AREA) return scale, new_im def process_image(path, out_path): orig_im = Image.open(path) im = cv2.imread(path, cv2.IMREAD_GRAYSCALE) scale, im = downscale_image(im) edges = cv2.Canny(im, 100, 200) # TODO: dilate image _before_ finding a border. This is crazy sensitive! #_, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) borders = find_border_components(contours, edges) borders.sort(key=lambda i_x1_y1_x2_y2: (i_x1_y1_x2_y2[3] - i_x1_y1_x2_y2[1]) * (i_x1_y1_x2_y2[4] - i_x1_y1_x2_y2[2])) border_contour = None if len(borders): border_contour = contours[borders[0][0]] edges = remove_border(border_contour, edges) edges = 255 * (edges > 0).astype(np.uint8) # Remove ~1px borders using a rank filter. maxed_rows = rank_filter(edges, -5, size=(1, 20)) maxed_cols = rank_filter(edges, -5, size=(20, 1)) debordered = np.minimum(np.minimum(edges, maxed_rows), maxed_cols) edges = debordered contours = find_components(edges) if len(contours) == 0: print('%s -> (no text!)' % path) return crop = find_optimal_components_subset(contours, edges) crop = pad_crop(crop, contours, edges, border_contour) crop = [int(x / scale) for x in crop] # upscale to the original image size. # draw and show cropped rectangle area in the original image rgb_im = orig_im.convert('RGB') draw = ImageDraw.Draw(rgb_im) draw.rectangle(crop, outline='red') rgb_im.show() text_im = orig_im.crop(crop) text_im.show() text_im.save(out_path) print('%s -> %s' % (path, out_path)) if __name__ == '__main__': # path = 'images/text.jpg' path = 'images/scannedImage.png' out_path = 'croppedImage.png' try: process_image(path, out_path) except Exception as e: print('%s %s' % (path, e))
-
미해결[개정판] 파이썬 머신러닝 완벽 가이드
cross_val_score, GridSearchCV에서 cv 값
안녕하세요. 위 함수/모듈에서 cv값을 정하게 되면 train, test를 나누는 방법은 KFold인건지요? 만약 그렇다면, StratifiedKFold로 하려면 다른 방법이 있을까요?
-
미해결취미로 해킹#1(OverTheWire - Bandit)
밴딧 초반 ssh 접속문제
현재 칼리사용하고 있으며 ssh접속시도를 하면 저렇게 세션이 끊기듯이 보이는데 인터넷에서 찾아보고 해결을 해보려고 해도 안되네요 (xshell도 동일한 현상) 혹 다른 해결방안은 있나요?
-
미해결리눅스 커맨드라인 툴
다른 강좌는 생각 없으신가요??
선생님 혹시 커널쪽으로 강좌를 해주실 생각은 없으신가요 시스템프로그래밍까지 하니 커널도 건드려 보고 싶은데 어려워서요 ㅠㅜ
-
미해결React로 NodeBird SNS 만들기
next를 사용하면,
next를 사용하면 기본적으로는 서버사이드 렌더링을 하는 것이 맞는지 궁금합니다. 기본 리액트 앱의 소스보기를 누르면 소스 보기에 내용 부분에 아무것도 나오지 않는 반면에, next로 만든 리액트 앱은 비동기로 불러와야 할 데이터를 빼면 태그들이 다 나오는 것 때문에 궁금합니다. - next는 기본적으로 ssr을 하는데, getinitialprops으로 조금 더 빨리 데이터를 붙여줄 수 있는 것인가요 - 아니면 getinitialprops을 사용함으로써 ssr을 할 수 있게 되는 것인가요?
-
해결됨Java TPC (생각하고, 표현하고, 코딩하고)
자바 설정중에 자바버젼 질문이요
안녕하세요, 꼭 자바 12로 설정해야하나요? 또는 1.8로 해도 상관 없나요?
-
미해결웹퍼블리셔가 알려주는 실무 웹사이트 따라만들기 Season1
[질문] css 임포트
안녕하세요. 따라서 하고 있는데요. 첫번째 동영상 강의에서 images 폴더까지 생성했는데, 두번째 동영상 강의 7:44 분정도에서 갑자기 css폴더가 생겨있는데, 제가 혹시 뭐 놓치고 있는건가요? css import를 하는건 알겠는데 저 파일이 갑자기 어디서 튀어나왔는지 모르겠어요..
-
미해결Klaytn 클레이튼 블록체인 어플리케이션 만들기 - NFT
[참고] Npm run dev 오류
Npm run dev 실행시 다음같은 오류가 발생할 경우 internal/modules/cjs/loader.js:638 throw err; Error: Cannot find module "acorn" 제 경운 acron 설치로 해결 됐습니다. 이외 방법 있으시면 공유 바랍니다 npm install -- save acorn
-
미해결프로그래밍 시작하기 : 파이썬 입문 (Inflearn Original)
자릿수 질문 입니다
print('%06.2f' % (3.1415926535))를 실행하면 003.14가 나온다고 하셨는데요, 여기서 06.2f에서 6은 자릿수를 나타 내는 것인가요. 그렇다면 003.14에서 '.'도 자릿수에 포함되는 것으로 치는 것인가요?
-
미해결직접 만드는 노션 템플릿 BEST 7선
꿀팁 모음 강의는 재생이 안되는데 오류일까요?
꿀팁 모음 강의는 재생이 안되는데 오류일까요?
-
미해결디자인 패턴 with JAVA (GoF)
TestPattern2 질문
TestPattern2 실행시 [8번째 8번째 7번째 2번째 9번째 10번째 8번째 8번째 4번째 4번째] 이런식으로 console에 출력됩니다 .
-
미해결Vue.js 완벽 가이드 - 실습과 리팩토링으로 배우는 실전 개념
gist 로그인 되어있는데 여전히 clone이 안됩니다ㅜㅜ
깃헙 로그인이 되어있는데도 안되는 이유를 모르겠어요..ㅜㅜ
-
미해결Illustrator CC - 일러스트레이터 입문부터 실전까지 한번에 마스터하기
예제파일이 안 열리는데 어떻게 해야하나요?
오류가 계속 뜨네요ㅠ
-
미해결스프링 기반 REST API 개발
질문이 있습니다.
Resouce에 custom Jsonserialize를 만들어 사용하면 꼭 content:{} object안에 내용이 담기는데, 모델마다 serializer를 만들어 주지 않으면 일관성이 떨어져서 content 안에 있는 필드를 꺼내고 싶습니다. 검색을 아무리해도 잘 나오지 않아 질문드립니다.
-
미해결프리다(Frida)를 이용한 안드로이드 앱 모의해킹
FRIDA 실행 관련 문의
안녕하세요. 좋은 강의 잘 듣고 있습니다. 후킹하는 방법에 대해 막연하였는데, 좋은 강의가 되고 있습니다. 다름이아니라 강의 내용을 보면 후킹시 전제조건은 테스트할 앱이 프로세스에 떠 있어야 가능한 것으로 보이는데요. 특정 앱의 경우 실행 전까지 frida-ps -U 명령어를 사용하면 com.google.chrome 처럼 프로세스가 뜨지않는데, 이러한 앱들이 다비이스 정보를 체크하여 호환되지않으면(테블릿 전용 앱) 실행이 되지 않을 경우에는 후킹이 불가능한 것인지. 아니면 방법이 있는 것인지 궁금합니다!
-
해결됨남박사의 파이썬 기초부터 실전 100% 활용
같은조건이라면 합계를 구하는 방법이 if else로 가능할지 궁금합니다
안녕하세요 박사님 좋은 강의 잘보고 있습니다 if else 강의 중에 원하는 값을 알고있을때의 조건문은 가능하지만 원하는 값이 아니라 같은조건일때 합계를 구하는거에 의문이 생겨 여쭙습니다. 아래의 데이타 프레임이 있습니다. name food price 홍길동 볶음밥 5600 홍길동 떡볶이 6000 가가멜 볶음밥 5600 가제트 탕수육 6200 가가멜 볶음밥 5600 홍길동 볶음밥 5600 name과 food가 같은값일때 price의 합계를 구하려면 if df['name'] == df['name'] and df['food'] == df['food'] : df[ 'price'].sum() 이런식으로 도 가능할까요?
-
미해결Klaytn 클레이튼 블록체인 어플리케이션 만들기 - NFT
파일 검색 안되네요
동영상처럼 설정을 바꿔봤지만 파일 검색은 안되네요. 한버누열람한 이력이 있는 경우만 찾을 뿐..
-
해결됨Ethereum 실전! 초보자를 위한 Lottery Dapp 개발
recent mode 질문
안녕하세요 강의 잘 듣고 있습니다. 강의와 같이 소스를 작성했는데, MetaMask 연결 요청이 뜨지 않고, react 로고화면(초기화면)만 나오고 있습니다.recent mode로 접근하지 않는 것 같은데, 무엇이 잘못 되었는지 궁금합니다. 작성한 App.js 같이 남깁니다! import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Web3 from 'web3'; class App extends Component{ async componentDidMount() { await this.initWeb3(); } initWeb3 = async() => { if (window.ethereum) { console.log('recent mode'); this.web3 = new Web3(window.ethereum); try { // Request account access if needed await window.ethereum.enable(); // Acccounts now exposed // this.eth.sendTransaction({/* ... */}); } catch (error) { // User denied account access... console.log(`User denied account access error : ${error}`); } } // Legacy dapp browsers... else if (window.web3) { console.log('legacy mode'); this.web3 = new Web3(Web3.currentProvider); // Acccounts always exposed // web3.eth.sendTransaction({/* ... */}); } // Non-dapp browsers... else { console.log('Non-Ethereum browser detected. You should consider trying MetaMask!'); } } render(){ return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } } export default App;