轮廓近似OpenCV

2024-09-25 10:32:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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的方式

提前谢谢!:)


Tags: importtrueimgforcv2opencv形状矩形
2条回答

使用近似值作为数组。我希望这能有帮助。

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

问题如下:

(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

相关问题 更多 >