首页 > 解决方案 > 无法使用网络摄像头在 RaspberryPi 中执行实时视频处理

问题描述

我编写了一个代码来使用RaspberryPi 3B+中的网络摄像头( Logitech C310 HD 网络摄像头)检测白色。代码将执行以下功能:

  1. 使用捕获视频cv2.VideoCapture (0)

  2. 抓取视频的每一帧并在该帧中寻找白色物体。

  3. 如果该帧中存在白色对象,代码将包围它并打印白色。

  4. 真实视频和处理后的视频将使用cv2.imshow('frame',frame1) and cv2.imshow('res',res1).

代码如下所示:

import cv2
import numpy as np
from time import sleep 

cap1 = cv2.VideoCapture(0)
cap1.set(3,640)
cap1.set(4,480)
cap1.set(5,15)


    while(1):

    _, frame1 = cap1.read()
    #hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of white color in HSV
    # change it according to your need !
    lower_white = np.array([150,150,150], dtype=np.uint8)
    upper_white = np.array([255,255,255], dtype=np.uint8)

    # Threshold the HSV image to get only white colors
    mask1 = cv2.inRange(frame1, lower_white, upper_white)

    kernal = np.ones((5, 5), "uint8")

    # Tracking the Red Color
    (_, contours1, hierarchy) = cv2.findContours(mask1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    for pic, contour1 in enumerate(contours1):
        area1 = cv2.contourArea(contour1)
        #start = time.time()
        if (area1 > 1200):
            print 'white in cam 1'




            #x, y, w, h = cv2.boundingRect(contour)
            #img = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
            ellipse1 = cv2.fitEllipse(contour1)
            cv2.ellipse(frame1, ellipse1, (0, 255, 0), 2)
            #cv2.putText(frame, "RED color", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255))


    red = cv2.dilate(mask1, kernal)

    # Bitwise-AND mask and original image
    res1 = cv2.bitwise_and(frame1,frame1, mask= mask1)

    cv2.imshow('frame',frame1)
    cv2.imshow('res',res1)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cap1.release()
cv2.destroyAllWindows()

我的问题是几个月前,这段代码实时运行良好。但是现在当我再次尝试运行相同的代码时,我的视频没有实时运行,但存在巨大的时间延迟。例如,当相机前面有一个白色物体时,需要几分钟才能将其显示为白色。过去,当我运行此代码时,视频帧窗口出现没有任何时间延迟,但现在帧窗口会在几分钟后出现。

请向我解释如何解决这个问题?为什么过去相同的代码可以工作,但现在不行?是python2还是python3还是RaspberryPi的问题?

标签: pythonraspberry-pi3webcamvideo-processingopencv3.0

解决方案


推荐阅读