OpenCV中的轮廓近似问题

3

我正在使用PythonOpenCV。 对于不好的形状,我们使用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()

这是结果的样子:

糟糕的矩形

这是我想要的效果:

期望输出

提前感谢! :)
2个回答

4
问题如下:
(1)图片质量太差,我不得不将arcLength()*0.1减少至arcLength()*0.08
(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


_, cnts = cv2.findContours(edge.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 数值错误:拆包过多(期望 2 个) 如何解决它!!! - venkat

3
请使用approx数组。希望这能帮到你。
cv2.drawContours(im,[approx],-1,(0,255,0),3)

4
解释回答如何解决原帖者的问题是有益的。 - cb4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接