NOTE: If you want to remove pygame dependency, you can go much lower level and access the Video 4 Linux 2 API directly using ioctl calls using Python's fcntl library.
import pygame
import pygame.camera as cm
1) Initialize pygame camera
cm.init()
2) Check if your device is listed
The device should have been listed before running the docker
docker run -it --device /dev/video0 ...In case it gets complicated to find devices, use --privileged and map all devices
docker run -it --privileged -v /dev:/dev ...To find the device folder in your machine (command line)
sudo apt-get install v4l-utils v4l2-ctl --list-devicesOUTPUT : Webcam C170 (usb-0000:00:14.0-4): /dev/video0
You can also list devices from pygame module
cm.list_cameras()
3) Set up the device
cam = cm.Camera(cm.list_cameras()[0])
4) Start camera and capture pictures
cam.start()
img = cam.get_image()
img
cam.stop()
5) Change the image to numpy array
Numpy should be installed separately
#Convert to numpy array
#The height and width are swapped
imgdata = pygame.surfarray.array3d(img)
imgdata
imgdata.shape
import matplotlib.pyplot as plt
%matplotlib inline
#image dimensions are swapped
plt.imshow(imgdata)
plt.imshow(imgdata.swapaxes(0,1)) #Can also use transpose (1,0,2)