opencv: Could not load the Qt platform plugin "xcb" in "" even though it was found

Viewed 1786

I installed opencv-python on ubuntu wsl, after setting up a venv using virtualenvwrapper (I use wsl in visual studio code). When running this code (which appears in one of the articles of this OCR guide:

import argparse
import cv2

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True)
args = vars(ap.parse_args())

image = cv2.imread(args["image"])
cv2.imshow("I", image)

with this command on teminal:

python script.py --image temp.png

I get:

qt.qpa.xcb: could not connect to display 
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "/home/ben123/.local/bin/.virtualenvs/ocr_venv/lib/python3.8/site-packages/cv2/qt/plugins" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: xcb.

The interpreter in vscode is the correct one (the one of the venv), and when I type pip list I get

Package       Version
------------- --------
numpy         1.22.2
opencv-python 4.5.5.62
pip           22.0.3
setuptools    60.6.0
wheel         0.37.1

Would appreciate any help at this point, since I spent so much time and didn't get nowhere.

Things I tried:

  1. following this guide to install it. Gave the same error.
  2. following an older guide from this site, was much more complicated and didn't work as well.
  3. uninstalling opencv-python and installing opencv-python again/ opencv-python-contrib/ opencv-python-headless/ opencv-python-contrib-headless (only one of them at a time)
  4. following this thread because it has similar problem
  5. literally reset my wsl several times just to make sure I don't have multiple pythons/ opencv versions that mess this up.
  6. tried installing (to a wsl venv) opencv directly with the official documentation
  7. Tried to give up on wsl completely and install opencv using anaconda but even that didn't work.
4 Answers

Just delete cv2.imshow from your code. Your OS is without graphics and can't display image

I had the same error in a completely different context.

Found that the problem was a PyQt5 installation in my virtual environment. Check if you have a PyQt in the path

/home/ben123/.local/bin/.virtualenvs/ocr_venv/lib/python3.8/site-packages/

if so, remove it

$ pip uninstall <PyQT package installed>

example:

$ pip uninstall PyQt5

Then reinstall opencv-python

$ pip uninstall opencv-python
$ pip install opencv-python

Hope that works!

To display graphical information about wsl, you should configure x11 related content. eg: You can use MobaXterm for graphical display.

Uninstalling opencv and installing similar headless version worked for me.

$ pip install opencv-python-headless
Related