I am working with OpenCV to display an image, and I encountered a problem on Ubuntu. The code works fine when I press the ESC key to exit the window, but if I manually click the "X" button to close the window, the program hangs and doesn’t proceed to the next steps (e.g., saving the image).
Here is my code:
import cv2
path = "/home/huanyizhiyuan/Softwares/VsCode_workspace/Python_workspace/image_solve/card1.jpg"
# Read the image
img = cv2.imread(path)
if img is None:
raise FileNotFoundError(f"Image not found: {path}")
# Resize the image
img = cv2.resize(img, (1000, 800))
# Display the image
cv2.imshow('image', img)
# Wait for keyboard input
cv2.waitKey(0)
# Close the window
cv2.destroyWindow('image')
# Save the image
cv2.imwrite('new_image.jpg', img)
-
If I press ESC or any key while the window is open, the program exits as expected, and the image is saved correctly.
-
If I manually click the close button (the "X" button in the corner of the window), the program freezes. It does not save the image or exit gracefully.
Environment:
Operating System: Ubuntu 24.04.1 LTS
opencv-python: 4.10.0.84
Python: 3.12.7
What I’ve Tried:
- I checked if the image path was correct and verified that the image is being displayed properly.
- I attempted to use cv2.destroyWindow after cv2.waitKey(0), but the issue persists when clicking the close button.
2
Answers
My hunch its with compatibility across different systems. As you are using linux modify like this
In a single Picture
The
& 0xFF
is used to extract the last 8 bits of the key code, which can help with compatibility across different systemsHave a look – What's 0xFF for in cv2.waitKey(1)?
The problem can be fixed.
You must include another
cv2.imshow
since you are usingcv2.destroyWindow('image')
.Snippet:
This will close button (the "X" button in the corner of the window). One at a time.