以下是一些简单的特征提取算法的Python代码示例:
1. 边缘检测(Sobel算子)
python
import cv2
import numpy as np
# 读取图像
image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
# 使用Sobel算子进行边缘检测
sobel_x = cv2.Sobel(image, cv2.CV_64F, 1, 0)
sobel_y = cv2.Sobel(image, cv2.CV_64F, 0, 1)
# 计算梯度的幅度
gradient_magnitude = np.sqrt(sobel_x**2 + sobel_y**2)
# 展示结果
cv2.imshow('Sobel Edge Detection', gradient_magnitude)
cv2.waitKey(0)
cv2.destroyAllWindows()
2. 颜色直方图
python
import cv2
import numpy as np
# 读取图像
image = cv2.imread('image.jpg')
# 转换到HSV空间
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# 定义HSV中蓝色的范围
blue_lower = np.array([110,50,50])
blue_upper = np.array([130,255,255])
# 设置HSV的阈值使得只有蓝色的部分显示
mask = cv2.inRange(hsv_image, blue_lower, blue_upper)
# 展示结果
cv2.imshow('Color Histogram', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
3. 局部二值模式(LBP)
python
import cv2
import numpy as np
# 读取图像
image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
# 使用LBP算法
radius = 3
points = 8
lbp_image = cv2.circle(image, (radius, radius), radius, 1, -1)
lbp_result = cv2.circle(image.copy(), (radius, radius), radius, 0, -1)
# 展示结果
cv2.imshow('LBP', lbp_result)
cv2.waitKey(0)
cv2.destroyAllWindows()
4. HOG特征提取
python
import cv2
import numpy as np
# 读取图像
image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
# 创建HOG描述符对象
winSize = (64, 128)
blockSize = (16, 16)
blockStride = (8, 8)
cellSize = (8, 8)
hog = cv2.HOGDescriptor(winSize, blockSize, blockStride, cellSize, 9)
# 计算HOG特征
hog_features = hog.compute(image)
# 展示结果(转换为图像)
hog_image = cv2.normalize(hog_features, None, 0, 255, cv2.NORM_MINMAX)
hog_image = hog_image.astype('uint8')
cv2.imshow('HOG Features', hog_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
请注意,这些代码示例使用了OpenCV库,因此您需要先安装OpenCV才能运行这些代码。您可以通过pip安装OpenCV:
bash
pip install opencv-python
这些示例仅用于教学目的,实际应用中可能需要更复杂的设置和优化。