Opencv raspicam

时间:2016-02-14 15:49:50

标签: python opencv raspberry-pi2 haar-classifier

您好我想运行此代码来检测使用带有OpenCV的树莓派B上的raspicam但是遇到错误的汽车。

import numpy as np
import cv2

car_cascade = cv2.CascadeClassifier('cars3.xml')
cap = cv2.VideoCapture(0)

while 1:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cars = car_cascade.detectMultiScale(gray, 1.3, 5)

    for (x,y,w,h) in cars:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]

    cv2.imshow('img',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

运行代码后返回

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/pi/installopencv/opencv-3.1.0/modules/imgproc/src/color.cpp, line 8000
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: /home/pi/installopencv/opencv-3.1.0/modules/imgproc/src/color.cpp:8000: error: (-215) scn == 3 || scn == 4 in function cvtColor

是否发生了错误,因为我使用的是raspicam和&#34; cap = cv2.VideoCapture(0)&#34;只适用于网络摄像头?我尝试启用V4L2模块,但它也没有工作

1 个答案:

答案 0 :(得分:0)

如果您想使用Raspberry PI相机模块,请使用picamera模块获取帧,而不是OpenCV'2 videoCapture模块。特别是您希望安装具有阵列支持的模块:

pip install "picamera[array]"

这将允许您轻松地将帧传递给OpenCV。 有关如何从头开始here的非常好的教程 这是它的要点:

# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2

# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640, 480))

# allow the camera to warmup
time.sleep(0.1)

# capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
    # grab the raw NumPy array representing the image, then initialize the timestamp
    # and occupied/unoccupied text
    image = frame.array

    # show the frame
    cv2.imshow("Frame", image)
    key = cv2.waitKey(1) & 0xFF

    # clear the stream in preparation for the next frame
    rawCapture.truncate(0)

    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break

在您的情况下,您可能希望将格式从"rgb"更改为"yuv"。 这样,您可以直接提取y(光度)通道,这将是您的灰度方法。希望你不需要进行色彩空间转换(从BGR到灰度)并从CSI(而不是USB)获取帧,从而获得速度的小幅提升。