0

我使用 python 和 opencv3 对直播中最大的图像进行轮廓处理,看起来我的代码出错了,谁能帮帮我

import cv2,platform
import numpy as np

def larger(x):
    gray = cv2.cvtColor(x, cv2.COLOR_BGR2GRAY)
    image = cv2.Canny(gray,35,200)
    (_,cnts,_) = cv2.findContours(image.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    c = max(cnts, key=cv2.contourArea)
    return cv2.minAreaRect(c)
capture = cv2.VideoCapture(0)
retval, im = capture.read()
y = larger(im)
box = np.int0(cv2.boxPoints(y))
cv2.drawContours(im,[box],-1,(0,255,0),2)
cv2.imshow("Image",im)
cv2.waitKey(0)
cv2.destroyAllWindows()

这段代码有两个问题:

1) is my web cam was on but cant see any video image, getting this error

    "Traceback (most recent call last):
      File "C:\Users\Snehith\Desktop\project vision\cnt.py", line 14, in <module>
        y = larger(im)
      File "C:\Users\Snehith\Desktop\project vision\cnt.py", line 8, in larger
        c = max(cnts, key=cv2.contourArea)
    ValueError: max() arg is an empty sequence"
2) i want a continuous video stream along with the contour, please explain the mistakes and also solutions in python and opencv 
4

1 回答 1

0

我只需要对你的代码做两个小改动:

1.) 您可以检查 capture.isOpened() 以查看是否连接了相机。

2.) 我已经包含了一个 while 循环,这样你就可以连续拉帧直到按下“q”。

import cv2,platform
import numpy as np

def larger(x):
    gray = cv2.cvtColor(x, cv2.COLOR_BGR2GRAY)
    image = cv2.Canny(gray,35,200)
    (_,cnts,_) = cv2.findContours(image.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    c = max(cnts, key=cv2.contourArea)
    return cv2.minAreaRect(c)

capture = cv2.VideoCapture(0)

if capture.isOpened():
    while(True):
        retval, im = capture.read()
        y = larger(im)
        box = np.int0(cv2.boxPoints(y))
        cv2.drawContours(im,[box],-1,(0,255,0),2)
        cv2.imshow("Image",im)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            capture.release()
            break

else:
    print "No camera detected."


cv2.destroyAllWindows()    

您可能会发现 OpenCV Python 教程对类似问题很有帮助,这里是 pdf 版本的链接: https ://media.readthedocs.org/pdf/opencv-python-tutroals/latest/opencv-python-tutroals.pdf

于 2016-04-03T17:51:17.567 回答