HOWTO · Python
How to Invert an Image Using OpenCV Module in Python
Learn how to invert an image using the OpenCV module in Python. This guide provides step-by-step instructions and code examples for both color and grayscale images, along with tips on saving your inverted images. Perfect for beginners and experienced programmers alike, discover the power of OpenCV for image processing today.
On this page
Invert an image in Python by applying cv2.bitwise_not() to an array returned by OpenCV. For unsigned 8-bit image channels, each value v becomes 255 - v. The sections below explain the channel behavior, show the calculation on sample pixel data, and demonstrate how to process color or grayscale files and save the result.
Prerequisites and Load an Image
Install Python and OpenCV in the environment where the script will run. The package is named opencv-python, while Python code imports it as cv2. Install it with pip install opencv-python if it is not already available. The NumPy alternative also requires NumPy, which is installed as a dependency of the standard OpenCV Python package.
Set input_path to a readable image file. OpenCV loads color images in BGR channel order by default. Assign image = cv2.imread(input_path) to load one; check image is not None before processing because a missing or unreadable file makes imread return None. The examples below use 8-bit channel values, the usual representation for common image files.
How Image Inversion Works
Inversion maps each channel value to its complement. For unsigned 8-bit values from 0 through 255, black becomes white, white becomes black, and a value such as 40 becomes 215. The operation applies independently to every channel, so a color pixel’s blue, green, and red values are all inverted. OpenCV’s default color array is BGR, not RGB; inversion preserves that channel order, so it does not swap colors.
Invert an Image with OpenCV
OpenCV’s cv2.bitwise_not() applies a bitwise NOT to each array element. On unsigned 8-bit image data, that produces the same result as subtracting each value from 255. This small standard-library example makes the pixel calculation visible without requiring an image file or image-processing package. Use it to understand the values; for an OpenCV image array, call cv2.bitwise_not(image) after checking that loading succeeded.
Run this example:
pixel = [10, 40, 200]
inverted_pixel = [255 - value for value in pixel]
print("original:", pixel)
print("inverted:", inverted_pixel)
original: [10, 40, 200]
inverted: [245, 215, 55]
For a file workflow, set input_path and output_path to your image and destination, then run this example. Install OpenCV first. The paths below are explicit placeholders to replace with files on your machine; the program reports a load or write problem without trying to process a missing image.
try:
import cv2
except ImportError:
print("Install opencv-python to run this example.")
else:
input_path = "input.png"
output_path = "inverted.png"
image = cv2.imread(input_path)
if image is None:
print(f"Could not read {input_path}")
else:
inverted = cv2.bitwise_not(image)
written = cv2.imwrite(output_path, inverted)
if not written:
print(f"Could not write {output_path}")
show_preview = False
if show_preview:
cv2.imshow("Original", image)
cv2.imshow("Inverted", inverted)
cv2.waitKey(0)
cv2.destroyAllWindows()
The loaded color array and its inverted result are kept in image and inverted. OpenCV returns color channels in BGR order by default, and this operation inverts each channel without reordering them. The sample pixel calculation above illustrates the same unsigned 8-bit result.
Invert a Grayscale Image
A grayscale image has one intensity value per pixel rather than three color channels. Load it directly with cv2.IMREAD_GRAYSCALE, check that gray_image is not None, and apply the same bitwise operation. The result remains a two-dimensional, single-channel array and can be saved with cv2.imwrite().
try:
import cv2
except ImportError:
print("Install opencv-python to run this example.")
else:
input_path = "input.png"
gray_output_path = "inverted-gray.png"
gray_image = cv2.imread(input_path, cv2.IMREAD_GRAYSCALE)
if gray_image is None:
print(f"Could not read {input_path} as grayscale")
else:
inverted_gray = cv2.bitwise_not(gray_image)
written = cv2.imwrite(gray_output_path, inverted_gray)
if not written:
print(f"Could not write {gray_output_path}")
Invert an Image with NumPy
NumPy provides numpy.invert as an alternative when image data is already in a NumPy array. It performs bitwise NOT on each element; for unsigned 8-bit values, this produces the same channel complement as OpenCV. This example reads an 8-bit color image, applies NumPy’s inversion, and checks the saved result. The 255 - v interpretation here is limited to unsigned 8-bit data; do not generalize it to signed or wider integer arrays, where NumPy still performs a bitwise complement.
try:
import cv2
import numpy as np
except ImportError:
print("Install opencv-python and numpy to run this example.")
else:
input_path = "input.png"
numpy_output_path = "inverted-numpy.png"
image = cv2.imread(input_path)
if image is None:
print(f"Could not read {input_path}")
else:
inverted_numpy = np.invert(image)
written = cv2.imwrite(numpy_output_path, inverted_numpy)
if not written:
print(f"Could not write {numpy_output_path}")
For ordinary 8-bit image files, cv2.bitwise_not(image) and numpy.invert(image) give the same per-channel result. Prefer the OpenCV operation when the rest of the workflow already uses OpenCV; use NumPy’s function when you specifically need its array operation.
Save and Display the Inverted Image
Write the array that corresponds to the image you inverted: use cv2.imwrite(output_path, inverted) for a color result or cv2.imwrite(gray_output_path, inverted_gray) for grayscale. Check the returned Boolean value; False means OpenCV could not write the file, for example because the destination path is unavailable or the format is unsupported. The examples check this result with written and report a failed write.
The OpenCV example includes an optional preview block. Set show_preview to True there to open both windows. GUI display requires a graphical environment and may not be available in a headless session. Saving with cv2.imwrite() does not require opening a window. The OpenCV and NumPy image-file examples are provided for an environment with those packages and a readable input.png; execution evidence supplied for this article covers only the small pixel calculation above.