user30985
user30985

Reputation: 683

How to create vector polygon objects after watershed segmentation

After watershed segmentation using openCV-python to segment objects , I would like to get vector polygon objects (objects inside the blue circle) but I don't know how to do it in opencv-python. I attached the python code of the watershed segmentation and the image.

How to create vector polygon objects

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

Upvotes: 3

Views: 1608

Answers (1)

Arnaud P
Arnaud P

Reputation: 12617

You are close, just need a few more lines after finding the contours:

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.

Upvotes: 4

Related Questions