🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI Freecv2.imwrite: Save Images in Python

Saving an image in Python starts with choosing a filename and destination. cv2.imwrite() encodes an image array using the filename extension and writes it to a file.
This article shows how to save an array with cv2.imwrite() and where a relative path points.
TL;DR
Use cv2.imwrite(filename, image) to encode an image array using the filename extension, then check its Boolean result and confirm the destination.
- Pass the output path first and the NumPy image array second.
- Create the parent directory yourself and check whether the write returned True.
- A relative path is resolved from Python’s current working directory.
What Is cv2.imwrite()?
cv2.imwrite(filename, image[, params]) accepts an output filename, an image array and optional encoder settings.
PNG preserves pixel values, which suits screenshots or arrays where exact values matter. PNG also supports transparency. JPEG uses lossy compression, so repeated saves can change pixel values.
OpenCV builds may not include every codec. If a writer rejects a format, check the installed build’s codec support before changing the image array.
Some image formats support several channel layouts, but a filename extension does not add a missing alpha channel. If transparency is required, the input array must contain the appropriate channel data and the chosen encoder must support it. Validate both before relying on a saved file to retain transparent pixels.
Likewise, high bit-depth data needs a compatible format and supported array depth. An 8-bit preview and a scientific image with wider samples have different storage needs, even when both are represented as NumPy arrays. Check the codec documentation for the depth and channel combinations it accepts.
For example, the same array can be written to Path(“output”) / “sample.png” or Path(“output”) / “sample.jpg”.
The Python call has three arguments in this order: filename, image, then an optional parameter sequence. Its filename is a string or supported path-like value. The image is a pixel array, not a display result.
The C++ API uses cv::imwrite(filename, image, params), where image is cv::Mat and params is a vector of integer flags and values. Python uses an ndarray and its own binding syntax, so adapt types when translating examples.
The format comes from the filename extension. A path ending in .png requests PNG encoding, while .jpg requests JPEG.
The returned Boolean answers whether the writer completed successfully. Store it when the next step depends on the file, then handle False before treating the output as complete.
For JPEG, the quality flag controls the encoder’s quality setting. A lower setting can reduce file size while adding visible compression artifacts. PNG has a separate compression-level flag that affects file size rather than visual quality.
Use defaults when the output only needs to be saved and decoded. Add a parameter when you have a specific requirement, such as controlling JPEG quality, and keep that flag beside the call that uses it. Every flag must be a supported integer constant for the chosen image format.
When writing a second representation, use a second filename with the matching suffix. The same in-memory array can be encoded once as PNG and once as JPEG, but the resulting files have different encoding properties. Keep both outputs if you need a lossless reference alongside a smaller compressed copy.
Choose a name that tells you which processed stage the file represents. For example, a resized output should not silently overwrite the original unless replacement is intended. A separate destination also makes it possible to compare the saved result with the input during debugging.
After saving, inspect the file with a reader such as cv2.imread() when later code depends on it. The array’s shape can confirm the expected row and column count, while a visual check can catch a color-order mistake that a successful write status cannot detect. This is useful when data came from a library that stores color channels in a different order.
For a grayscale array, pass the two-dimensional image directly. Do not add a color channel just to match a three-channel example, because that changes the data representation. For a color array, check the channel count and ordering before saving when the pixels came from another image package.
For a batch of processed images, include a stable identifier in each destination name so one iteration does not overwrite another. A frame number or input stem can make the relationship clear, provided the parent folder exists before the first write.
When choosing between PNG and JPEG, think about what will consume the result. A mask or annotated screenshot may need exact boundaries and transparency, while a photographic preview may tolerate lossy encoding. Keep an uncompressed source when later processing depends on exact pixel values.
The filename extension and array contents play different roles. The suffix requests an encoder, while the array supplies the samples that encoder processes. A writer cannot infer that RGB channel order should be converted to OpenCV’s usual BGR convention, so make that conversion before the save when needed.
For output verification, inspect more than the return status when the file is part of a pipeline. Reloading checks decoding, and comparing the reloaded shape with the expected dimensions can reveal an incorrect source array. A successful write of an unexpected array is still a result your downstream code may not want.
Prefer an explicit destination when a script may be launched from different folders. If a relative path is intentional, make the working directory part of the way you run the program so the output location remains predictable for future executions.
How to Save an Image with cv2.imwrite Step by Step
Save the array to a named file, check the return value, then read the file back when you need to verify it exists and can be decoded.
Step 1: Import OpenCV and create an image array
Install the OpenCV package in the Python environment used to run the script, then import cv2. The sample creates a tiny three-channel NumPy array, so it needs no input photo.
import cv2
import numpy as np
image = np.zeros((2, 3, 3), dtype=np.uint8)
image[0, 0] = [0, 0, 255]
OpenCV images use arrays whose dimensions describe rows, columns and channels. Here the dimensions are 2 by 3 pixels with three color channels.
The sample uses uint8 values, which represent integer channel values from 0 through 255. That is a common representation for ordinary 8-bit images. If an upstream operation creates a floating-point array, check the expected range and convert deliberately before saving, rather than assuming that a different dtype will produce the same encoded appearance.
For an image loaded from disk, confirm that cv2.imread() returned an array before passing it on. A misspelled input filename or unsupported input can produce None, and trying to write that value does not give the writer valid pixels. This check belongs near the read operation because it identifies the source of the problem before encoding begins.
For a grayscale image, the array has rows and columns without a final channel dimension. A color image commonly has three channels, and OpenCV stores them in BGR order. Convert data from an RGB-oriented library before saving, or the colors may appear swapped.
Also check the array dtype because the selected encoder supports particular depths. OpenCV may convert an unsupported depth for a format or fail the write, as listed in the codec reference.
Step 2: Choose a filename and save
Pass a path ending in the desired format and retain the result from cv2.imwrite(). The parent folder in this example is created before the save call.
from pathlib import Path
out = Path("output") / "sample.png"
out.parent.mkdir(parents=True, exist_ok=True)
written = cv2.imwrite(str(out), image)
print(written)
Step 3: Verify the saved file
Check the Boolean result and load the path again to verify the encoder produced an image that OpenCV can read.
saved = cv2.imread(str(out))
print(saved.shape)
In my run, the command printed this output:
OpenCV 5.1.0
saved: True
file: /home/ubuntu/.cache/journaldev-article-runs/askpython-opencv-imwrite-20261124T211753Z-76ed171f0126/output/sample.png
shape after read: (2, 3, 3)
missing directory result: False

