首页 文章

如何在分水岭分割后创建矢量多边形对象

提问于
浏览
2

在使用openCV-python对分割对象进行分水岭分割之后,我想获得矢量多边形对象(蓝色圆圈内的对象),但我不知道如何在opencv-python中进行分割 . 我附加了分水岭分割和图像的python代码 .

如何创建矢量多边形对象

import cv2
import numpy as np
import scipy.misc
import scipy.ndimage as snd
# image is read and is converted to a numpy array
img = cv2.imread('D:/exam_watershed/Example_2_medicine/Medicine_create_poly/medicine.jpg')
# image is convereted to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# binary thresholding is done using the threshold
# from Otsu's method
ret1,thresh1 = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# foreground pixels are determined by
# performing erosion
fore_ground = cv2.erode(thresh1,None,iterations = 3)
bgt = cv2.dilate(thresh1,None,iterations = 3)
ret,back_ground = cv2.threshold(bgt,1,100,1)
# marker is determined by adding foreground and background pixels
marker = cv2.add(fore_ground,back_ground)
# converting marker to 32 int
marker32 = np.int32(marker)
cv2.watershed(img,marker32)
m = cv2.convertScaleAbs(marker32) #the output is converted to unit8 image
ret3,thresh3 = cv2.threshold(gray,0,255,\
           cv2.THRESH_BINARY+cv2.THRESH_OTSU)
_, contours1, _= cv2.findContours(thresh3,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

b = cv2.drawContours(img,contours,-1,(0,255,0),thickness = 1,lineType = 8)
original image

image after watershed segmentation

1 回答

  • 4

    你很近,在找到轮廓后只需要几行:

    polys = []
    for cont in contours1:
        approx_curve = cv2.approxPolyDP(cont, 3, False)
        polys.append(approx_curve)
    cv2.drawContours(img, polys, -1, (0, 255, 0), thickness=1, lineType=8)
    cv2.imshow("medicine polygons", img)
    cv2.waitKey()
    

    The doc on approxPolyDP .

相关问题