How to Display Image Using OpenCV in Computer Vision
To display an image using
OpenCV, use cv2.imshow() to open a window showing the image, then call cv2.waitKey() to keep the window open until a key is pressed, and finally cv2.destroyAllWindows() to close the window. This sequence ensures the image appears properly and the program waits for user interaction.Syntax
The basic syntax to display an image in OpenCV is:
cv2.imshow(window_name, image): Opens a window namedwindow_nameand displays theimage.cv2.waitKey(delay): Waits for a key press fordelaymilliseconds. Use 0 to wait indefinitely.cv2.destroyAllWindows(): Closes all OpenCV windows.
python
cv2.imshow('Window Name', image) cv2.waitKey(0) cv2.destroyAllWindows()
Example
This example loads an image from disk and displays it in a window until you press any key.
python
import cv2 # Load image from file image = cv2.imread('example.jpg') # Check if image loaded successfully if image is None: print('Error: Image not found or unable to load.') else: # Display the image in a window named 'My Image' cv2.imshow('My Image', image) # Wait indefinitely until a key is pressed cv2.waitKey(0) # Close all OpenCV windows cv2.destroyAllWindows()
Output
A window titled 'My Image' opens showing the image until a key is pressed.
Common Pitfalls
Common mistakes when displaying images with OpenCV include:
- Not calling
cv2.waitKey(), which causes the window to close immediately. - Using an incorrect image path causing
cv2.imread()to returnNone. - Not calling
cv2.destroyAllWindows()to properly close windows. - Trying to display images in environments without GUI support (like some servers).
python
import cv2 # Wrong way: missing waitKey, window closes instantly image = cv2.imread('example.jpg') cv2.imshow('Image', image) cv2.destroyAllWindows() # Window closes immediately # Right way: cv2.imshow('Image', image) cv2.waitKey(0) # Wait for key press cv2.destroyAllWindows()
Quick Reference
| Function | Purpose |
|---|---|
| cv2.imread(path) | Load image from file path |
| cv2.imshow(window_name, image) | Display image in a window |
| cv2.waitKey(delay) | Wait for key press (0 = infinite) |
| cv2.destroyAllWindows() | Close all OpenCV windows |
Key Takeaways
Always use cv2.waitKey() after cv2.imshow() to keep the window open.
Check if the image loaded correctly before displaying it.
Use cv2.destroyAllWindows() to close windows cleanly.
Provide the correct image path to cv2.imread() to avoid errors.
OpenCV image display requires a GUI environment to work.