가장 커다란 contour를 탐색 코드
import cv2 as cv
import numpy as np
# 입력영상을 이진영상으로
input = 'C:/Users/yauaz/Desktop/4-1/Computer_Vision/CV_HW/HW4/hw4.jpg'
rate=0.2
src = np.array([[50, 50], [300, 50], [50,400], [300, 400]], dtype=np.float32)
A4_SIZE_X, A4_SIZE_Y =525, 375
img = cv.imread(input)
img_copy = cv.resize(img, (0,0), fx=rate, fy=rate,interpolation=cv.INTER_AREA)
gray = cv.cvtColor(img_copy, cv.COLOR_BGR2GRAY)
_, binary = cv.threshold(gray, 200, 255, cv.THRESH_BINARY)
# contour 탐색
contours, _ = cv.findContours(binary,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
contour_image = img_copy.copy()
cv.drawContours(contour_image, contours, -1, (0, 255, 0), 3)
largest_contour = max(contours, key=cv.contourArea)
contour_image2 = img_copy.copy()
cv.drawContours(contour_image, [largest_contour], -1, (0, 0, 255), 3)
#cv.imshow('Contours', contour_image2)
# contour의 corner점 순서에 따라 수정
#dst = np.array([[0, 0], [A4_SIZE_X-1, 0], [0, A4_SIZE_Y-1], [A4_SIZE_X-1, A4_SIZE_Y-1]], dtype=np.float32)
# 행렬 추정 및 warping
#( Hint getPerspectiveTransform 함수 사용 )
#( Hint warpPerspective 함수 사용 )
#M = cv.getPerspectiveTransform(src, dst)
#cv.imshow('binary',binary)
#cv.imshow('gray',gray)
cv.imshow('contour',contour_image)
cv.waitKey(0)
cv.destroyAllWindows()
가장 커다란 contour를 직사각형으로 보이게 하는 코드
import cv2 as cv
import numpy as np
# 입력 이미지 경로 설정
input_path = 'C:/Users/yauaz/Desktop/4-1/Computer_Vision/CV_HW/HW4/hw4.jpg'
rate = 0.2
A4_SIZE_X, A4_SIZE_Y = 525, 375 # A4 용지 크기
# 이미지 읽기 및 사이즈 조정
img = cv.imread(input_path)
img_resized = cv.resize(img, (0, 0), fx=rate, fy=rate, interpolation=cv.INTER_AREA)
# 그레이스케일 변환 및 이진화
gray = cv.cvtColor(img_resized, cv.COLOR_BGR2GRAY)
_, binary = cv.threshold(gray, 200, 255, cv.THRESH_BINARY)
# 컨투어 찾기
contours, _ = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
largest_contour = max(contours, key=cv.contourArea)
# 가장 큰 컨투어의 꼭짓점 찾기
epsilon = 0.02 * cv.arcLength(largest_contour, True)
approx_corners = cv.approxPolyDP(largest_contour, epsilon, True)
if len(approx_corners) == 4:
src = np.array([point[0] for point in approx_corners], dtype=np.float32)
# 목표 꼭짓점 위치 설정
dst = np.array([[A4_SIZE_X-1, A4_SIZE_Y-1], [A4_SIZE_X-1, 0], [0, 0], [0, A4_SIZE_Y-1]], dtype=np.float32)
# Homography 행렬 계산
M = cv.getPerspectiveTransform(src, dst)
# 이미지 변환
transformed = cv.warpPerspective(img_resized, M, (A4_SIZE_X, A4_SIZE_Y))
# 결과 이미지 출력
cv.imshow('Transformed', transformed)
cv.waitKey(0)
cv.destroyAllWindows()
else:
print("적절한 모서리를 찾지 못했습니다.")
세요