-27 opencv runtime_error ai_generated true

cv2.error: OpenCV(4.8.0) ../modules/highgui/src/window.cpp:376: error: (-27:Null pointer) NULL window in function 'cvWaitKey'

ID: opencv/highgui-waitkey-before-imshow-crash

Also available as: JSON · Markdown · 中文
95%Fix Rate
85%Confidence
1Evidence
2023-05-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
4.5.5 active
4.6.0 active
4.7.0 active
4.8.0 active
4.9.0 active

Root Cause

cv2.waitKey() is called before cv2.imshow() creates a window, or the window was destroyed before the waitKey call.

generic

中文

在 cv2.imshow() 创建窗口之前调用了 cv2.waitKey(),或者窗口在 waitKey 调用前已被销毁。

Official Documentation

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

Workarounds

  1. 98% success Ensure cv2.imshow() is called before cv2.waitKey(): cv2.imshow('window', image); cv2.waitKey(0); cv2.destroyAllWindows()
    Ensure cv2.imshow() is called before cv2.waitKey(): cv2.imshow('window', image); cv2.waitKey(0); cv2.destroyAllWindows()
  2. 75% success If using a headless environment, set the OpenCV backend to headless before any GUI calls: cv2.imshow = lambda *args: None; cv2.waitKey = lambda *args: None
    If using a headless environment, set the OpenCV backend to headless before any GUI calls: cv2.imshow = lambda *args: None; cv2.waitKey = lambda *args: None

中文步骤

  1. Ensure cv2.imshow() is called before cv2.waitKey(): cv2.imshow('window', image); cv2.waitKey(0); cv2.destroyAllWindows()
  2. If using a headless environment, set the OpenCV backend to headless before any GUI calls: cv2.imshow = lambda *args: None; cv2.waitKey = lambda *args: None

Dead Ends

Common approaches that don't work:

  1. 70% fail

    The window must be explicitly created by imshow; sleeping does not change the order of operations.

  2. 50% fail

    namedWindow with cv2.WINDOW_GUI_NORMAL or similar may still result in a null internal window handle on some backends.