Search code examples
pythonpython-3.xcameraraspberry-piraspbian

can't capture image by raspberry pi camera in python


I have a problem when trying to take an image with a Raspberry Pi camera.

When I execute this code:

import sys

sys.path.append('/usr/local/lib/python3.4/site-packages')
import cv2
import numpy as np
import detect
cap = cv2.VideoCapture(0)

while(True):
    ret, frame = cap.read()
    img = detect.detect(frame)

    cv2.imshow('frame',img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()

I get the error:

Traceback (most recent call last):
...
...
...
TypeError: 'NoneType' object is not subscriptable

I searched to solve this problem and found a command to enter in terminal:

sudo modprobe bcm2835-v4l2

It solves the problem momentarily, but it appears again after I restart the Raspberry Pi.

Please help me to solve this problem.


Solution

  • Edit the file /etc/modules (as root) and add the bcm2835-vl42 line like this:

    # This file contains the names of kernel modules that should be loaded
    # at boot time, one per line. Lines beginning with "#" are ignored.
    
    
    # v4l2 added for OpenCV video capture
    bcm2835-v4l2