👨🏼💻개발/OpenCV
OpenCV - 캡챠 문자 검출하기
Janger
2022. 5. 18. 11:28
728x90
import cv2
import numpy as numpy
import matplotlib.pyplot as plt
img = cv2.imread('./characters.PNG')
img = cv2.blur(img, (10, 10), anchor=(-1, -1), borderType=cv2.BORDER_DEFAULT) # 블러처리(떨어진 조각을 붙이기)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 회색 전환
img_gray = 255 - img_gray # 이미지 반전
res, thr = cv2.threshold(img_gray, 90, 255, cv2.THRESH_BINARY) # 이진화
cv2.imshow('gray', thr)
contours, hierachy = cv2.findContours(thr, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 윤곽선 추출
# 윤곽선 그리기
for cnt in contours[0:]:
cv2.drawContours(img, [cnt], -1, (255, 255, 0), 2)
temp_img = img
# https://answers.opencv.org/question/179510/how-can-i-sort-the-contours-from-left-to-right-and-top-to-bottom/
contours = sorted( contours, key=lambda ctr: cv2.boundingRect(ctr)[0]) # X의 위치를 기준으로 이미지 순서 정렬
for cnt in contours[:]:
x, y, w, h = cv2.boundingRect(cnt)
if (h, w) > (10, 10):
cv2.rectangle(img, (x,y), (x+w, y+h), (0, 0, 255), 3)
# 사이즈만큼 추출
cropped = temp_img[y:y+h, x:x+w]
# 사이즈 두배
cropped = cv2.pyrUp(cropped, dstsize=(w*2, h*2), borderType=cv2.BORDER_DEFAULT)
cv2.imshow('cropped', cropped)
cv2.waitKey(0)
cv2.imshow('frame', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
결과:
참조:
https://076923.github.io/posts/Python-opencv-21/
Python OpenCV 강좌 : 제 21강 - 윤곽선 검출
윤곽선(Contour)
076923.github.io
728x90