Search code examples
pythonopencvraspberry-pi

Cannot take picture using OpenCV with Raspberry Pi 4 ssh


I am running OpenCV on my Raspberry Pi using ssh. I have connected a camera, but it’s not taking the image.

Here is my code:

import cv2

cam_port = 0
cam = cv2.VideoCapture(cam_port)

result, image = cam.read()


if result:
    cv2.imshow("img", image)
    cv2.imwrite("imasdf.png", image)
    cv2.waitKey(0)
    cv2.destroyWindow("img")
else:
    print("No image detected. Please! try again")

I get this error:

Traceback (most recent call last):
  File "/home/ai/bacterium.py", line 10, in <module>
    cv2.imshow("img", image)
cv2.error: OpenCV(4.8.1) /io/opencv/modules/highgui/src/window.cpp:1272: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage'

I have libgtk2.0-dev installed. When I run the install command for libgtk2.0-dev I get this:

Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
libgtk2.0-dev is already the newest version (2.24.33-2+rpt1).
0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded.

I run the file again, and I still get the same error.


Solution

  • I realized that since I was connecting to my Raspberry Pi via ssh, I couldn't use imshow.

    This is my code now:

    import cv2
    
    cam_port = 0
    cam = cv2.VideoCapture(cam_port)
    
    result, image = cam.read()
    
    cv2.imwrite("imasdf.png", image)