Sub topic 3
Displaying and saving images
This chapter assumes you can run Python scripts, have installed opencv-python with pip, and know that an OpenCV image is a NumPy array in BGR order, as covered in the earlier chapters. You will show an image in a window, control how long it stays open, write it to disk, and handle the cases where display or saving does not work.
Showing an image with cv2.imshow
cv2.imshow(winname, image) opens a window with the given title and draws the array in it. The title also identifies the window. Calling imshow again with the same title updates that window instead of opening a new one.
imshow only queues the drawing. The window is painted and handles events (redraw, close button, key presses) inside cv2.waitKey. If you call imshow and never call waitKey, the window may not appear, or it appears blank and unresponsive.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()The three calls do the following:
cv2.imshow("Image", img)creates or updates the window.cv2.waitKey(0)blocks until a key is pressed while the window has focus.cv2.destroyAllWindows()closes every OpenCV window. Usecv2.destroyWindow("Image")to close one.
imshow expects BGR order, which matches what imread returns, so no color conversion is needed. It also interprets pixel values by dtype. A uint8 image is shown as 0 to 255. A float image is shown as 0.0 to 1.0, so a float image with values up to 255 looks almost entirely white.
How waitKey works
cv2.waitKey(delay) takes a delay in milliseconds and returns the code of the key that was pressed, or -1 if no key was pressed before the delay ran out.
| Call | Behavior |
|---|---|
| `cv2.waitKey(0)` | Waits forever for a key press. |
| `cv2.waitKey(1)` | Waits at most 1 ms. Typical inside video loops. |
| `cv2.waitKey(500)` | Waits up to half a second, then returns `-1` if nothing was pressed. |
Two details cause most confusion:
- Closing the window with the X button does not stop
waitKey(0). It keeps waiting for a key press that may never come, or it returns immediately in a way that depends on the GUI backend. If you want the close button to end your program, poll the window state yourself (see the loop below). - Key codes may carry extra bits on some platforms. The common idiom
cv2.waitKey(delay) & 0xFFkeeps only the low 8 bits so you can compare withord("q")or27(the Escape key).
This loop closes on q, Escape, or the window's close button:
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
WINDOW = "Image"
cv2.imshow(WINDOW, img)
while True:
key = cv2.waitKey(50) & 0xFF
if key in (27, ord("q")):
break
if cv2.getWindowProperty(WINDOW, cv2.WND_PROP_VISIBLE) < 1:
break
cv2.destroyAllWindows()cv2.getWindowProperty(..., cv2.WND_PROP_VISIBLE) returns a value below 1 once the window has been closed. Check it after waitKey, because the close event is only processed inside waitKey.
Window size and several windows
By default the window matches the image size and cannot be resized by the user. To make a resizable window, create it first with cv2.namedWindow and the WINDOW_NORMAL flag:
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
cv2.namedWindow("Image", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Image", 800, 600) # width, height of the window
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()resizeWindow changes only the window. The array is untouched, and OpenCV scales the picture to fit when drawing. To compare images, call imshow with a different title for each. One waitKey call serves all open windows.
Saving with cv2.imwrite
cv2.imwrite(filename, image) writes the array to disk. It chooses the file format from the extension, so copy.png writes PNG and copy.jpg writes JPEG, no matter what the array came from.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
ok = cv2.imwrite("copy.png", img)
print(ok) # True if the file was writtenimwrite returns True on success and False on many failures. The most common cause of False is a directory that does not exist. imwrite does not create directories. An extension OpenCV does not recognize raises a cv2.error instead of returning False. Always check the return value, in the same spirit as checking imread for None.
Controlling quality and compression
Pass format-specific options as a flat list of alternating flag and value:
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
# JPEG quality: 0 to 100, default 95. Higher means larger files.
cv2.imwrite("high.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 95])
cv2.imwrite("low.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 40])
# PNG compression: 0 to 9, default 3. Higher means smaller files and slower writes.
cv2.imwrite("small.png", img, [cv2.IMWRITE_PNG_COMPRESSION, 9])PNG compression is lossless. The pixel values you read back are identical to what you wrote, and only the file size and write time change. JPEG quality is lossy. Each save discards some information, and saving a JPEG repeatedly adds more loss each time. Keep an original or save intermediate results as PNG, and write JPEG once at the end.
What can be saved
- dtype. JPEG and PNG output expects
uint8data. PNG also acceptsuint16. If you computed a float image, convert it first, for examplenp.clip(result, 0, 255).astype(np.uint8). - Channels. A 2D array is saved as grayscale. A 3-channel array is saved as color and assumed to be BGR, which
imwriteconverts correctly for the file. A 4-channel BGRA array keeps transparency in PNG. JPEG has no alpha channel. - RGB arrays. If you converted to RGB for another library,
imwritestill treats the array as BGR and the saved file has red and blue swapped. Convert back withcv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)before saving.
A small save helper
This helper creates the folder, passes parameters through, and raises on failure:
from pathlib import Path
import cv2
def save_image(path, image, params=None):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
ok = cv2.imwrite(str(path), image, params or [])
if not ok:
raise OSError(f"cv2.imwrite failed for {path}")
return path
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
save_image("output/gray.png", cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
save_image("output/preview.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 85])Converting Path to str is a precaution. Some older OpenCV builds accept only strings.
When cv2.imshow is not available
imshow needs a graphical window system. It fails in these situations:
- Headless packages. The
opencv-python-headlessbuild has no GUI backend. Callingimshowraises acv2.errorsaying the function is not implemented. - Servers, containers, and SSH sessions without a display. The error mentions that it cannot connect to a display, or the process crashes.
- Notebooks. Jupyter and Colab either hang or fail with
imshow.
The reliable fallback is to save the image and open the file, or to show it with Matplotlib. Matplotlib expects RGB, so convert first:
import cv2
import matplotlib.pyplot as plt
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(rgb)
plt.axis("off")
plt.show()For a grayscale array, use plt.imshow(gray, cmap="gray"). Without cmap, Matplotlib applies a green-to-purple color map.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Window flashes and disappears | Script ends right after `imshow` | Call `cv2.waitKey(0)` before the script exits. |
| Window is gray or never appears | No `waitKey` call, so events are never processed | Add `cv2.waitKey(1)` or longer. |
| Window does not close on the X button | `waitKey(0)` is blocking | Use the polling loop with `WND_PROP_VISIBLE`. |
| Image looks blue or orange in Matplotlib | BGR array passed to an RGB library | Convert with `COLOR_BGR2RGB`. |
| Float image looks all white | Values above 1.0 in a float array | Convert to `uint8`, or scale to 0.0 to 1.0. |
| `imwrite` returns `False` | Folder does not exist, or path not writable | Create the folder, then check the return value. |
| `cv2.error` on `imwrite` | Unknown file extension | Use `.png`, `.jpg`, `.bmp`, or `.tiff`. |
| `imshow` is "not implemented" | Headless build installed | Use Matplotlib or save the file. |
Exercise
A script calls cv2.imshow("Result", img) and cv2.imwrite("out/result.png", img), then exits without a waitKey call. The out folder does not exist. Name each problem you can predict and give the fix.
Show answer
Three problems. First, without cv2.waitKey the window may never be painted, or it vanishes immediately, so add cv2.waitKey(0) before exiting, followed by cv2.destroyAllWindows(). Second, imwrite does not create the out folder, so it returns False and no file is written. Create the folder first, for example with Path("out").mkdir(exist_ok=True). Third, the script ignores the return value of imwrite, so it never learns that the save failed. Store the result in a variable and raise an error if it is False.
Exercise
You load a JPEG, convert it to RGB with cv2.cvtColor for a Matplotlib preview, and then save the RGB array with cv2.imwrite. What is wrong with the saved file, and how do you fix it?
Show answer
imwrite treats every 3-channel array as BGR, so the saved file has its red and blue channels swapped and the colors look wrong. Save the original BGR array, or convert the RGB array back with cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) before calling imwrite.