WRITING A NEW IMAGE IN PYTHON

Photo of author

By Jackson Taylor

Home » Electronics Topics » Python & OpenCv » WRITING A NEW IMAGE IN PYTHON

Writing an image in Python means taking pixel data, either from a file you loaded or from an array you created, and saving it to disk as a new file. The most common tool for this is OpenCV, and the function you need is cv2.imwrite(). This guide shows a working example, explains each line, and covers the mistakes that most often cause a blank or missing output file.

What you need before you start

You need Python 3 and the OpenCV package. You can install it with pip:

pip install opencv-python

You will also need an image file to work with. In the examples below it is called IMAGE_1.PNG and sits in the same folder as your script. If you want a refresher on loading files first, read our guide to opening an image in Python.

A basic example: read an image and write a new one

This short script reads an image and saves a new copy under a different name:

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video
import cv2

img = cv2.imread('IMAGE_1.PNG', 0)  # reads the image as grayscale
cv2.imwrite('output.PNG', img)      # writes the new file

Run it, and a file named output.PNG appears in the same folder. Because of the flag, the new image is a grayscale version of the original.

The original version of this example also called cv2.waitKey(0) and cv2.destroyAllWindows(). Those two lines only matter when you open a preview window with cv2.imshow(). If you are only saving a file, you can leave them out. Also make sure every line starts at the same indentation level, because extra spaces at the start of a line cause an IndentationError in Python.

Here is the original snippet with a link to more examples:

import cv2
img = cv2.imread('IMAGE_1.PNG',0) #reads the image
cv2.imwrite('output.PNG',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

more examples

How the code works

cv2.imread()

This function loads an image from disk into a NumPy array. The second argument controls how the image is loaded:

  • 1 (or cv2.IMREAD_COLOR): loads a color image. This is the default.
  • (or cv2.IMREAD_GRAYSCALE): loads the image in grayscale.
  • -1 (or cv2.IMREAD_UNCHANGED): loads the image as it is, including any transparency channel.
See also
2 HP DC MOTOR ADJUSTABLE SPEED CONTROL

If the file cannot be found or read, imread() does not raise an error. It returns None, and you will only see a problem later when you try to use the result.

cv2.imwrite()

This function takes a file name and an image array, and saves the array to disk. It returns True if the file was written and False if not, so it is worth checking the result:

ok = cv2.imwrite('output.PNG', img)
if not ok:
    print('Could not write the image')

If a file with the same name already exists, it is overwritten without a warning.

Saving in a different format

OpenCV chooses the file format from the extension you give in the file name. To convert a PNG to a JPEG, you only need to change the extension:

img = cv2.imread('IMAGE_1.PNG')
cv2.imwrite('output.jpg', img)

Common extensions include .png, .jpg, .bmp and .tiff. Which ones work depends on the image libraries available in your OpenCV build, but PNG and JPEG are supported in the standard pip package.

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works

Controlling JPEG quality

You can pass a third argument to adjust compression. For JPEG, quality runs from 0 to 100, and higher values give better quality and larger files:

cv2.imwrite('output.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 90])

Controlling PNG compression

PNG is lossless, so the setting only affects file size and speed. The value runs from 0 to 9, where higher means a smaller file and slower saving:

cv2.imwrite('output.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 9])

Creating a brand new image from scratch

You do not have to start from an existing file. An image is just an array of numbers, so you can create one with NumPy and save it:

import cv2
import numpy as np

# 200 pixels high, 300 pixels wide, 3 color channels, all black
img = np.zeros((200, 300, 3), dtype=np.uint8)

# draw a filled blue rectangle (OpenCV colors are in B, G, R order)
cv2.rectangle(img, (50, 50), (250, 150), (255, 0, 0), -1)

cv2.imwrite('new_image.png', img)

Two details matter here. The array must use the uint8 type for normal 8-bit images, and the shape is (height, width, channels), not width first.

See also
HOW TO SEND OR RECEIVE SERIAL DATA IN PYTHON USING XCTU OR TO ARDUINO

Writing frames from a camera

The same function saves frames from a webcam. After reading a frame with VideoCapture, you pass it straight to imwrite(). Our tutorial on capturing an image from the camera with Python and OpenCV covers the full setup, and you can also save a frame only when a key is pressed if you want control over the moment of capture.

Using Pillow as an alternative

If you do not need OpenCV’s computer vision features, the Pillow library is a good option for simple image work:

from PIL import Image

img = Image.new('RGB', (300, 200), color=(0, 0, 255))
img.save('new_image.png')

Note that Pillow uses RGB order, while OpenCV uses BGR. If you move arrays between the two libraries, convert the color order first, or your reds and blues will be swapped.

Common problems and fixes

  • The output file is not created. Check the return value of imwrite(). The folder may not exist, or you may not have permission to write there.
  • An error saying the image is empty. The input was probably not found, so imread() returned None. Check the file name, extension and working directory.
  • The output is black or looks wrong. Confirm the array type is uint8 and that values are in the 0 to 255 range. Floating point arrays with values between 0 and 1 will usually save as nearly black.
  • Colors look swapped. This is the BGR versus RGB difference described above.
  • The image is grayscale when you expected color. Check that you did not pass to imread().

FAQ

How do I save an image in Python?

With OpenCV, load or create an image array and call cv2.imwrite('file_name.png', img). With Pillow, call img.save('file_name.png') on an image object.

Does cv2.imwrite() overwrite existing files?

Yes. If a file with the same name exists in the target folder, it is replaced without any warning. Use a different file name if you want to keep the original.

See also
CUK CONVERTER SIMULATION AND HARDWARE USING ARDUINO AND MATLAB SIMULINK

Why is my saved image grayscale?

Most likely you loaded it with the flag in cv2.imread('file', 0), which converts it to grayscale. Remove the flag, or use cv2.IMREAD_COLOR, to keep the colors.

Do I need cv2.waitKey() when writing an image?

No. waitKey() and destroyAllWindows() are only needed when you display the image in a window. Saving a file works without them.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works