You can use v4l2loopback (https://github.com/umlaeute/v4l2loopback) for that. It is written in C but there are some python wrappers. I've used virtualvideo (https://github.com/Flashs/virtualvideo).
The virtualvideo README is pretty straight forward but here is my modification of their github example to match your goal:
import virtualvideo import cv2 class MyVideoSource(virtualvideo.VideoSource): def __init__(self): self.cam = cv2.VideoCapture(0) _, img = self.cam.read() size = img.shape #opencv 's shape is y,x,channels self._size = (size[1], size[0]) def img_size(self): return self._size def fps(self): return 30 def generator(self): while True: _, img = self.cam.read() yield img vidsrc = MyVideoSource() fvd = virtualvideo.FakeVideoDevice() fvd.init_input(vidsrc) fvd.init_output(2, 640, 480, pix_fmt = 'yuyv422') fvd.run()
in init_output the first argument is the virtual camera resource thar i've created when adding the kernel module:
sudo modprobe v4l2loopback video_nr = 2 exclusive_caps = 1
March 14, 2018 at 1:15 pm,March 15, 2017 at 6:21 pm,March 15, 2017 at 8:54 am,March 15, 2017 at 9:06 am
Now that you have your Raspberry Pi camera module installed, you need to enable it. Open up a terminal and execute the following command:
$ sudo raspi - config
And from there, I opened up a terminal and executed the following command:
$ raspistill - o output.jpg
Before installing picamera
, be sure to activate our cv
virtual environment:
$ workon cv
Open up a new file, name it test_image.py
, and insert the following code:
# 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() rawCapture = PiRGBArray(camera) # allow the camera to warmup time.sleep(0.1) # grab an image from the camera camera.capture(rawCapture, format = "bgr") image = rawCapture.array # display the image on screen and wait for a keypress cv2.imshow("Image", image) cv2.waitKey(0)
To execute this example, open up a terminal, navigate to your test_image.py
file, and issue the following command:
$ python test_image.py
Hey, Adrian! Thank you for this post, it’s wonderful.
I got an error while trying to execute test_image.py.
File "test_image.py", line 18, in
cv2.imshow("Image", image)
NameError: name 'image'
is not defined
I can see two things that might have went wrong here. First, make sure you are in your virtual environment when installing the picamera[array]
:
$ source~/.profile $ workon cv
Make sure you have installed the picamera[array]
library:
$ workon cv
$ pip install "picamera[array]"
$ python your_script.py
I have a feeling that you’re using picamera v1.11 and Python 2.7. Try downgrading to picamera v1.10 and this should resolve the blank/black frame issue:
$ pip uninstall picamera
$ pip install 'picamera[array]' == 1.10
Hi Adrian,
I got these errors when i executed “test_image.py ” code
File "/home/pi/.virtualenvs/cv/local/lib/python3.4/site-packages/picamera/encoders.py", line 534, in __init__
if not resize and format != 'yuv'
and input_port.name.startswith('vc.ril.video_splitter'):
TypeError: startswith first arg must be bytes or a tuple of bytes, not str
14th January, 2019: Initial version
from pygrabber.dshow_graph
import FilterGraph
graph = FilterGraph()
print(graph.get_input_devices())
from pygrabber.dshow_graph import FilterGraph from tkinter import Tk graph = FilterGraph() graph.add_input_device(0) graph.add_default_render() graph.prepare() graph.run() root = Tk() root.withdraw() # hide Tkinter main window root.mainloop()
from pygrabber.dshow_graph
import FilterGraph
import cv2
graph = FilterGraph()
cv2.namedWindow('Image', cv2.WINDOW_NORMAL)
graph.add_input_device(0)
graph.add_sample_grabber(lambda image: cv2.imshow("Image", image))
graph.add_null_render()
graph.prepare()
graph.run()
print("Press 'C' or 'c' to grab photo, another key to exit")
while cv2.waitKey(0) in [ord('c'), ord('C')]:
graph.grab_frame()
graph.stop()
cv2.destroyAllWindows()
print("Done")
import threading
import matplotlib.pyplot as plt
import numpy as np
from pygrabber.dshow_graph
import FilterGraph
class Camera:
def __init__(self, device_id):
self.graph = FilterGraph()
self.graph.add_input_device(device_id)
self.graph.add_sample_grabber(self.img_cb)
self.graph.add_null_render()
self.graph.display_format_dialog()
self.graph.prepare()
self.graph.run()
self.image_grabbed = None
self.image_done = threading.Event()
def img_cb(self, image):
self.image_grabbed = np.flip(image, 2)
self.image_done.set()
def capture(self):
self.graph.grab_frame()
def wait_image(self):
self.image_done.wait(1000)
return self.image_grabbed
print("Opening first camera")
camera1 = Camera(0)
print("Opening second camera")
camera2 = Camera(1)
input("Press ENTER to grab photos")
camera1.capture()
camera2.capture()
print("Waiting images")
image1 = camera1.wait_image()
image2 = camera2.wait_image()
print("Done")
ax1 = plt.subplot(2, 1, 1)
ax1.imshow(image1)
ax2 = plt.subplot(2, 1, 2)
ax2.imshow(image2)
plt.show()
Regsvr32 C: \Program Files(x86)\ Screen Capturer Recorder\ screen - capture - recorder.dll
Regsvr32 C: \Program Files(x86)\ Screen Capturer Recorder\ screen - capture - recorder - x64.dll
C: \Users\ Leica\ Programs\ python_grabber - master\ venv\ Scripts\ python.exe C: /Users/Leica / Programs / python_grabber - master / main.py
Exception in Tkinter callback
Traceback(most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.752.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1892, in __call__
return self.func( * args)
File "C:\Users\Leica\Programs\python_grabber-master\gui\MainWindow.py", line 166, in camera_properties
self.grabber.set_device_properties()
File "C:\Users\Leica\Programs\python_grabber-master\pygrabber\PyGrabber.py", line 94, in set_device_properties
self.graph.get_input_device().set_properties()
File "C:\Users\Leica\Programs\python_grabber-master\pygrabber\dshow_graph.py", line 99, in set_properties
show_properties(self.instance)
File "C:\Users\Leica\Programs\python_grabber-master\pygrabber\dshow_graph.py", line 592, in show_properties
OleCreatePropertyFrame(
File "_ctypes/callproc.c", line 997, in GetResult OSError: [WinError - 2147467259] Unspecified error
Hi, I am referring python_grabber module to access the cameras, I trying to get the camera properties using "set_device_properties()" from pygrabber module but I am facing the following issue " Hide Copy Code File "_ctypes/callproc.c", line 920, in GetResult OSError: [WinError - 2147467259] Unspecified error " Please solve this issue. Thanks in advance. regards, Thulasidass.V What I have tried: from pygrabber.PyGrabber import * from tkinter import Tk from pygrabber.dshow_graph import * import cv2 dass = PyGrabber(0) print(dass.get_video_devices()) print(dass.get_audio_devices()) print(dass.get_video_compressors()) print(dass.get_audio_compressors()) print(dass.get_asf_profiles()) print(dass.set_device(0)) print(dass.set_device_properties())
from gui.MainWindow
import *