pythonopencvraspberry-piraspberry-pi4

How to solve opencv cv2.imshow() Unable to init server: Could not connect: Connection refused Can't initialize GTK backend in function 'cvInitSystem'


Hi I installed opencv to a raspberry pi 4 (2022-04-04 Buster OS). Here is the code I am using:

import cv2
    
camera = cv2.VideoCapture(0)
success, frame = camera.read()
if not success:
    stop('camera not connected')
cv2.imshow('Window', frame)
cv2.waitKey(1000)

When I try to run the code, I am getting this error message:

Unable to init server: Could not connect: Connection refused Traceback (most recent call last): File "try01.py", line 7, in cv2.imshow('Window', frame) cv2.error: OpenCV(4.6.0) /tmp/pip-wheel-8c7uejek/opencv-python_88dbbad412c5416b992ae69de26299d6/opencv/modules/highgui/src/window_gtk.cpp:635: error: (-2:Unspecified error) Can't initialize GTK backend in function 'cvInitSystem'

Python version: 3.7.3

opencv version: 4.6.0

numpy version: 1.21.6

Any suggestions?


Solution

  • I followed these steps https://dustinpfister.github.io/2020/03/27/linux-raspbian-lite-xserver-xorg/

    and then I need to run

    export DISPLAY=:0

    and the problem is fixed. Thank you guys for your help!!