轮廓逼近OpenCV

时间:2015-11-27 13:58:28

标签: python opencv

我正在使用opencv for python。对于糟糕的形状,我们使用approxpolyDP()。为此,我创建了一个错误的矩形(添加到帖子中)

使用它时,我只得到2个点而不是正确的矩形。

任何人都可以帮助我为什么会这样吗?

import cv2
import numpy as np

im = cv2.imread("badrect.png")
img = im
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
canny = cv2.Canny(img,100,200)


(_,cnts,_) = cv2.findContours(canny,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)

cnt = cnts[0]

epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)

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

cv2.imshow("img",im)
cv2.waitKey(0)
cv2.destroyAllWindows()

这就是结果的样子。Bad rectangle 我希望它以desired output

的形式出现

提前致谢! :)

2 个答案:

答案 0 :(得分:2)

使用约作为数组。我希望这会有所帮助。

cv2.drawContours(im,[approx],-1,(0,255,0),3)

答案 1 :(得分:1)

问题如下:

(1)image非常糟糕,我必须减少arcLength()*0.08而不是arcLength()*0.1;

(2)你混淆了im和img,小心。

import cv2
import numpy as np
from matplotlib import pyplot as plt

path = "/Users/summing/Desktop/skM2L.jpg"
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

(ret, thresh) = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
edge = cv2.Canny(thresh, 100, 200)
(cnts, _) = cv2.findContours(edge.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)


total = 0
for c in cnts:
    epsilon = 0.08 * cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, epsilon, True)

    cv2.drawContours(img, [approx], -1, (0, 255, 0), 4)
    total += 1

print "I found {0} RET in that image".format(total)
cv2.imshow("Output", img)
cv2.waitKey(0)
exit()

代码工作找到了我。希望它有所帮助。这是result