Francesco Pegoraro
Francesco Pegoraro

Reputation: 808

OpenCV VideoCapture() on Ubuntu 17.04 not working

I'm trying to use OpenCV's cv2 python bindings on Ubuntu 17.04 and I can't seem to get VideoCapture to work properly. I'm doing a test with the code:

import cv2
import numpy as np
from matplotlib import pyplot as plt
cap = cv2.VideoCapture(0)
plt.ion()
while True:
    ret,image = cap.read()
    print(image)
    print(cap)
    im = np.array(image, dtype=float)
    plt.imshow(im)
    plt.pause(0.0005)
    plt.show()

and the result is

None
<VideoCapture 0x7f272f87adb0>
Traceback (most recent call last):
  File "cam.py", line 15, in <module>
    plt.imshow(im)
  File "/home/daniele/.local/lib/python3.5/site-packages/matplotlib/pyplot.py", line 3157, in imshow
    **kwargs)
  File "/home/daniele/.local/lib/python3.5/site-packages/matplotlib/__init__.py", line 1898, in inner
    return func(ax, *args, **kwargs)
  File "/home/daniele/.local/lib/python3.5/site-packages/matplotlib/axes/_axes.py", line 5124, in imshow
    im.set_data(X)
  File "/home/daniele/.local/lib/python3.5/site-packages/matplotlib/image.py", line 600, in set_data
    raise TypeError("Invalid dimensions for image data")
TypeError: Invalid dimensions for image data

and no window with video from webcam is opened.

If I don't use im = np.array(image, dtype=float) the error is the same but TypeError: Image data can not convert to float I have checked that my webcam is 0 in my system and I tryed it with 'Cheese' and it works. I have installed Opencv by pip3 install opencv-python

Upvotes: 1

Views: 2420

Answers (1)

ZdaR
ZdaR

Reputation: 22954

OpenCV already has some in-built utils for displaying images in a window using cv2.imshow(), using the OpenCV API you wont need to convert the image to np.array(). See if the following code works:

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    ret,image = cap.read()
    cv2.imshow("window", image)
    # Set the window delay time in milliseconds.
    cv2.waitkey(300)

Upvotes: 1

Related Questions