2014-12-24 48 views
0

我有一個圖像,並且想要使用標記控制的分水嶺創建此圖像的多邊形分段。我寫了下面的代碼,但是我不能分離相互連接的對象並創建對象的多邊形。如何爲分水​​嶺分割創建多邊形

如何解決這些問題?非常感謝你的幫助。

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) 
res = scipy.misc.toimage(marker32) 
res.save('D:/exam_watershed/Example_2_medicine/Medicine_create_poly/res_output.png') 

original image

image after segment

回答

1

This question似乎是非常接近你的需求,因爲該示例使用完全相同的圖像作爲你的。

要將生成的「水壩」轉換爲多邊形,我建議在結果圖像上使用cv2.findContourscv2.approxPolyDP

+0

按照您的建議,我將分割圖像轉換爲二進制圖像,然後運行輪廓: _,contours1,_ = cv2.findContours(thresh3,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)。然後運行功能: DEF approxing(CNT)的: 背面= [] 閉合=真 爲CNT的CNT中: 小量= 10 CNT2 = cv2.approxPolyDP(CNT,ε,閉合) back.append(CNT2) 返回 c =近似(輪廓1)。並保存結果,image_out = cv2.imwrite('D:/contour2.jpg',c)。但它有錯誤圖像不是一個numpy或標量。如何解決這個問題?謝謝 – user30985