OpenCV Image Processing Fundamentals
OpenCV provides rich image processing and computer vision functions, including image reading, display, color space conversion, filtering, edge detection, contour detection, and more.
In this chapter, we will introduce the basic concepts and common functions of OpenCV.
Image Representation and Processing
OpenCV uses NumPy arrays to represent image data. Each image is a multidimensional array, where each element corresponds to a pixel in the image. The image size and color mode can also be represented by the shape of the array.
Basic properties of an image:
- Image dimensions (Width, Height): You can dynamically bind
img.shape. - Color channels (Channels): Usually RGB (three channels), or a grayscale image (single channel).
- Data type (Data type): Common ones include
uint8(0-255 range), or can befloat32or others.
Read an image:
import cv2
img = cv2.imread('image.jpg')
-
cv2.imread()Read an image file and return a NumPy array. -
If the image path is wrong or the file does not exist, return
None。
Display an image:
# Display image
cv2.imshow("Display Window", image)
# Wait for key input
cv2.waitKey(0)
# Close all windows
cv2.destroyAllWindows()
cv2.imshow() is used to display an image, cv2.waitKey(0) waits for a key event, and cv2.destroyAllWindows() closes all windows.
Save an image:
# Save image
cv2.imwrite("output_image.jpg", image)
cv2.imwrite() saves the image to a specified path.
Basic Image Operations
1. Access and modify pixel values
# 获取像素值 (BGR 格式)
pixel_value = image[100, 100] # 获取 (100, 100) 处的像素值
# Modify pixel value
image[100, 100] = [255, 255, 255] # 将 (100, 100) 处的像素设置为白色
2. Image ROI (Region of Interest)
# 获取 ROI
roi = image[50:150, 50:150] # 获取 (50,50) 到 (150,150) 的区域
# 修改 ROI
image[50:150, 50:150] = [0, 255, 0] # 将 ROI 区域设置为绿色
3. Image channel splitting and merging
# Separate channels
b, g, r = cv2.split(image)
# Merge channels
merged_image = cv2.merge([b, g, r])
4. Image scaling, rotation, translation, and flipping
# 缩放
resized_image = cv2.resize(image, (new_width, new_height))
# 旋转
rotation_matrix = cv2.getRotationMatrix2D((center_x, center_y), angle, scale)
rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height))
# 平移
translation_matrix = np.float32([[1, 0, tx], [0, 1, ty]]) # tx, ty 为平移距离
translated_image = cv2.warpAffine(image, translation_matrix, (width, height))
# 翻转
flipped_image = cv2.flip(image, flip_code) # flip_code: 0 (垂直翻转), 1 (水平翻转), -1 (双向翻转)
Image Arithmetic Operations
1. Image addition
result = cv2.add(image1, image2)
2. Image subtraction
result = cv2.subtract(image1, image2)
3. Image blending
result = cv2.addWeighted(image1, alpha, image2, beta, gamma)
alpha and beta are weights, and gamma is a scalar value.
Image Thresholding
1. Simple thresholding
ret, thresholded_image = cv2.threshold(image, thresh, maxval, cv2.THRESH_BINARY)
thresh is the threshold, and maxval is the maximum value.
2. Adaptive thresholding
thresholded_image = cv2.adaptiveThreshold(image, maxval, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, block_size, C)
3. Otsu's binarization
ret, thresholded_image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
Image Smoothing
1. Mean filtering
blurred_image = cv2.blur(image, (kernel_size, kernel_size))
2. Gaussian filtering
blurred_image = cv2.GaussianBlur(image, (kernel_size, kernel_size), sigmaX)
3. Median filtering
blurred_image = cv2.medianBlur(image, kernel_size)
4. Bilateral filtering
blurred_image = cv2.bilateralFilter(image, d, sigmaColor, sigmaSpace)
Image Color Spaces and Conversion
OpenCV supports conversions between multiple color spaces, such as from RGB to grayscale, HSV, and others.
Image color space conversion is very important in many image processing tasks.
Convert from RGB to grayscale:
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Convert from BGR to HSV:
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
Convert from RGB to YUV:
yuv_img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
Color space conversion is a basic operation in image processing, used for different algorithms and visual effects.
Image Resizing and Cropping
OpenCV provides multiple ways to resize an image and crop image regions.
Resize an image:
resized_img = cv2.resize(img, (width, height))
Crop an image:
cropped_img = img[y1:y2, x1:x2]
You can crop a specific region of an image using slicing operations.
Image Smoothing and Denoising (Blurring)
Image smoothing can reduce noise; common blurring algorithms include Gaussian blur, mean blur, and others.
Gaussian blur:
blurred_img = cv2.GaussianBlur(img, (5, 5), 0)
Mean blur:
blurred_img = cv2.blur(img, (5, 5))
Median blur:
blurred_img = cv2.medianBlur(img, 5)
Image Edge Detection
Edge detection is a commonly used image processing technique for detecting edges in an image; the most common method is Canny edge detection.
Canny edge detection:
edges = cv2.Canny(img, 100, 200)
The Canny algorithm finds edges by computing the gradient of an image, returning a binary image where edges are white and other regions are black.
Sobel operator:
sobel_x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=5)
sobel_y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=5)
Laplacian operator:
laplacian = cv2.Laplacian(image, cv2.CV_64F)
Morphological operations
Morphological operations are commonly used for processing binary images; common operations include erosion, dilation, opening, closing, and others.
**Erosion:** Shrinks the white regions in an image.
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
eroded_img = cv2.erode(img, kernel, iterations=1)
**Dilation:** Expands the white regions in an image.
dilated_img = cv2.dilate(img, kernel, iterations=1)
Opening and closing operations:
- Opening (erosion followed by dilation): used to remove small objects.
- Closing (dilation followed by erosion): used to fill small holes in an image.
opening_img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
closing_img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
Image Contour Detection
OpenCV provides powerful contour detection functionality that can be used for object recognition, image segmentation, and other applications.
Detect contours:
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, threshold_img = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(threshold_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
Draw contours:
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
Video processing
OpenCV also supports video processing; it can read video files, capture video streams, and perform real-time processing.
Read a video:
Example
cap
=
cv2.
VideoCapture
(
'video.mp4'
)
while
cap.
isOpened
(
)
:
ret
,
frame
=
cap.
read
(
)
if
not
ret:
break
Process each frame
cv2.
imshow
(
'Video'
,
frame
)
if
cv2.
waitKey
(
1
)
&
0xFF
==
ord
(
'q'
)
:
break
cap.
release
(
)
cv2.
destroyAllWindows
(
)