【问题标题】:How to create vector polygon objects after watershed segmentation如何在分水岭分割后创建矢量多边形对象
【发布时间】:2015-02-24 03:20:28
【问题描述】:

使用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, 轮廓, -1, (0,255,0), 厚度=1, lineType=8)

【问题讨论】:

    标签: python opencv polygons


    【解决方案1】:

    你已经很接近了,只需要在找到轮廓后多几行:

    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 docapproxPolyDP

    【讨论】:

    • 感谢 Arnaud 的建议。但是,当我运行函数 approx_curve= cv2.approxPolyDP(cont, 3, False) 时出现错误:错误:(-215) npoints >= 0 && (depth == CV_32S || depth == CV_32F) in function cv::大约PolyDP。 countours 是 numpy 数组: [ 2 0 -1 -1] [ 3 1 -1 -1] [ 4 2 -1 -1]你能帮我解决一下吗?
    • 哼,你可能没有最新的 numpy 版本(1.9.1)。我已经使用 Opencv 2.4.8 和 3.0.0-beta 测试了该代码,在调整 cv2.findContours 的解包后工作正常。无论如何,我建议查看cont.dtype。正如错误消息所建议的,它应该是int32float32 类型。如果没有,您可以尝试在添加 from numpy import int32 之类的内容后将 cv2.approxPolyDP(cont, ...) 替换为 cv2.approxPolyDP(cont.astype(int32), ...)
    猜你喜欢
    • 2020-06-14
    • 2012-07-11
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多