JeremyKirkham
JeremyKirkham

Reputation: 1077

How to run opencv4nodejs VideoCapture inside a raspberry pi

I've added the opencv4nodejs library to my raspberry pi package, I'm trying to access the picam 2 video camera, but I keep getting the error "Error: VideoCapture::New - failed to open capture". The script I'm running is as following:

import * as cv from 'opencv4nodejs'

async function main() {
  const wCap = new cv.VideoCapture(0);
  const intvl = setInterval(() => {
    let frame = wCap.read();
    // loop back to start on end of stream reached
    if (frame.empty) {
      wCap.reset();
      frame = wCap.read();
    }
    console.log(frame);
  }, 0);
}

main()

FWIW, I'm running this inside docker on a raspberry pi 3b+, using resin.io to deploy the images.

Upvotes: 0

Views: 1695

Answers (3)

RobertMcReed
RobertMcReed

Reputation: 461

I followed the approach of @MForMarlon and @z Eyeland and set this up automatically each time the pi boots.

However, the instructions for running a script on boot did not work for me, so here is my combined solution:

1) Create a script at root: nano ~/setuppicamera.sh

#!/bin/bash
sudo modprobe bcm2835-v4l2
  • Save the script by pressing ctrl-x and then y and then enter

2) Make the script executable: chmod +x ~/setuppicamera.sh

3) Add the script to the desktop autostart file:

  • Open the autostart file: sudo nano ~/.config/lxsession/LXDE-pi/autostart
  • Create a new line above @xscreensaver -no-splash and add @/home/pi/setuppicamera.sh
  • Save the file: ctrl-x then y then enter

Now every time you reboot you should be able to access the picamera at source 0.

To test that it worked, reboot your pi with sudo reboot and then run v4l2-ctl --list-devices. You should see output along the lines of:

mmal service 16.1 (platform:bcm2835-v4l2):
    /dev/video0

If you instead see Failed to open /dev/video0: No such file or directory something went wrong. Double check the steps above and try again. Note that your picamera must be connected at the time of boot for this script to work properly.

Upvotes: 0

sirshakir
sirshakir

Reputation: 139

Here the neat commands I run every-time I boot up the pi

 #!/bin/bash
 cd 
 cd /dev
 sudo modprobe bcm2835-v4l2
 v4l2-ctl --list-devices

Upvotes: 2

MForMarlon
MForMarlon

Reputation: 861

Have you tried running

sudo modprobe bcm2835-v4l2

on the pi before your script runs? Otherwise, opencv will not properly recognize your picam.

Upvotes: 2

Related Questions