cv2.connectedComponents()标注一幅图像,并对其进行修正,使未知区域被标注为0,并观察标注的效果
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
def read_img(img_7_path,img_8_path):
img=cv2.imread(img_7_path)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
ishow=img.copy()
ret,thresh=cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
kernel=np.ones((3,3),np.uint8)
opening=cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel,iterations=2)
bg=cv2.dilate(opening,kernel,iterations=3)
dist=cv2.distanceTransform(opening,cv2.DIST_L2,5)
ret,fore=cv2.threshold(dist,0.7*dist.max(),255,0)
fore=np.uint8(fore)
ret,markers=cv2.connectedComponents(fore)
foreAdv=fore.copy()
unkown=cv2.subtract(bg,foreAdv)
ret,markers2=cv2.connectedComponents(foreAdv)
markers2=markers+1
markers2[unkown==255]=0
plt.subplot(121)
plt.imshow(markers)
plt.axis('off')
plt.subplot(122)
plt.imshow(markers2)
plt.axis('off')
plt.show()
if __name__ == '__main__':
work_path = os.getcwd()
data_path = os.path.join(work_path, 'data')
img_7_path = os.path.join(data_path, '7.jpg')
img_8_path = os.path.join(data_path, '8.jpg')
read_img(img_7_path,img_8_path)