-2 opencv system_error ai_generated partial

cv::error: (-2:Unspecified error) Could not create window in function 'cv::namedWindow'

ID: opencv/highgui-window-could-not-be-created

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2024-09-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
4.5.5 active
4.8.0 active
4.9.0 active

Root Cause

The display server (X11, Wayland, or macOS Quartz) is not available, or the window manager is not running.

generic

中文

显示服务器(X11、Wayland 或 macOS Quartz)不可用,或窗口管理器未运行。

Official Documentation

https://docs.opencv.org/4.x/d7/dfc/group__highgui.html#ga5afdf8410934fd099df085bd3b1c0d6a

Workarounds

  1. 95% success import os os.environ['OPENCV_IO_ENABLE_OPENCL'] = '0' # Or simply avoid namedWindow calls; save images to disk instead: cv2.imwrite('output.jpg', img) # For debugging, print image shape instead of displaying.
    import os
    os.environ['OPENCV_IO_ENABLE_OPENCL'] = '0'
    # Or simply avoid namedWindow calls; save images to disk instead:
    cv2.imwrite('output.jpg', img)
    # For debugging, print image shape instead of displaying.
  2. 90% success sudo apt-get install xvfb Xvfb :99 -screen 0 1024x768x24 & export DISPLAY=:99 # Then run your OpenCV script
    sudo apt-get install xvfb
    Xvfb :99 -screen 0 1024x768x24 &
    export DISPLAY=:99
    # Then run your OpenCV script

中文步骤

  1. import os
    os.environ['OPENCV_IO_ENABLE_OPENCL'] = '0'
    # Or simply avoid namedWindow calls; save images to disk instead:
    cv2.imwrite('output.jpg', img)
    # For debugging, print image shape instead of displaying.
  2. sudo apt-get install xvfb
    Xvfb :99 -screen 0 1024x768x24 &
    export DISPLAY=:99
    # Then run your OpenCV script

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Qt backend also requires a display server; if no display is available, it will still fail.

  2. 70% fail

    If no X server is running, setting DISPLAY won't create one; the variable only works if X is already active.

  3. 80% fail

    Root privileges do not enable a display server; the error is about display availability, not permissions.