如何在OpenCV中绘制一个闭合的多边形曲线集,使用不同颜色表示每个段(如彩虹色空间)?
我正在学习如何使用cv2.approxPolyDP这个函数,把OpenCV中的轮廓分割成更简单、更相关的曲线。为了更好地理解这个过程,我想自己做个示例。现在我快要搞明白了,这个cv2.approxPolyDP函数(实现了RDP算法)似乎在正常工作,但当我把结果画出来时,看到的却是一系列的点,而不是我期待的曲线。
欢迎大家提供任何有帮助的建议。
这是我使用的test-pattern.png文件:
import numpy as np
import cv2, cv
#read the test image - this one happens to be binary
img = cv2.imread("test-pattern.png",0)
#invert the image
img2 = cv2.bitwise_not(img)
cv2.imshow("after bitwise not",img2)
#find the contours of the image
contour,hier = cv2.findContours(img,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
#make a color image of the same size for displaying contours later on .... img3 and img4
height, width = img.shape # binary image is height, width; otherwise would be height, width, depth
img3 = np.zeros((height,width,3), np.uint8)
img4 = np.zeros((height,width,3), np.uint8)
#draw contours on the color image
cv2.drawContours(img3,contour[0],-1,(0,0,200),1)
cv2.imshow("contours",img3)
#print a bunch of stuff to the command line for diagnostic purposes
print "contour vector length: ", len(contour), "\n hier length: ", len(hier)
print "contour area: ", cv2.contourArea(contour[0])
print "canvas area: ", height*width
print "bounding rect: ", cv2.boundingRect(contour[0])
#get the RDP curve vector, and try to display it as a contour on img4
#I chose an epsilon value of 1.1 ... it can be tweaked later
#It will be best to draw these curves in a rainbow colorspace so I can see them
print "RDP curve:", cv2.approxPolyDP(contour[0], 1.1, 1)
print "RDP curve length: ", len(cv2.approxPolyDP(contour[0], 1.1, 1))
cv2.drawContours(img4,cv2.approxPolyDP(contour[0], 1.1, 1),-1,(0,90,200),1)
cv2.imshow("contours",img4)
cv2.waitKey(0)
这里是最后一段代码生成的输出的一个裁剪部分。我裁剪了它,这样你可以看到点的分布。我不太习惯通过OpenCV处理曲线,但为了更好地理解,我想把RDP算法(cv2.approxPolyDP)生成的曲线用某种彩虹色的方式展示出来。这样我就能看到所有的独立曲线是如何连接在一起形成轮廓的。之后我还需要对这些曲线进行一些操作,所以可视化它们会非常有用。
还有一个有趣的事情是,当我最开始绘制轮廓时,如果我使用cv2.drawContours函数,把所有的轮廓都传进去 cv2.drawContours(img3,contour,-1,(0,0,200),1)
,我得到了形状的实线轮廓,以及框架的外边界:
但如果我只选择代表形状本身的轮廓(而不是框架的外边界) cv2.drawContours(img3,contour[0],-1,(0,0,200),1)
,我得到的输出就像是点状的轮廓:
我想我还没有完全理解drawContours这个函数的作用。
1 个回答
你看到的点状结果是因为你传给 drawContours
函数的数据类型不对。这个近似值是一个 numpy 数组,而这个函数需要的是一个列表。
这样做应该能解决问题:
cv2.drawContours(img3,[contour[0]],-1,(0,0,200),1)
注意,现在第二个参数变成了 [contour[0]]