The successful write returned True. The reloaded array kept its (2, 3, 3) shape, while the missing-folder check returned False rather than producing an output file.
Check the Path and the Image Before Saving
My missing-folder test returned False, so inspect both destination and input when a write fails.
A relative destination is interpreted from the process’s current working directory, which can differ from the folder that contains the Python file. IDEs, notebooks and shell sessions can each start a process from a different directory. When the output seems to disappear, print Path.cwd() in the program or use an absolute destination to make the location explicit.
For a nested destination, create its parent path before calling the writer. Path.parent identifies the folder portion of the output filename, and mkdir(parents=True, exist_ok=True) creates missing levels while leaving an existing directory in place. Keep this operation separate from imwrite so a directory-creation error is distinguishable from an encoding failure.
The Boolean result is useful in batch jobs too. If a loop writes many frames or processed images, check each result and associate a failure with its filename. Otherwise, a later step may report only that an expected file is absent, leaving the original failed write hard to identify.
| Case | What to check | Fix |
|---|---|---|
| Relative filename | Python’s current working directory | Print Path.cwd() or use an absolute path |
| Missing parent folder | Whether the directory exists | Call Path(path).parent.mkdir(parents=True, exist_ok=True) |
| False result | Destination permissions and path | Correct the destination and test the Boolean again |
| Empty image | Whether cv2.imread() returned None or the array is empty | Validate the input before calling imwrite() |
Use the table to identify which input or destination needs attention before trying another save.
Conclusion
Use the path table to diagnose missing output, then check the returned status.
For the related steps, read how to read images with OpenCV and extract images from a video.
FAQ
These answers cover the two checks that commonly come up after a save call.
Where does cv2.imwrite() save the file?
A relative filename is resolved from Python’s current working directory. Use an absolute path to specify another destination.
What does cv2.imwrite() return?
It returns True when the image is written and False when the write fails. Check the result and confirm the destination directory exists.
Does cv2.imwrite() create folders?
No. Create the parent directory before saving, for example with Path(path).parent.mkdir(parents=True, exist_ok=True).


