Site icon DataFlair

Working with Images in OpenCV

working with images in opencv

Machine Learning courses with 110+ Real-time projects Start Now!!

Hey there! If you’re fascinated by the incredible world of computer vision and image processing, then working with images in OpenCV is going to be right up your alley. Images are the heart and soul of so many captivating applications, from identifying objects to analyzing videos. Lucky for us, OpenCV, a fantastic open-source computer vision library, is here to help us make magic happen with those images.

In this article, we’ll embark on a journey together, exploring the ins and outs of working with images in OpenCV. Whether you’re just starting out or a seasoned developer, this guide will be your trusty companion, unleashing the full potential of OpenCV for all your image-related tasks.

Image file types where deployment of OpenCV is possible :

To read an image from a file using OpenCV, you need to have the following prerequisites:

1. Python and OpenCV Installed: Ensure you have Python installed on your system. Additionally, you must have OpenCV installed. You can install OpenCV using pip by running the following command:

pip install opencv-python

2. Image File: You should have the image file (e.g., JPEG, PNG, etc.) you want to read using OpenCV. Make sure you know the file’s path or place it in the same directory as your Python script.

3. Working IDE or Code Editor: You need a working integrated development environment (IDE) or a code editor where you can write and execute your Python code. Popular choices include Anaconda, Jupyter Notebook, PyCharm, Visual Studio Code, or any other Python-supported IDE.

Once you have Python, OpenCV installed, and an image file available, you are ready to read the image using OpenCV. Use the cv2.imread() function, passing the path to your image file as an argument. This will return the image data as a NumPy array, which you can further process or display as needed.

How to read an image from a file using OpenCV?

Ah, reading an image from a file is one of the fundamental steps in working with images in OpenCV. Let’s explore how you can do that!

To read an image from a file using OpenCV, you’ll need to follow these steps:

1. Import the necessary OpenCV library:

Before diving into reading images, make sure you have OpenCV installed and imported into your project.

You can typically import it with the following line of code:

Import cv2

2. Provide the path to the image file:

You’ll need to specify the path to the image file you want to read. It could be a relative or absolute path, depending on where the image is located on your system. Make sure to include the file extension (e.g., .jpg, .png, etc.). Think of it as giving OpenCV the directions to find the image in your computer’s vast storage.

3. Read the image using OpenCV’s `imread()` function:

OpenCV provides the `imread()` function, which allows you to read the image file. It outputs a NumPy array that represents the image after receiving the file location as input. It’s like opening a treasure chest filled with pixel values and colours.

Here’s an example of how to use it:

We are going to read an image of a Tiger from a file,

image = cv2.imread(r"C:\Users\sanji\Desktop\DataFlair\Working With Images in OpenCV\wildlife-tiger.jpg")

4. Check if the image was successfully read:

It’s essential to verify if the image was successfully read from the file. You can check if the `image` variable is `None` or has a valid value. If it’s `None`, it means there was an error while reading the image. It’s like checking if your friend successfully picked up the image without any mishaps.

import cv2
image = cv2.imread(r"C:\Users\sanji\Desktop\DataFlair\Working With Images in OpenCV\wildlife-tiger.jpg")

cv2.imshow('DataFlair @satchit', image)


cv2.waitKey(0)
cv2.destroyAllWindows()

Various forms of cv2.imread()

1. Reading an image as a color image: Using cv2.IMREAD_COLOUR

import cv2

color_image = cv2.imread(r"C:\Users\sanji\Desktop\DataFlair\Working With Images in OpenCV\wildlife-tiger.jpg", cv2.IMREAD_COLOR)

This method reads the image in the BGR color format (default) and preserves the color information. Each pixel is represented by three color channels: Blue, Green, and Red.

2. Reading an image as a grayscale image: Using cv2.IMREAD_GRAYSCALE

