2017-06-05 147 views
0

http://docs.opencv.org/trunk/d4/d73/tutorial_py_contours_begin.html 提供的示例之后,我在Spyder环境中使用python绘制二进制图像中检测到的组件的轮廓。我的代码是在这里:OpenCV:在二进制图像中绘制对象的轮廓

im = cv2.imread('test.jpg') #raw RGB image 
im2 = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) #gray scale image 
plt.imshow(im2,cmap = 'gray') 

图片如下:

enter image description here

然后,

thresh, im_bw = cv2.threshold(im2, 127, 255, cv2.THRESH_BINARY) #im_bw: binary image 
im3, contours, hierarchy = cv2.findContours(im_bw,cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) 
cv2.drawContours(im2, contours, -1, (0,255,0), 3) 
plt.imshow(im2,cmap='gray') #without the code, only an array displayed in the console 

这些代码不会给人以轮廓出于某种原因身影。但是,如果我改变代码的最后两行如下:

cv2.drawContours(im, contours, -1, (0,255,0), 3) 
plt.imshow(im,cmap='gray') 

它产生与轮廓图:

enter image description here

我感到困惑,这些代码是如何工作的? cv2.drawCoutours仅适用于GRB图像吗?希望不是。 此外,应当注意,轮廓[0]给出一个三维阵列:

idx = contours[0] 
print idx.shape 

(392L, 1L, 2L) 

的IDX应储存所有轮廓点的像素坐标。但是如何解释每个维度代表什么,并从中获得每个轮廓点的像素坐标?然后,我可以使用这些坐标绘制轮廓而不诉诸于cv2.drawContours

回答

0

cv2.findContours和cv2.drawContours都是破坏性方法,它们修改原始输入图像,而后者仅适用于绘制RBG图像,这解释了在绘制的灰度图像中不显示可见轮廓。

除了cv2.drawContours之外,还可以使用存储在cv2.findContours获得的“等高线”(在上面的代码中)中存储的边界像素索引来轻松绘制等高线。