Refer GCP/Docker/docker-webcam for more details

In [1]:
import pygame
import pygame.camera as cm
pygame 1.9.4
Hello from the pygame community. https://www.pygame.org/contribute.html
In [2]:
cm.init()
In [3]:
cm.list_cameras()
Out[3]:
['/dev/video0']
In [4]:
cam = cm.Camera(cm.list_cameras()[0])
In [5]:
cam.start()
In [6]:
img = cam.get_image()
In [7]:
img
Out[7]:
<Surface(640x480x24 SW)>
In [8]:
cam.stop()
In [9]:
#Convert to numpy array
#The height and width are swapped
imgdata = pygame.surfarray.array3d(img)
In [10]:
imgdata
Out[10]:
array([[[155, 182, 177],
        [155, 177, 174],
        [158, 178, 178],
        ...,
        [ 60,  56,  31],
        [ 60,  56,  29],
        [ 58,  57,  29]],

       [[156, 183, 178],
        [157, 179, 176],
        [155, 175, 175],
        ...,
        [ 61,  57,  32],
        [ 61,  57,  30],
        [ 58,  57,  29]],

       [[154, 181, 172],
        [158, 181, 175],
        [162, 179, 180],
        ...,
        [ 59,  57,  34],
        [ 59,  57,  34],
        [ 58,  57,  36]],

       ...,

       [[ 30,  24,  26],
        [ 30,  24,  26],
        [ 33,  24,  27],
        ...,
        [ 26,  23,  14],
        [ 27,  24,  15],
        [ 24,  24,  16]],

       [[ 32,  23,  26],
        [ 33,  24,  27],
        [ 32,  23,  26],
        ...,
        [ 27,  24,  15],
        [ 26,  23,  14],
        [ 26,  23,  14]],

       [[ 32,  23,  26],
        [ 31,  22,  25],
        [ 31,  22,  25],
        ...,
        [ 27,  24,  15],
        [ 26,  23,  14],
        [ 26,  23,  14]]], dtype=uint8)
In [11]:
imgdata.shape
Out[11]:
(640, 480, 3)
In [12]:
import matplotlib.pyplot as plt
%matplotlib inline
In [13]:
#image dimensions are swapped
plt.imshow(imgdata)
Out[13]:
<matplotlib.image.AxesImage at 0x7fb7cfb9b1d0>
In [14]:
plt.imshow(imgdata.swapaxes(0,1)) #Can also use transpose (1,0,2)
Out[14]:
<matplotlib.image.AxesImage at 0x7fb7cfb92080>