首页 文章

如何在OpenCV中绘制一组封闭的多边形曲线,将每个线段表示为不同的颜色(即在彩虹色空间中)?

提问于
浏览
1

我正在学习使用cv2.approxPolyDP函数将OpenCV轮廓分割成更简单更相关的曲线 . 我想为自己说明这一点,以便更好地了解正在发生的事情 . 我越来越近了,cv2.approxPolyDP函数(实现RDP算法)似乎正在工作,但绘制为轮廓时的输出似乎是一系列点而不是我预期的曲线 .

Feel free to contribute anything helpful.

这是我正在使用的test-pattern.png文件:
enter image description here

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)生成的曲线 . 通过这种方式,我可以看到所有连接的曲线形成轮廓 . 稍后我将需要对这些曲线执行一些操作,因此可视化它们可能非常有用 .

enter image description here

我最初在绘制轮廓时注意到的另一个有趣的事情是,如果我使用cv2.drawContours传递所有轮廓 cv2.drawContours(img3,contour,-1,(0,0,200),1) 我得到了形状的实体跟踪,以及框架的外边框:
enter image description here

另一方面,如果我选择表示形状本身的轮廓(而不是框架的外边框) cv2.drawContours(img3,contour[0],-1,(0,0,200),1) ,我得到了更多的虚线跟踪作为输出:
enter image description here

我想我没有完全处理drawContours函数在这里做的事情 .

1 回答

  • 1

    您得到虚线结果的原因是您将错误的数据类型传递给 drawContours 函数 . 近似是一个numpy数组,而函数需要一个列表 .

    这应该解决问题:

    cv2.drawContours(img3,[contour[0]],-1,(0,0,200),1)

    请注意,第二个参数现在是 [contour[0]]

相关问题