5-3 Accessing Images

Accessing Images: OpenCV's First Magic Trick!

Ever wanted your code to "see" images just like your eyes do? Now, we're going to learn about the imread function. It's the superhero of OpenCV, allowing your code to easily read all kinds of images and set the foundation for future image processing!


Preparation: A Little Setup

Before you can use the imread function, you need to invite the OpenCV module into your program.

import cv2 as cv

This line of code brings the cv2 Python module for image processing from the OpenCV library into your program. To make coding easier, we usually give it a shorter name, cv. So, from now on, whenever you see cv, you'll know it represents OpenCV's functions!


imread's "ID Card" and "Manual"!

Every function has its "ID card" and "instruction manual" that tell you how it works, what data it needs, and what result it will give you. Here's the "prototype" of the imread function and its "parameters":

def imread(
    filename: str,  # The file path of the image, as a string
    flags: int = ... # Tells imread which mode to read the image in 
                # (usually optional, the default is fine)
) -> cv2.typing.MatLike: ... # What the function returns to you

Return Value: What does imread give you? 

When imread successfully reads an image, it returns a special “object” to you — and this “object” contains the image data itself!                  -> cv2.typing.MatLike:…

1. -> cv2.typing.MatLike 
This means the function is expected to return a value of type typing.MatLike. Think of it this way: when you successfully read an image, the computer stores its data in a special "language" called MatLike. It's essentially what an image "looks like" inside the computer, usually represented as a NumPy array (a great way to store data in Python) that contains all the pixel information of the image!

2. : 
The colon indicates that the function's "manual" ends here. What follows is usually the function's actual "work" (the code itself).

3. ...
If you see this in a "function preview" or "draft" document, it means the main code of the function is "omitted." It's just a placeholder to tell you how the function will work.


Hands-On Example: Read Your First Image!

Ready? Let's write some code to let your computer "see" an image!

import cv2 as cv # Import the OpenCV module and give it a short name, cv

# Set the file path of the image you want to read
# Remember to replace 'Pandora.png' with your own image path!
file_path = 'Pandora.png'

# Use OpenCV's imread function to read the image from the specified path.
# The image data is stored in a variable called 'source_picture'.
source_picture = cv.imread(file_path)

# Check if the image was loaded successfully.
# If 'source_picture' is None (nothing), it means the image failed to load!
if source_picture is None:
    print(f"Warning: Oops! Could not load the image.")
    print(f"Please check if the file path is correct: {file_path}")
else:
    # Start an infinite loop so the image window stays open until you close it.
    while True:
        # Use OpenCV's imshow function to create or update a window named 'Read Picture'
        # and display the 'source_picture' in it.
        cv.imshow('Read Picture', source_picture)

        # cv.waitKey(1) "pauses" your program for 1 millisecond 
            # (one-thousandth of a second).
        # It checks if you've pressed a key. If you did, 
          # it returns the key's number code;
        # if not, it returns -1.
        key = cv.waitKey(1)

        # Check if the pressed key is the ESC key (the number code for ESC is 27).
        if key & 0xFF == 27:
            break  
        # If you press the ESC key, exit this infinite loop and close the image window.

    # Call cv.destroyAllWindows() to close all image windows created by OpenCV.
    # This is a good habit to free up computer resources and keep your program clean!
    cv.destroyAllWindows()

Program Result:

Graphic confirming that OpenCV is successfully installed on the system
 

When you run the code above, if everything goes well, a window will pop up showing your image! You can try changing the image path to see different results. 


This is the introduction to the imread function! By learning it, you've taken the first step in image processing. Now you can use code to do all sorts of fun things with images, like:

1. Image Editing: Add filters, adjust brightness, crop, and more.
2. Image Recognition: Teach the computer to recognize objects, faces, and other things in pictures (this is a crucial foundation for AI!).
3. Game Development: Read the graphical assets used in games.

imwrite: The Magic to Save Your Pictures!

After processing an image with code, you're probably wondering how to "save" your cool results. Don't worry! The imwrite function is your savior! It's the "magician" in OpenCV responsible for turning the image data from your program's memory back into a file on your computer!


imwrite 's "ID Card" and "Manual"!

Here's the "prototype" of the imwrite function. You need to tell it two main things:

def imwrite(
    filename: str,  # What file path do you want to save the image to? 
               # (e.g., 'MyPicture.png'), as a string.
    img: cv2.typing.MatLike, # Which image do you want to save? 
                     # This is usually the image data you read with imread.
    params: _typing.Sequence[int] = ... # Some extra settings, like image quality 
                             # (usually optional, the default is fine).
) -> bool: ... # What the function returns to you.

Return Value: What does imwrite tell you!

After you ask imwrite to save your image, it will give you a simple answer:

bool:

This means the function is expected to return a boolean value (bool). A boolean value is like a switch, with only two states:

- True:
    Means "success!" The image has been saved to your computer.
- False:
    Means "it failed..." The image couldn't be saved. This can happen for many reasons, such as an incorrect file path, a lack of permissions to save to that location, or an issue with the image format.


Tips: A Few Things to Remember When Saving Pictures!

To ensure your image is saved successfully, keep these points in mind:

1. File Extension Determines Format:

imwrite is super smart! It looks at the file extension you provide (e.g., .png, .jpg) to decide which format to save the image in. So, to save as a PNG file, name your file Pandora.png!

2. Format Support:

Different image formats (like JPG, PNG, BMP, etc.) have different levels of support for an image's "depth" and "number of color channels.”


Hands-On Example: Save an Image to Your Computer!

Now, let's write some code to read an image and then save it to a different file!

import cv2 as cv # Import the OpenCV module

# Set the file path of the original image to read.
# Remember to replace 'Pandora.png' with your own image path!
file_path = 'Pandora.png'

# Use OpenCV's imread function to read the image from the specified path.
# The image data is stored in a variable called 'source_picture'.
source_picture = cv.imread(file_path)

# Check if the image was loaded successfully.
# If 'source_picture' is None (nothing), it means the image failed to load!
if source_picture is None:
    print(f"Warning: Oops! Could not load the image.")
    print(f"Please check if the file path is correct: {file_path}")
else:
    # Set the target file path to save the image.
    # Here, we'll save it as 'SavePicture.png'. 
    # You can change the name and extension to whatever you like!
    save_path = 'SavePicture.png'

    # Use OpenCV's imwrite function to save the 'source_picture' data to 
    # the specified path.
    # The file format is automatically determined by 
    # the file extension of 'save_path' (here, .png).
    cv.imwrite(save_path, source_picture)
    print(f"Congratulations! The image has been successfully saved to: {save_path}") 
    # A celebratory message if the save is successful!

    # Call cv.destroyAllWindows() to close all image windows created by OpenCV.
    # It's a good habit to free up computer resources and keep your program clean!
    cv.destroyAllWindows()

Program Result:

Visual chart of different Python built-in data types like int, float, str, and list

When you run the code above, if everything goes well, you should see a new file named SavePicture.png in the same folder as your code file! This means you successfully saved an image using your program!


This is the introduction to the imwrite function! By mastering imread and imwrite, you can easily read and save images, laying a solid foundation for your upcoming image processing projects.

 

Copyright © 2026 YUAN High-Tech Development Co., Ltd.
All rights reserved.