우리의 목적은 이미지에서 텍스트가 적혀있는 버튼들을 찾아서, 글자가 다르게 적혀있는 한개의 버튼을 찾아낸 뒤 이를 하이라이트해서 사용자에게 보여주는 프로그램을 만드는 것입니다. 현재 글자를 찾아 컨투어를 인식하고 화면에 보여주는 부분까지는 문제 없이 동작합니다. 그러나 그 중에서 다른 글자를 하나 찾는 알고리즘이 제대로 동작하지 않는 것 같습니다. 참고로 우리가 찾아야 하는 다른 글자는 한글로 적혀 있습니다. 이를 고려하여 개선할 수 있는 아이디어에 대해 생각해보고, 이를 실제로 반영하여. 수정해주세요.
code
import cv2
import numpy as np
def extract_word_clusters(image_path, min_area=2000):
# 이미지 로드
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 이진화 (검은색 글자를 흰색 배경에서 인식)
_, binary = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)
# 팽창(Dilation)으로 글자들을 연결하여 하나의 덩어리로 만들기
kernel = np.ones((10, 10), np.uint8)
dilated = cv2.dilate(binary, kernel, iterations=2)
# 컨투어 찾기
contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 원본 이미지에서 글자 컨투어만 그리기
contour_img = img.copy()
filtered_contours = []
for contour in contours:
area = cv2.contourArea(contour)
if area > min_area: # 면적 기준 필터링
x, y, w, h = cv2.boundingRect(contour)
# 배경 색상 기준 확인 (흰색 배경)
mask = np.zeros(gray.shape, dtype=np.uint8)
cv2.drawContours(mask, [contour], -1, 255, -1) # 컨투어 영역을 흰색으로
mean_val = cv2.mean(gray, mask=mask)[0] # 평균 색상 계산
# 평균 색상이 흰색에 가까운지 확인
if mean_val > 210: # 흰색 배경의 기준
filtered_contours.append((x, y, w, h, img[y:y+h, x:x+w])) # 글자 이미지 저장
cv2.rectangle(contour_img, (x, y), (x + w, y + h), (0, 255, 0), 2) # 초록색 박스
return filtered_contours, contour_img
def find_different_letter(letters):
# 첫 번째 글자와 나머지 글자를 비교하기
if not letters:
return None
first_letter_img = letters[0][4] # 첫 번째 글자 이미지
different_letter_position = None
for i in range(1, len(letters)):
# 이미지 비교
if not np.array_equal(first_letter_img, letters[i][4]):
different_letter_position = letters[i]
break
return different_letter_position
def highlight_different_letter(image, different_letter_position):
# 다른 글자에 박스 그리기
x, y, w, h = different_letter_position[:4]
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) # 빨간색 박스
if __name__ == "__main__":
image_path = 'path_to_image.png' # 이미지 경로 설정
letters, contour_img = extract_word_clusters(image_path)
# 다른 글자 찾기
different_letter_position = find_different_letter(letters)
if different_letter_position:
highlight_different_letter(contour_img, different_letter_position)
cv2.imshow('Highlighted Different Letter', contour_img)
print(f"다른 글자의 위치: {different_letter_position[:4]}") # 위치 출력
else:
print("다른 글자가 없습니다.")
cv2.waitKey(0) # 키 입력 대기
cv2.destroyAllWindows()
Assistant
프로그램의 핵심 문제는 각 버튼의 이미지를 픽셀 단위로 단순히 비교하기 때문에, 버튼 안의 글자가 서로 다르더라도 전체 이미지가 다르지 않다면 한글 버튼을 제대로 식별하지 못할 수 있다는 점입니다. 한글은 모양이 비슷해 보이는 경우가 많아서 단순한 이미지 비교로는 정확하게 차이를 감지하기 어려울 수 있습니다. 이를 개선하기 위해 이미지 내의 글자를 실제 텍스트로 추출하고 비교하는 방법을 고려할 수 있습니다. 이를 위해 Tesseract OCR(Open Source Optical Character Recognition 툴)을 사용할 수 있습니다.
Tesseract OCR을 설치하고 Python에서 pytesseract 라이브러리를 사용해 텍스트를 추출하고 비교하는 방법으로 코드를 수정할 수 있습니다.
여전히 잘못된 글자를 찾고 있는 것 같은데, 글자를 어떻게 인식했는지 모두 터미널에 출력하여 보여주세요.
Assistant
프로그램이 각 버튼의 글자를 인식할 때마다 콘솔에 인식된 텍스트를 출력하도록 수정하겠습니다. 이는 pytesseract를 사용해서 추출한 각 글자의 텍스트를 터미널에 출력하여 디버깅하는 데 유용합니다. 넣어야 하는 출력 부분은 extract_word_clusters 함수 내에서 글자를 추출한 후입니다.
다음은 코드 수정 사항입니다:
python
import cv2
import numpy as np
import pytesseract
def extract_word_clusters(image_path, min_area=2000):
# 이미지 로드
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 이진화 (검은색 글자를 흰색 배경에서 인식)
_, binary = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)
# 팽창(Dilation)으로 글자들을 연결하여 하나의 덩어리로 만들기
kernel = np.ones((10, 10), np.uint8)
dilated = cv2.dilate(binary, kernel, iterations=2)
# 컨투어 찾기
contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 원본 이미지에서 글자 컨투어만 그리기
contour_img = img.copy()
filtered_contours = []
for contour in contours:
area = cv2.contourArea(contour)
if area > min_area: # 면적 기준 필터링
x, y, w, h = cv2.boundingRect(contour)
# 배경 색상 기준 확인 (흰색 배경)
mask = np.zeros(gray.shape, dtype=np.uint8)
cv2.drawContours(mask, [contour], -1, 255, -1) # 컨투어 영역을 흰색으로
mean_val = cv2.mean(gray, mask=mask)[0] # 평균 색상 계산
# 평균 색상이 흰색에 가까운지 확인
if mean_val > 210: # 흰색 배경의 기준
cropped_img = img[y:y+h, x:x+w]
# 텍스트 추출
text = pytesseract.image_to_string(cropped_img, lang='kor', config='--psm 6').strip()
filtered_contours.append((x, y, w, h, cropped_img, text))
# 인식된 텍스트를 출력
print(f"인식된 텍스트: {text}")
cv2.rectangle(contour_img, (x, y), (x + w, y + h), (0, 255, 0), 2) # 초록색 박스
return filtered_contours, contour_img
def find_different_letter(letters):
if not letters:
return None
# 첫 번째 글자의 텍스트
first_letter_text = letters[0][5]
different_letter_position = None
for i in range(1, len(letters)):
# 텍스트 비교
if first_letter_text != letters[i][5]:
different_letter_position = letters[i]
break
return different_letter_position
def highlight_different_letter(image, different_letter_position):
# 다른 글자에 박스 그리기
x, y, w, h = different_letter_position[:4]
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) # 빨간색 박스
if __name__ == "__main__":
image_path = 'path_to_image.png' # 이미지 경로 설정
letters, contour_img = extract_word_clusters(image_path)
# 다른 글자 찾기
different_letter_position = find_different_letter(letters)
if different_letter_position:
highlight_different_letter(contour_img, different_letter_position)
cv2.imshow('Highlighted Different Letter', contour_img)
print(f"다른 글자의 위치: {different_letter_position[:4]}") # 위치 출력
else:
print("다른 글자가 없습니다.")
cv2.waitKey(0) # 키 입력 대기
cv2.destroyAllWindows()
User
인식해야 하는 글자는 '대한[줄바꿈]민국[줄바꿈]만세'인데, 없는 글자를 추가로 '한[줄바꿈]대한[줄바꿈]민국[줄바꿈]만세'와 같이 이상하게 인식하는 경우가 있습니다. OCR 문제 같은데 개선 방법이 있을까요?
Assistant
OCR 성능이 좋지 않을 때의 일반적인 문제 중 하나입니다. '대한민국만세'와 같이 수직으로 배치된 글자는 Tesseract OCR이 가로 줄 단위로 인식할 가능성이 높기 때문에 줄바꿈이나 없는 글자가 추가될 수 있습니다. 이러한 문제를 해결하기 위한 몇 가지 방법을 아래에 제시합니다:
이미지 전처리 개선: OCR 인식 성능을 높이기 위해 이미지의 전처리를 개선합니다. 다음과 같은 방법을 사용할 수 있습니다.
해상도 향상: 이미지가 너무 저해상도일 경우 해상도를 인위적으로 높이는 방법을 사용합니다.
필터링: 이미지에 적당한 블러링이나 샤프닝을 적용해서 텍스트가 더 명확하게 보이도록 합니다.
명암 조절: 대비를 높여 글자가 더 잘 보이도록 합니다.
Tesseract 팩 설정 조정:
--psm 옵션을 조정하여 텍스트 배치 방식에 맞게 설정할 수 있습니다. --psm 11 (수직으로 정렬된 텍스트를 인식) 또는 --psm 6 (단일 블록의 단일 열 텍스트) 등을 시도해 볼 수 있습니다.
-c 옵션으로 tessedit_char_whitelist를 설정해 사용할 문자를 제한하거나, tessedit_char_blacklist로 잘못 인식되는 겹쳐 보이는 문자를 걸러낼 수도 있습니다.
텍스트 후처리:
OCR로 인식한 결과를 기준으로 줄 맞춤을 수동 조정하여 정규 표현식을 통해 일관된 패턴을 찾고 수정할 수 있습니다.
모델 훈련: Tesseract의 학습 기능을 이용해 일반적인 폰트나 문서를 더 잘 인식하도록 추가 데이터를 사용해 모델을 훈련할 수도 있습니다. 이는 다소 복잡하고 시간이 많이 걸리지만 특정 환경에 강하게 작동할 수 있습니다.
다음은 전처리 및 Tesseract 인식 설정을 개선하는 방법의 예시입니다:
python
User
근데 OCR은 실행 속도가 너무 오래걸리는 것 같습니다. 이미지의 패턴을 비교할 수 있는 방법은 없을까요?
Assistant
OCR이 이미지를 처리하는 데 시간이 걸리는 경우, 이미지 자체의 패턴을 비교하는 방법으로 해결할 수 있습니다. 이 경우 색상 혹은 이미지의 형태를 기준으로 비교할 수 있습니다. 특히, 이미지에 포함된 텍스트의 위치, 크기, 그리고 각 요소 간의 상대적 거리를 기반으로 비교할 수 있습니다. 아래에 몇 가지 접근 방식을 소개합니다.
1. 이미지 히스토그램 비교
이미지 히스토그램은 이미지의 색분포를 나타내며, 색상 또는 채도의 유사도를 비교하는 데 유용합니다.
프로그램에서 위 세 가지 방법을 비교 대상으로 선택하고, 모든 버튼을 하나의 기준 버튼과 비교하여 차이점을 찾아낼 수 있습니다. 기준 버튼과 거의 유사한 버튼은 같은 텍스트일 것으로 판단하고, 유사도가 떨어지는 버튼을 '다른 글자' 버튼으로 여길 수 있습니다.
이 방법들은 텍스트의 세부적인 차이를 정확히 감지하기는 어렵지만, 패턴이나 구조적 유사도의 차이로 적절한 인식 결과를 얻는 데 유용할 수 있습니다.
User
한글 텍스트를 구별하기에 가장 적절할 것 같은 알고리즘을 찾아 추천해주세요.
Assistant
한글 텍스트를 구별하는 데 효과적인 알고리즘은 일반적으로 이미지의 미세한 차이와 패턴을 감지할 수 있는 방법이어야 합니다. 아래 몇 가지 방법 중 한글이나 다른 복잡한 문자 체계에 잘 맞는 알고리즘을 추천합니다.
1. 템플릿 매칭(Template Matching)
템플릿 매칭은 이미지의 특정 패턴을 찾기 위한 방법입니다. 일반적인 상황에서는 모든 글자를 개별적으로 저장한 뒤, 대상 이미지에서 매치되는 영역을 찾는 방식으로 사용할 수 있으며, 한글과 같은 복잡한 문자도 잘 구별할 수 있는 방법 중 하나입니다.
장점: 정확한 동일 문자 비교에 유리하며, 이미지에서 특정 패턴을 감지하는 능력이 뛰어남.
단점: 템플릿이 각 글자별로 필요하며, 정밀한 회전이나 축소 등의 변형에는 성능이 떨어질 수 있음.
2. ORB(Oriented FAST and Rotated BRIEF)
ORB는 특징 디스크립터를 사용하는 알고리즘으로, 각각의 이미지에서 특징점을 감지하고 비교합니다. 한글이나 다른 언어의 복잡한 문자를 잘 구별할 수 있습니다.
장점: 크기나 회전 불변의 특징을 갖고, 비교적 빠르고 성능이 좋음. 관심영역 내의 텍스트를 찾는 데 유리.
단점: 텍스트 외에 다른 이미지 구성 요소가 화면에 많을 경우 성능 저하 가능성.
3. CNN 기반의 문자 인식 모델
Convolutional Neural Networks (CNN)은 이미지 분류 및 객체 인식에서 탁월한 성능을 보여줍니다. 사전 훈련된 모델을 사용하거나, 대량의 한글 이미지 데이터셋을 사용해 모델을 훈련시켜 특정 한글 문자를 인식할 수 있습니다.
장점: 다양한 글꼴과 스타일 변형에 강하며, 높은 인식률을 자랑함.
단점: 사전 훈련이나 커스텀 모델을 만드는 데 많은 데이터와 계산 자원이 필요함.
추천
한글 텍스트의 패턴 인식을 위한 ORB 알고리즘을 사용해보시는 것을 추천드립니다. 특정 관심 영역에서 문자 간 비교를 통해 다른 문자를 감지하는 방식으로 유용합니다. 아래에서는 ORB를 사용하여 두 이미지의 키포인트를 비교하는 방법에 대한 간단한 예시를 보여드리겠습니다.
python
import cv2
def compare_images_orb(img1, img2):
# ORB 디텍터를 초기화
orb = cv2.ORB_create()
# 키포인트와 디스크립터를 찾음
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)
# BF매처 초기화
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
# 디스크립터 매칭
matches = bf.match(des1, des2)
# 매칭 결과를 거리로 정렬 (순서대로 정렬된 매치)
matches = sorted(matches, key=lambda x: x.distance)
# 이미지의 유사도를 거리 기반으로 계산
# 거리가 가까울수록 유사도가 높음
similarity_score = sum([match.distance for match in matches]) / len(matches)
return similarity_score
이 방법을 사용하여 기준 이미지와 대상 이미지를 비교하고 점수가 낮은(유사성이 높은) 이미지만 필터링하여 구별할 수 있습니다. 이 방식은 이미지의 위치와 회전이 조금 달라도 잘 처리할 수 있어 다양한 상황에서 유용하게 쓸 수 있습니다.
User
다음 코드에 해당 알고리즘을 적용하여 전체 코드를 다시 작성해주세요.
code
import cv2
import numpy as np
import pytesseract
def extract_word_clusters(image_path, min_area=2000):
# 이미지 로드
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 이진화 (검은색 글자를 흰색 배경에서 인식)
_, binary = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)
# 팽창(Dilation)으로 글자들을 연결하여 하나의 덩어리로 만들기
kernel = np.ones((10, 10), np.uint8)
dilated = cv2.dilate(binary, kernel, iterations=2)
# 컨투어 찾기
contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 원본 이미지에서 글자 컨투어만 그리기
contour_img = img.copy()
filtered_contours = []
for contour in contours:
area = cv2.contourArea(contour)
if area > min_area: # 면적 기준 필터링
x, y, w, h = cv2.boundingRect(contour)
# 배경 색상 기준 확인 (흰색 배경)
mask = np.zeros(gray.shape, dtype=np.uint8)
cv2.drawContours(mask, [contour], -1, 255, -1) # 컨투어 영역을 흰색으로
mean_val = cv2.mean(gray, mask=mask)[0] # 평균 색상 계산
# 평균 색상이 흰색에 가까운지 확인
if mean_val > 210: # 흰색 배경의 기준
cropped_img = img[y:y+h, x:x+w]
# 텍스트 추출
text = pytesseract.image_to_string(cropped_img, lang='kor', config='--psm 6').strip()
filtered_contours.append((x, y, w, h, cropped_img, text))
# 인식된 텍스트를 출력
print(f"인식된 텍스트: {text}")
cv2.rectangle(contour_img, (x, y), (x + w, y + h), (0, 255, 0), 2) # 초록색 박스
return filtered_contours, contour_img
def find_different_letter(letters):
if not letters:
return None
# 첫 번째 글자의 텍스트
first_letter_text = letters[0][5]
different_letter_position = None
for i in range(1, len(letters)):
# 텍스트 비교
if first_letter_text != letters[i][5]:
different_letter_position = letters[i]
break
return different_letter_position
def highlight_different_letter(image, different_letter_position):
# 다른 글자에 박스 그리기
x, y, w, h = different_letter_position[:4]
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) # 빨간색 박스
if __name__ == "__main__":
image_path = 'path_to_image.png' # 이미지 경로 설정
letters, contour_img = extract_word_clusters(image_path)
# 다른 글자 찾기
different_letter_position = find_different_letter(letters)
if different_letter_position:
highlight_different_letter(contour_img, different_letter_position)
cv2.imshow('Highlighted Different Letter', contour_img)
print(f"다른 글자의 위치: {different_letter_position[:4]}") # 위치 출력
else:
print("다른 글자가 없습니다.")
cv2.waitKey(0) # 키 입력 대기
cv2.destroyAllWindows()
Assistant
아래의 코드는 템플릿 매칭과 ORB 알고리즘을 사용하여 한글 텍스트 이미지의 다른 글자를 식별하도록 작성된 코드입니다. 안정적인 있는 글자를 찾기 위해 OCR 단계를 건너뛰고 이미지 패턴 비교를 활용합니다.
python
Not yet included in a published release.
import cv2
import numpy as np
import pytesseract
def extract_word_clusters(image_path, min_area=2000):
# 이미지 로드
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 이진화 (검은색 글자를 흰색 배경에서 인식)
_, binary = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)
# 팽창(Dilation)으로 글자들을 연결하여 하나의 덩어리로 만들기
kernel = np.ones((10, 10), np.uint8)
dilated = cv2.dilate(binary, kernel, iterations=2)
# 컨투어 찾기
contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 원본 이미지에서 글자 컨투어만 그리기
contour_img = img.copy()
filtered_contours = []
for contour in contours:
area = cv2.contourArea(contour)
if area > min_area: # 면적 기준 필터링
x, y, w, h = cv2.boundingRect(contour)
# 배경 색상 기준 확인 (흰색 배경)
mask = np.zeros(gray.shape, dtype=np.uint8)
cv2.drawContours(mask, [contour], -1, 255, -1) # 컨투어 영역을 흰색으로
mean_val = cv2.mean(gray, mask=mask)[0] # 평균 색상 계산
# 평균 색상이 흰색에 가까운지 확인
if mean_val > 210: # 흰색 배경의 기준
cropped_img = img[y:y+h, x:x+w]
# 텍스트 추출
text = pytesseract.image_to_string(cropped_img, lang='kor', config='--psm 6')
filtered_contours.append((x, y, w, h, cropped_img, text.strip()))
cv2.rectangle(contour_img, (x, y), (x + w, y + h), (0, 255, 0), 2) # 초록색 박스
return filtered_contours, contour_img
def find_different_letter(letters):
if not letters:
return None
# 첫 번째 글자의 텍스트
first_letter_text = letters[0][5]
different_letter_position = None
for i in range(1, len(letters)):
# 텍스트 비교
if first_letter_text != letters[i][5]:
different_letter_position = letters[i]
break
return different_letter_position
def highlight_different_letter(image, different_letter_position):
# 다른 글자에 박스 그리기
x, y, w, h = different_letter_position[:4]
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) # 빨간색 박스
if __name__ == "__main__":
image_path = 'path_to_image.png' # 이미지 경로 설정
letters, contour_img = extract_word_clusters(image_path)
# 다른 글자 찾기
different_letter_position = find_different_letter(letters)
if different_letter_position:
highlight_different_letter(contour_img, different_letter_position)
cv2.imshow('Highlighted Different Letter', contour_img)
print(f"다른 글자의 위치: {different_letter_position[:4]}") # 위치 출력
else:
print("다른 글자가 없습니다.")
cv2.waitKey(0) # 키 입력 대기
cv2.destroyAllWindows()
이 코드에서는 pytesseract를 사용하여 이미지를 텍스트로 변환하고, 이를 기반으로 차이점을 감지합니다. 기본적인 pytesseract 설정을 사용하기 때문에, 복잡한 이미지에서는 추가적인 이미지 전처리가 필요할 수 있습니다. pytesseract.image_to_string() 함수의 --psm 옵션을 조정하여 OCR 성능을 최적화할 수 있습니다.
위 코드를 실행하면 각 버튼의 인식된 텍스트가 터미널에 출력됩니다. 이를 통해 추출한 텍스트가 무엇인지 확인할 수 있으며, 프로그램이 정상적으로 작동하는지 점검할 수 있습니다. pytesseract에 의해 정확하지 않은 텍스트가 인식된다면, 이미지의 해상도를 높이거나, 전처리를 변경하여 인식 성능을 최대화할 수 있습니다.
import cv2
import numpy as np
import pytesseract
def preprocess_image(img):
# 이미지의 해상도 향상
scale_percent = 150 # 설정한 퍼센트 만큼 해상도 증가
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)
img = cv2.resize(img, dim, interpolation=cv2.INTER_CUBIC)
# 그레이스케일 변환
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 가우시안 블러링 적용
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
# 명암 대비 향상을 위한 히스토그램 평활화
equalized = cv2.equalizeHist(blurred)
# 이진화 (오츠 알고리즘 사용)
_, binary = cv2.threshold(equalized, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
return binary
def extract_word_clusters(image_path, min_area=2000):
img = cv2.imread(image_path)
processed_img = preprocess_image(img)
# 팽창(Dilation)으로 글자들을 연결하기
kernel = np.ones((10, 10), np.uint8)
dilated = cv2.dilate(processed_img, kernel, iterations=2)
contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contour_img = img.copy()
filtered_contours = []
for contour in contours:
area = cv2.contourArea(contour)
if area > min_area:
x, y, w, h = cv2.boundingRect(contour)
cropped_img = img[y:y+h, x:x+w]
text = pytesseract.image_to_string(
cropped_img, lang='kor',
config='--psm 6'
).strip()
filtered_contours.append((x, y, w, h, cropped_img, text))
print(f"인식된 텍스트: {text}")
cv2.rectangle(contour_img, (x, y), (x + w, y + h), (0, 255, 0), 2)
return filtered_contours, contour_img
# 나머지 부분은 이전 코드와 동일
이 코드에서는 이미지 인식 전처리를 더욱 정밀하게 하여 OCR 인식의 정확도를 높입니다. 특히, 수직으로 정렬된 텍스트가 잘 인식되기 위해 Tesseract의 psm 옵션을 잘 맞춰 설정할 필요가 있습니다. 그 외에도 사전 훈련된 모델 사용이나 특정 글꼴, 크기에 대한 훈련 데이터를 추가해 사용하는 것도 장기적인 해결책이 될 수 있습니다.
import cv2
import numpy as np
def extract_word_clusters(image_path, min_area=2000):
# 이미지 로드
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 이진화 (검은색 글자를 흰색 배경에서 인식)
_, binary = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)
# 팽창(Dilation)으로 글자들을 연결하여 하나의 덩어리로 만들기
kernel = np.ones((10, 10), np.uint8)
dilated = cv2.dilate(binary, kernel, iterations=2)
# 컨투어 찾기
contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contour_img = img.copy()
filtered_contours = []
for contour in contours:
area = cv2.contourArea(contour)
if area > min_area: # 면적 기준 필터링
x, y, w, h = cv2.boundingRect(contour)
# 배경 색상 기준 확인 (흰색 배경)
mask = np.zeros(gray.shape, dtype=np.uint8)
cv2.drawContours(mask, [contour], -1, 255, -1) # 컨투어 영역을 흰색으로
mean_val = cv2.mean(gray, mask=mask)[0] # 평균 색상 계산
# 평균 색상이 흰색에 가까운지 확인
if mean_val > 210: # 흰색 배경의 기준
cropped_img = img[y:y+h, x:x+w]
filtered_contours.append((x, y, w, h, cropped_img))
cv2.rectangle(contour_img, (x, y), (x + w, y + h), (0, 255, 0), 2) # 초록색 박스
return filtered_contours, contour_img
def compare_images_orb(img1, img2):
# ORB 디텍터를 초기화
orb = cv2.ORB_create()
# 키포인트와 디스크립터를 찾음
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)
# BF매처 초기화
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
# 디스크립터 매칭
matches = bf.match(des1, des2)
# 매칭 결과를 거리로 정렬 (순서대로 정렬된 매치)
matches = sorted(matches, key=lambda x: x.distance)
# 유사도 계산: 거리가 적을수록 유사
similarity_score = sum([match.distance for match in matches]) / len(matches)
return similarity_score
def find_different_letter(letters):
if not letters:
return None
# 기준이 되는 첫 번째 글자 영역
reference_img = letters[0][4]
thresholds = 30 # 유사도 기준선, 필요에 따라 조정
different_letter_position = None
lowest_score = float('inf')
for i in range(1, len(letters)):
similarity_score = compare_images_orb(reference_img, letters[i][4])
print(f"이미지 {i} 유사도 점수: {similarity_score}") # 유사도 점수 출력
if similarity_score < lowest_score:
lowest_score = similarity_score
different_letter_position = letters[i]
return different_letter_position if lowest_score > thresholds else None
def highlight_different_letter(image, different_letter_position):
# 다른 글자에 박스 그리기
x, y, w, h = different_letter_position[:4]
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) # 빨간색 박스
if __name__ == "__main__":
image_path = 'path_to_image.png' # 이미지 경로 설정
letters, contour_img = extract_word_clusters(image_path)
# 다른 글자 찾기
different_letter_position = find_different_letter(letters)
if different_letter_position:
highlight_different_letter(contour_img, different_letter_position)
cv2.imshow('Highlighted Different Letter', contour_img)
print(f"다른 글자의 위치: {different_letter_position[:4]}") # 위치 출력
else:
print("다른 글자가 없습니다.")
cv2.waitKey(0) # 키 입력 대기
cv2.destroyAllWindows()
이 코드에서는 extract_word_clusters를 통해 이미지 내 버튼 영역을 찾고, 각 버튼을 compare_images_orb로 비교하여 패턴의 유사성을 판단하고, 유사도가 낮은(차별적) 글자를 찾습니다. ORB 알고리즘은 이미지의 회전 및 크기 변화를 잘 처리할 수 있어 유리합니다.