In this article, we will embark on an exciting journey to learn how to manipulate and analyze images using Python and the OpenCV library. Starting from the basics, we will understand how to load, display, and save images, as well as perform fundamental operations such as resizing, cropping, and rotating. We'll also explore more advanced techniques including color space conversions, image filtering, and edge detection.
Before we begin, make sure to have Python installed in your system. If not, you can download and install it from the official Python website. Next, we'll need to install OpenCV. You can do this by running the following command in your terminal:
pip install opencv-python
Let's start with the basics. Here's how you can load an image with OpenCV:
import cv2
# Load an image
img = cv2.imread('example.jpg')
After loading an image, displaying it is quite straightforward:
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
You can save the modified image using the following command:
cv2.imwrite('example_modified.jpg', img)
resized_img = cv2.resize(img, (new_width, new_height))
cropped_img = img[y:y+h, x:x+w]
(height, width) = img.shape[:2]
center = (width // 2, height // 2)
matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated_img = cv2.warpAffine(img, matrix, (width, height))
Let's now dive into more advanced techniques.
You can convert an image from one color space to another using the cvtColor function. Here's an example of converting an image to grayscale:
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Edge detection is an image processing technique for finding the boundaries of objects within images. Here's how you can implement it using the Canny function:
edges = cv2.Canny(img, threshold1, threshold2)
Ready to start learning? Start the quest now