import cv2
image = cv2.imread(r"C:\Users\sanji\Desktop\DataFlair\Working With Images in OpenCV\wildlife-tiger.jpg",cv2.IMREAD_GRAYSCALE)
cv2.imshow('DataFlair @satchit', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

In this case, the image is read in grayscale mode, where each pixel value represents the intensity of the grey colour. This is useful when color information is not necessary for your image-processing tasks.

3. Reading an image as-is with alpha channel (including transparency): Using cv2.IMREAD_UNCHANGED

import cv2
image = cv2.imread(r"C:\Users\sanji\Desktop\DataFlair\Working With Images in OpenCV\wildlife-tiger.jpg",cv2.IMREAD_UNCHANGED)
cv2.imshow('DataFlair @satchit', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

This method allows you to read images that have an alpha channel, which represents transparency. It retains all color channels and additional alpha channel information

Let’s use cv2.imshow() to unveil a piece of art to the world!

import cv2
image = cv2.imread(r"C:\Users\sanji\Desktop\DataFlair\Working With Images in OpenCV\wildlife-tiger.jpg")
cv2.imshow('DataFlair @satchit', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Let’s modify the pixel values of an image. Shall we?

Modifying pixel values in an image is a fundamental technique in image processing, allowing us to enhance, manipulate, or apply various effects to an image. With OpenCV, a popular computer vision library in Python, this process becomes seamless and efficient.

import cv2
image = cv2.imread(r"C:\Users\sanji\Desktop\DataFlair\Working With Images in OpenCV\wildlife-tiger.jpg")
if image is not None:
    inverted_image = 255 - image
     cv2.imshow('DataFlair OG @satchit', image)
    cv2.imshow('DataFlair INT @satchit', inverted_image)
     cv2.waitKey(0)
    cv2.destroyAllWindows()
else:
    print("Failed to load the image.")

Here’s an easy code to know about the dimensions of the image!

import cv2
image = cv2.imread(r"C:\Users\sanji\Desktop\DataFlair\Working With Images in OpenCV\wildlife-tiger.jpg")
if image is not None:
     height, width, channels = image.shape
  print(f"Image Dimensions: {width}x{height}")
else:
    print("Failed to load the image.")

Do you want to add a border or your own sketch to the image? Let’s start!

import cv2
image = cv2.imread(r"C:\Users\sanji\Desktop\DataFlair\Working With Images in OpenCV\wildlife-tiger.jpg")
if image is not None:
     border_color = (0, 255, 0)  # Green color
     border_width = 20
bordered_image = cv2.copyMakeBorder(image, border_width, border_width, border_width, border_width, cv2.BORDER_CONSTANT, value=border_color)
cv2.imshow('Original Image', image)
    cv2.imshow('Bordered Image', bordered_image)
 cv2.waitKey(0)
    cv2.destroyAllWindows()
else:
    print("Failed to load the image.")

How to write and store an image from one file to another using OpenCV?

The cv2.imwrite() function in OpenCV is used to write/save an image to disk in a specified file format. It allows you to store the results of your image processing or analysis or simply save an image for later use or sharing.

Here are the key details you should know about cv2.imwrite():

1. Output filename: Specify the path and filename where you want to save the image. Make sure to include the appropriate file extension (e.g., `.jpg`, `.png`) to indicate the desired file format.

2. Image data: Pass the image you want to save to the function. It should be in the expected format for the chosen file format. For example, if you’re saving a color image, ensure the color channels are in the correct order (BGR).

Here’s an example of how to use cv2.imwrite() :

import cv2


image = cv2.imread(r"C:\Users\sanji\Desktop\DataFlair\Working With Images in OpenCV\wildlife-tiger.jpg")


import cv2


output_path = r"C:\Users\sanji\Desktop\DataFlair/wildlife-tiger.jpg"


cv2.imwrite(output_path, image)

In this example, we load an image using `cv2.imread()` and store it in the `image` variable. Then, we specify the path and filename for the output image using `cv2.imwrite()`. By calling this function, the image is saved to the specified location with the provided filename.

Make sure to provide the correct output path and filename to ensure the successful saving of the image. One can Perform any desired image processing or analysis between the cv2.imread() and cv2.imwrite() functions.

Summary

In the captivating world of computer vision and image processing, the ability to store images for future use is essential. With OpenCV’s remarkable `cv2.imwrite()` function, preserving your visual treasures has never been easier.

This article serves as your guide, walking you through the process of writing and storing images using OpenCV. From importing the necessary library to specifying output paths and filenames, you’ll learn the art of image preservation with a few lines of code. Unleash your creativity, secure your hard work, and unlock the power of preservation with OpenCV’s image-storing capabilities. Let’s embark on this exciting journey together!

Exit mobile version