cv2.connectedComponents()标注一幅图像,并观察标注的效果

cv2.connectedComponents()标注一幅图像,并观察标注的效果

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)

    plt.subplot(131)
    plt.imshow(ishow)
    plt.axis('off')
    plt.subplot(132)
    plt.imshow(fore)
    plt.axis('off')
    plt.subplot(133)
    plt.imshow(markers)
    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)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qestion_yz_10086/article/details/107914736