다음 코드가 찾아낸 컨투어 영역들의 유사도를 모두 비교하여 다르게 생긴 이미지 하나를 찾아 녹색으로 표시하려고 합니다. 우리가 비교할 이미지는 밝은색 배경에…
- User
다음 코드가 찾아낸 컨투어 영역들의 유사도를 모두 비교하여 다르게 생긴 이미지 하나를 찾아 녹색으로 표시하려고 합니다. 우리가 비교할 이미지는 밝은색 배경에 어두운 색으로 적혀있는 한글 텍스트입니다. 매우 비슷한 글자의 차이를 감지해야 합니다. (예, '대한민국' vs '대한민극') 어떤 알고리즘을 사용하여 유사도를 비교해야 다른 글자가 적힌 이미지 하나를 찾아낼 수 있을지 여러 후보를 제시해본 뒤, 그 중 가장 적절한 알고리즘을 하나 결정하여 적용해주세요. 현재 빨간색 박스로 출력한 영역을 각각 하나의 이미지로 보고 비교해야 합니다. 제발 영역을 건드리지 말고 빨간색으로 최종 하이라이트 한 부분 정보를 활용하여 비교해주세요.
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_gray = gray[y:y+h, x:x+w] _, cropped_binary = cv2.threshold(cropped_gray, 200, 255, cv2.THRESH_BINARY_INV) # 내부 컨투어 찾기 internal_contours, _ = cv2.findContours(cropped_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 내부 컨투어들을 하나의 사각형으로 합치기 if internal_contours: all_points = np.vstack(internal_contours) # 모든 점들을 합침 ix, iy, iw, ih = cv2.boundingRect(all_points) cv2.rectangle(contour_img, (x + ix, y + iy), (x + ix + iw, y + iy + ih), (0, 0, 255), 2) # 빨간 박스 filtered_contours.append((x, y, w, h, None)) return filtered_contours, contour_img if __name__ == "__main__": image_path = 'path_to_image.png' # 이미지 경로 설정 letters, contour_img = extract_word_clusters(image_path) cv2.imshow('Highlighted Different Letter', contour_img) cv2.waitKey(0) # 키 입력 대기 cv2.destroyAllWindows() - Assistant
- User
원래 코드와 합쳐서 전체 코드를 작성해주세요.
- Assistant
- User
잘못된 결과를 출력합니다. 다른 추천 알고리즘은 없나요? 코드를 작성해주세요.
- Assistant
- User
다음 오류는 왜 발생하는걸까?
Traceback (most recent call last): File "/home/asitis/Coding/Toss/hangul.py", line 95, in result_img = find_different_image(letters, contour_img) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/asitis/Coding/Toss/hangul.py", line 84, in find_different_image max_diff_index = differences[0][1] # Get index of the most different image ~~~~~~~~~~~^^^ IndexError: list index out of range
- Assistant
- User
컨투어 추출 알고리즘을 살짝 변경했습니다. 다음 코드에 ORB를 적용하도록 코드를 다시 작성해주세요.
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) # 꼭짓점 색상 추출 (사각형의 네 꼭짓점) top_left = gray[y, x] top_right = gray[y, x + w - 1] bottom_left = gray[y + h - 1, x] bottom_right = gray[y + h - 1, x + w - 1] # 꼭짓점 색상이 특정 기준 이상인지 확인 if all(color > 250 for color in [top_left, top_right, bottom_left, bottom_right]): # 컨투어 내부만 크롭하여 다시 이진화 cropped_gray = gray[y:y+h, x:x+w] _, cropped_binary = cv2.threshold(cropped_gray, 200, 255, cv2.THRESH_BINARY_INV) # 내부 컨투어 찾기 internal_contours, _ = cv2.findContours(cropped_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 내부 컨투어들을 하나의 사각형으로 합치기 if internal_contours: all_points = np.vstack(internal_contours) ix, iy, iw, ih = cv2.boundingRect(all_points) cv2.rectangle(contour_img, (x + ix, y + iy), (x + ix + iw, y + iy + ih), (0, 0, 255), 2) # 빨간 박스 filtered_contours.append((x, y, w, h, None)) return filtered_contours, contour_img if __name__ == "__main__": image_path = 't1.png' # 이미지 경로 설정 letters, contour_img = extract_word_clusters(image_path) cv2.imshow('Highlighted Different Letter', contour_img) cv2.waitKey(0) # 키 입력 대기 cv2.destroyAllWindows() - Assistant