OpenCV Tutorial
Image Processing
Feature Detection and Description
Drawing Functions
Video Processing
Applications and Projects
Manipulating images, including scaling, rotating, shifting (translation), and performing edge detection are fundamental operations in computer vision. Here's a step-by-step tutorial using Python's OpenCV library:
Firstly, you'll need to install OpenCV:
pip install opencv-python
import cv2 import numpy as np
image = cv2.imread('path_to_image.jpg')
You can use the resize()
function:
scaled_image = cv2.resize(image, None, fx=0.5, fy=0.5) # Scaling to 50%
You can rotate an image using the getRotationMatrix2D()
and warpAffine()
functions:
(rows, cols) = image.shape[:2] matrix = cv2.getRotationMatrix2D((cols/2, rows/2), 90, 1) # Rotate 90 degrees around the image center rotated_image = cv2.warpAffine(image, matrix, (cols, rows))
You can shift an image using the warpAffine()
function:
matrix = np.float32([[1, 0, 25], [0, 1, 50]]) # Shift 25 units on X-axis and 50 units on Y-axis shifted_image = cv2.warpAffine(image, matrix, (cols, rows))
The Canny edge detector is a multi-step process that detects a wide range of edges in images:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Convert image to grayscale edges = cv2.Canny(gray, 50, 150) # Threshold values can be adjusted
To view the processed images:
cv2.imshow('Original Image', image) cv2.imshow('Scaled Image', scaled_image) cv2.imshow('Rotated Image', rotated_image) cv2.imshow('Shifted Image', shifted_image) cv2.imshow('Edges', edges) cv2.waitKey(0) cv2.destroyAllWindows()
This tutorial provides you with the basics of some common operations in image processing using OpenCV. Each of these operations can be further fine-tuned, and OpenCV provides many more functionalities to explore. Remember to always experiment with parameters and settings to achieve the best results for your specific application!
Restoring images using inpainting in Python with OpenCV:
import cv2 import numpy as np image = cv2.imread('damaged_image.jpg') mask = cv2.imread('mask.jpg', cv2.IMREAD_GRAYSCALE) result = cv2.inpaint(image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA) cv2.imshow('Original Image', image) cv2.imshow('Inpainted Image', result) cv2.waitKey(0) cv2.destroyAllWindows()
Sample code for image inpainting with OpenCV:
# Similar to the previous code snippet
Optimizing image inpainting parameters in Python with OpenCV:
# Experiment with inpainting parameters for optimal results