我用python和opencv3在直播中绘制了最大的图像,看起来我的代码出了问题,有人能帮我吗



我使用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. 是我的网络摄像头打开了,但看不到任何视频图像,得到这个错误

    Traceback (most recent call last):
      File "C:UsersSnehithDesktopproject visioncnt.py", line 14, in <module>
        y = larger(im)
      File "C:UsersSnehithDesktopproject visioncnt.py", line 8, in larger
        c = max(cnts, key=cv2.contourArea)
    ValueError: max() arg is an empty sequence
    
  2. 我想要一个连续的视频流和轮廓,请解释python和opencv 中的错误和解决方案

我只需要对您的代码做两个小的更改:

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

最新更新