본문 바로가기

인공지능/Python

원본 이미지와 마스크 이미지 합성(with opacity)

Problem

Image segmentation 결과인 mask를 원본 이미지위에 투명도를 줘서 segment를 확인할 수 있게끔 하려고함.

근데 cv2.drawContours에는 opacity를 줄 수 없기 때문에 찾아보니 cv2.addWeighted를 이용해서 원본이미지 위에 덮어 씌우는 방식으로 해결

 

Solution

# get input image
origin = self.get_origin_image()
# get score of segment
score = self.get_score()
# get mask of segment
masks = self.get_masks()

# black mask for fill polygon
blank_mask = np.zeros(origin.shape)


# draw outline and polygon
for j in range(len(score)):
	# set threshold
    if score[j] < threshold :
        continue
    # get contours
    contours, hierarchy = cv2.findContours(masks[j], cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
    # draw solid outline
    cv2.drawContours(origin, [contours[0]], 0, self.colors[j], 2)
    # draw fill polygon
    cv2.drawContours(blank_mask, [contours[0]], 0, self.colors[j], -1)
    
# add opacity in polygon
origin = cv2.addWeighted(origin, 0.6, blank_mask, 0.4, 0.0,dtype = cv2.CV_8U)