Opening an image is the first step in almost every image-processing task in Python, whether you want to resize a photo, detect edges, or feed pictures to a machine learning model. This tutorial shows the short OpenCV example, explains what each line does, and then covers the Pillow library as an alternative.
Quick example: open and display an image with OpenCV
OpenCV is the most common library for this job. Install it with pip install opencv-python, put an image file in the same folder as your script, and run the following code:
import cv2
img = cv2.imread('IMAGE_1.PNG', 0) # reads the image as grayscale
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
A window titled “image” opens and shows the picture. Press any key while the window is selected and the program closes it and exits. Note that every line must start at the same indentation level; extra leading spaces on the later lines will cause an IndentationError.
You can find more examples in our earlier Python tutorial.
What each line does
- import cv2 loads the OpenCV library. The package you install is called opencv-python, but you import it as cv2.
- cv2.imread(‘IMAGE_1.PNG’, 0) reads the file and returns the pixels as a NumPy array. The second argument is the read mode. The
here means grayscale. - cv2.imshow(‘image’, img) shows the array in a window. The first argument is the window title.
- cv2.waitKey(0) pauses the program until you press a key. Without it, the window would open and close almost instantly.
- cv2.destroyAllWindows() closes every window that OpenCV opened.
Choosing how the image is read
The second argument of cv2.imread() is a flag that controls the format of the loaded image. The three most useful values are:
cv2.IMREAD_COLOR(or1): loads a three-channel color image. This is the default, and any transparency is dropped.cv2.IMREAD_GRAYSCALE(or): loads a single-channel grayscale image, as in the example above.cv2.IMREAD_UNCHANGED(or-1): loads the image as stored, including an alpha (transparency) channel if the file has one.
Named constants are easier to read than numbers, so this version is clearer for other people:
import cv2
img = cv2.imread('IMAGE_1.PNG', cv2.IMREAD_COLOR)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Check that the image loaded
The most common beginner problem is a wrong file path. OpenCV does not raise an error when it cannot find a file. Instead, cv2.imread() quietly returns None, and the error appears later when you try to display or process the image. A simple check saves time:
import cv2
img = cv2.imread('IMAGE_1.PNG')
if img is None:
print('Could not open the image. Check the file name and path.')
else:
print(img.shape)
File names are also case-sensitive on Linux and macOS, so IMAGE_1.PNG and image_1.png are different files there. If the script is not run from the image’s folder, use a full path or a path relative to where you launch Python.
Looking at the image data
Once the image is loaded, it is just a NumPy array, so you can inspect it directly:
img.shapegives(height, width)for a grayscale image and(height, width, 3)for a color image.img.dtypeis normallyuint8, meaning each pixel value is a whole number from 0 to 255.img[y, x]returns the value of the pixel at row y and column x.
One detail trips up many people: OpenCV stores color channels in BGR order (blue, green, red), not the usual RGB. This matters when you pass the image to other libraries, as shown below.
Opening an image with Pillow
Pillow is a friendly alternative when you only need to open, inspect, resize or convert images, and do not need OpenCV’s computer vision tools. Install it with pip install pillow.
from PIL import Image
img = Image.open('IMAGE_1.PNG')
print(img.format, img.size, img.mode)
img.show()
Here img.size returns (width, height), which is the reverse order of OpenCV’s shape. img.mode tells you the color mode, such as RGB or L for grayscale. The show() method opens the picture in your system’s default image viewer rather than in a Python window.
Pillow also raises a clear FileNotFoundError if the file does not exist, which can be easier for beginners than the silent None from OpenCV.
Displaying the image with Matplotlib
If you work in Jupyter Notebook or Google Colab, cv2.imshow() often does not work properly and can even freeze the notebook. Matplotlib is the usual solution. Because OpenCV uses BGR order, convert the colors first, or the picture will look wrong, with blues and reds swapped:
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('IMAGE_1.PNG')
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
plt.axis('off')
plt.show()
For a grayscale image, use plt.imshow(img, cmap='gray') instead.
OpenCV or Pillow: which should you use?
- Use OpenCV if you plan to do image processing, work with video or a webcam, or run computer vision algorithms. For example, you can learn how to capture an image from a camera with the same library.
- Use Pillow for simple tasks such as converting formats, resizing, cropping and basic drawing.
The two work well together. You can convert between them through NumPy arrays, remembering the BGR and RGB difference.
What to do next
After opening an image, you will usually want to change it and store the result. Once you have processed the picture, you can save a new image to disk with cv2.imwrite(). If your source is a webcam rather than a file, you can also save a frame when a key is pressed. Image handling also appears in many Raspberry Pi projects, so it is worth getting comfortable with these basics; you can find ideas in our list of Raspberry Pi Python projects.
Frequently asked questions
Why does cv2.imread() return None?
Almost always the file path is wrong, the file name or extension is misspelled, or the file is corrupted or in an unsupported format. Print the path and check that the file exists from the folder where you run the script.
Why does my image open in grayscale?
You probably passed as the second argument to cv2.imread(), which loads the image as grayscale. Leave the argument out, or use cv2.IMREAD_COLOR, to load it in color.
Why does the OpenCV window close immediately?
The program reached the end of the script before you could see the window. Add cv2.waitKey(0) after cv2.imshow() so the window stays open until you press a key.
Can I open an image in Python without OpenCV?
Yes. Pillow (Image.open()) is the most common choice, and Matplotlib can also read and show images with plt.imread() and plt.imshow().