Rotating and cropping the images in Python using opencv
- 2023年5月09日
- 技術情報
Today, I would like to share how to rotate and crop the images in Python using opencv.
Rotating and cropping are common image processing techniques used to manipulate digital images. Python OpenCV is a powerful library for image processing that provides numerous tools for image manipulation. In this tutorial, we will learn how to rotate and crop images using Python OpenCV.
1. Installing OpenCV
First, we need to install OpenCV in our system. If you haven’t installed OpenCV yet, you can install it using pip:
pip install opencv-python
2. Loading an Image
After installing OpenCV, we can load an image using the imread() function. The imread() function takes the image file path as an argument and returns an array representing the image.
import cv2
# Load image
image = cv2.imread('path/to/image.jpg')
3. Rotating an Image
Rotating an image involves changing the orientation of the image. We can use the cv2.rotate() function to rotate an image. The cv2.rotate() function takes three arguments: the image, the rotation type, and the angle of rotation.
# Rotate image
rotated_image = cv2.rotate(image, cv2.cv2.ROTATE_90_CLOCKWISE)
In the above example, we have rotated the image 90 degrees clockwise.
4. Cropping an Image
Cropping an image involves selecting a portion of the image and discarding the rest. We can use array slicing to crop an image. The array slicing notation is [start_row:end_row, start_column:end_column].
# Crop image
cropped_image = image[start_row:end_row, start_column:end_column]
In the above example, we have cropped the image from start_row to end_row and start_column to end_column.
5. Displaying Images
After rotating or cropping an image, we can display the images using the cv2.imshow() function. The cv2.imshow() function takes two arguments: the name of the window and the image.
# Display images
cv2.imshow('Original Image', image)
cv2.imshow('Rotated Image', rotated_image)
cv2.imshow('Cropped Image', cropped_image)
# Wait for a key press and close all windows
cv2.waitKey(0)
cv2.destroyAllWindows()
6. Saving an Image
We can save the rotated or cropped image using the cv2.imwrite() function. The cv2.imwrite() function takes two arguments: the name of the file and the image.
# Save image
cv2.imwrite('path/to/saved/image.jpg', rotated_image)
In the above example, we have saved the rotated image to a file named ‘saved_image.jpg’ in the specified path.
Conclusion
In this tutorial, we have learned how to rotate and crop images using Python OpenCV. We have also learned how to display and save images. These are just a few of the many image processing techniques that can be performed using OpenCV. With OpenCV, we can perform a wide range of image processing tasks, from simple operations like cropping and rotating to more complex operations like edge detection and object recognition.
This is all for now. Hope you enjoy that.
By Asahi
waithaw at 2023年05月09日 10:00:00