How can I take snapshots from a webcam in ruby? I know the webcam device is on /dev/video0, but how do I get a picture from it?
6 Answers
I'm the developer of Hornetseye. You can capture images with the V4L2-interface of HornetsEye as follows.
require 'rubygems'
require 'hornetseye_v4l2'
require 'hornetseye_xorg'
require 'hornetseye_rmagick'
include Hornetseye
input = V4L2Input.new '/dev/video0'
img = X11Display.show { input.read }
img.to_ubytergb.save_ubytergb 'test.png'
Currently supported colourspaces are UYVY, YUYV, YUV420, GREY, RGB24. Note that other colourspaces such as MJPEG are not supported at the moment.

- 2,781
- 28
- 25
-
The gem is [`hornetseye-v4l2`](https://rubygems.org/gems/hornetseye-v4l2) – Dorian Oct 08 '16 at 21:42
-
But this doesn't work on macOS, and the OpenCV example works: http://stackoverflow.com/a/39938139/407213 – Dorian Oct 08 '16 at 22:44
-
@Dorian yes, that's correct. It only works under GNU/Linux. – wedesoft Oct 18 '16 at 21:36
-
This is a very interesting project. When I see efforts like this, I wish ruby hype train was still running. – nurettin Feb 12 '17 at 15:04
-
@nurettin Thanks – wedesoft Mar 21 '17 at 12:23
I've never actually used it but hornetseye looks good. This question has also already been asked here
-
I've been trying to use hornetseye, but it doesn't seem to fully work. – Malfist Jan 15 '10 at 17:30
The Video4Linux API involves sending special ioctls to the /dev/video*
device, with data in packed structures; not something easy to do from Ruby. (It's not all that much fun from C, either.)
ruby-v4l is an extension library for capture pictures in Ruby using Video4Linux.
Orphaned in Debian because its maintainer hasn't been active since 2005, so if it doesn't work I don't think you'll be able to get much support.
A more modern solution would probably be to create proper libv4l binding for Ruby. However, I don't know of any present work on that.

- 198,619
- 38
- 280
- 391
With the ruby-opencv
gem:
require "opencv"
capture = OpenCV::CvCapture.open
sleep 1 # Warming up the webcam
capture.query.save("image.jpg")
capture.close
And to install OpenCV on macOS: brew install homebrew/science/opencv --HEAD
.

- 22,759
- 8
- 120
- 116
I've written a small wrapper-gem for the new OpenCV since ruby-opencv is stuck at OpenCV2, which isn't available on some modern systems. It should work on both macOS and Linux, provided OpenCV is installed.
Here it is: https://github.com/khasinski/framegrabber
In your case it would be:
Framegrabber.open(0) # 0 is the device id
image = Framegrabber.grab_image # Gets you a Magick::Image object
Framegrabber.release # turns off the webcam

- 2,965
- 2
- 25
- 34