Hands-on Guide: Basic Image Operations using OpenCV in Python

OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. It contains various functions for image processing, video analysis, and camera calibration. In this guide, we will learn how to perform basic image operations using OpenCV in Python, such as loading, displaying, resizing, and saving images.

Prerequisites

Before we start, make sure you have the following installed:

  1. Python 3.x
  2. OpenCV library for Python. You can install it using pip:
pip install opencv-python

Loading an Image

To load an image from a file, use the imread() function. It takes the image file path as an argument and returns a NumPy array representing the image.

import cv2

image_path = 'path/to/your/image.jpg'
image = cv2.imread(image_path)

Displaying an Image

To display the loaded image, use the imshow() function. It takes two arguments: the window name and the image array. Use the waitKey() function to pause the script execution until a key is pressed, and the destroyAllWindows() function to close the window.

cv2.imshow('My Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Resizing an Image

To resize an image, use the resize() function. It takes two arguments: the image array and the desired size (width, height) as a tuple. You can also specify the interpolation method using the interpolation parameter.

width = 300
height = 200
resized_image = cv2.resize(image, (width, height), interpolation=cv2.INTER_LINEAR)

Saving an Image

To save an image to a file, use the imwrite() function. It takes two arguments: the output file path and the image array.

output_path = 'path/to/save/image.jpg'
cv2.imwrite(output_path, resized_image)

Complete Example

Here's a complete example that demonstrates how to load, display, resize, and save an image using OpenCV in Python:

import cv2

# Load an image
image_path = 'path/to/your/image.jpg'
image = cv2.imread(image_path)

# Display the original image
cv2.imshow('Original Image', image)

# Resize the image
width = 300
height = 200
resized_image = cv2.resize(image, (width, height), interpolation=cv2.INTER_LINEAR)

# Display the resized image
cv2.imshow('Resized Image', resized_image)

# Save the resized image
output_path = 'path/to/save/image.jpg'
cv2.imwrite(output_path, resized_image)

# Wait for a key press and close the window
cv2.waitKey(0)
cv2.destroyAllWindows()

That's it! Now you know how to perform basic image operations using OpenCV in Python. You can use these skills as a foundation for more advanced image processing tasks, such as object detection, image segmentation, or face recognition.

An AI coworker, not just a copilot

View VelocityAI