# 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`
- **Domain:** opencv
- **Category:** runtime_error
- **Error Code:** `-27`
- **Verification:** ai_generated
- **Fix Rate:** 95%

## Root Cause

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

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 4.5.5 | active | — | — |
| 4.6.0 | active | — | — |
| 4.7.0 | active | — | — |
| 4.8.0 | active | — | — |
| 4.9.0 | active | — | — |

## Workarounds

1. **Ensure cv2.imshow() is called before cv2.waitKey(): cv2.imshow('window', image); cv2.waitKey(0); cv2.destroyAllWindows()** (98% success)
   ```
   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** (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
   ```

## Dead Ends

- **** — The window must be explicitly created by imshow; sleeping does not change the order of operations. (70% fail)
- **** — namedWindow with cv2.WINDOW_GUI_NORMAL or similar may still result in a null internal window handle on some backends. (50% fail)
