python - 在 python 中使用 cv2.approxPolyDP() 绘制轮廓

标签 python image opencv computer-vision opencv3.0

我无法使用 cv2.approxPolyDP() 绘制形状的完整轮廓。

我得到以下结果:

My result

但我想要这样的输出:

This is what I'm looking for

这是我的代码:

import cv2
im = cv2.imread('C:\Python27\Test\Targets\s1.jpg') # read picture

imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) # BGR to grayscale

ret, thresh = cv2.threshold(imgray, 200, 255, cv2.THRESH_BINARY)

countours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

epsilon = 0.1 * cv2.arcLength(countours[0], True)
approx = cv2.approxPolyDP(countours[0], epsilon, True)

cv2.drawContours(im, approx, -1, (0, 255, 0), 3)
cv2.imshow("Contour", im)

cv2.waitKey(0)
cv2.destroyAllWindows()

最佳答案

cv2.CHAIN_APPROX_SIMPLE 去除所有冗余点并压缩轮廓,从而节省内存。如果您传递给 findContours() 函数 cv2.CHAIN_APPROX_NONE 参数而不是 cv2.CHAIN_APPROX_SIMPLE,您的问题将得到解决。 您的代码应更改如下:

_, countours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, 
                                                 cv2.CHAIN_APPROX_NONE)

关于python - 在 python 中使用 cv2.approxPolyDP() 绘制轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41576815/

相关文章:

RGB 相当于 R 中的 image() 函数?

python - 如何从视频中提取 ROI - 将不相关的像素涂黑

c++ - 从 cpp 文件创建头文件 .h

python - 从 pandas DataFrame 中的日期时间列中提取月份

python - 如何将多列重新排列成具有相同索引的一列

python - 从可用数据结构生成二元决策图

c++ - 错误:使用已删除的函数 std::basic_ofstream(OpenCV 和 C++11)

python - Django 可以与 pandas 和 numpy 一起很好地工作吗?

javascript - 使用计算机的时钟每分钟更改一次图像以计时更改

css - 具有多种背景选择的响应图像