Python/영상처리

[OpenCV] 영역 검출

헬로희 2023. 11. 19. 22:15
728x90

 

# 이미지 불러오기
img = cv2.imread(img_path, cv2.IMREAD_COLOR)

# 영역추출 전 Gray color로 변환
gray = cv2.cvtCOLOR(img, cv2.COLOR_BGR2GRAY)

#임계값을 구하고 binary 이미지로 변환
ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)
binary = cv2.bitwise_not(binary)

binary_cp = binary.copy()
h,w = binary.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)

#특징 추출
cv2.floodFill(binary_cp, mask, (0,0),255)
binary_cp_inv = cv2.bitwise_not(binary_cp)
feature_img = binary | binary_cp_inv

# 매끄럽지 않기 때문에 
# erosion과 dilation을 이용하여 이미지를 채워줌

# blank image
blk_img = np.zeros((img.shape[0], img.shape[1],3), np.uint8)

# 외곽선 검출
contours, hierachy = cv2.findContours(feature_img, cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

idx = 0 
for cnt in contours:
    idx += 1
    cv2.drawContours(blk_img, [cnt], 0,(255,255,255), thickness=cv2.FILLED)


kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
dilation = cv2.dilate(blk_img,kernel,iterations = 2)
new_feature_img = cv2.erode(dilation,kernel,iterations = 2)

                             원본                                                       특징추출                                                 dilation, erosion후

 

 

728x90