물체의 경계선을 찾고 그리는 방법입니다.
contour의 좌표가 이미 있다면 (annotation이 있는 경우) cv2.drawContours에 좌표를 바로 넣으시면 됩니다.
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 이미지 로드
# 그레이스케일로 변환
img = cv2.imread("opencv/경계선검출/testimg.png", cv2.IMREAD_GRAYSCALE)
img_resize = cv2.resize(img, (450, 200))
img_resize_copy = img_resize.copy()
# 정확도를 높이기 위해 binary 이미지로 변환
# 픽셀의 밝기값이 125이상이면 255, 아니면 0
# 도형픽셀의 밝기가 116이기 때문
img_th = np.where((img_resize < 125), 255, 0).astype(np.uint8)
# contour 찾기
contours, hierarchy = cv2.findContours(img_th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# contour 그리기
draw_img = cv2.drawContours(img_resize, contours, -1, (0, 0, 255), 5)
# plotting
plt.subplot(121)
plt.imshow(img_resize_copy)
plt.axis('off')
plt.title('Original_img')
plt.subplot(122)
plt.imshow(draw_img)
plt.axis('off')
plt.title('Draw_img')
plt.show()
도움이 되셨다면 아무 광고나 클릭 한 번 부탁드립니다👍