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

标签 python opencv polygons

在使用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), thickness=1, lineType=8) original image

image after watershed segmentation

最佳答案

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

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 上。

关于python - 如何在分水岭分割后创建矢量多边形对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27663455/

相关文章:

python - 使用 SpaCy DisplaCy 可视化自定义 IOB 标签

python - 可以安全地假设(并教导)Python 字典将保持有序吗?

查找包围点的多边形的算法 - 仅定义线

python - Pandas : extracting column1's value at column2th position

python - Fabric 任务的返回值

C++ ffmpeg实时视频传输

c++ - Matlab的filter2在OpenCV中的等效函数

opencv - OpenCV MultiBandBlender无法正常工作

android - 如何从位图区域获取多边形形状

opengl - 如何在OpenGL中绘制2D不规则曲线形状