版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/weixin_44474718/article/details/86772255
一、使用色彩空间
RGB 红绿蓝
HSV 色相 饱和度 明度
HLS 色相 亮度 饱和度
1.1、以RGB色彩空间编码图像
RGB实际上是以BRG顺序进行保存的。
HSV ( Hue Saturation Value )using cv2.COLOR_BGR2HSV
HLS (hue, lightness, saturation) using cv2.COLOR_BGR2HLS
LAB (lightness, green-red, and blue-yellow) using cv2.COLOR_BGR2LAB
YUV (overall luminance, blue-luminance, red-luminance) using cv2.COLOR_BGR2YUV
import cv2
import matplotlib.pyplot as plt
img_bgr = cv2.imread('data/lena.jpg')
img_rgb = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2RGB) # 将bgr转换成rgb
plt.figure(figsize=(12, 6))
plt.subplot(121)
plt.imshow(img_bgr)
plt.subplot(122)
plt.imshow(img_rgb)
plt.show()
二、图像角点检测(检测边缘)
OpenCV provides at least two different algorithms to find corners in an image:
Harris corner detection: Knowing that edges are areas with high-intensity changes in all directions, Harris and Stephens came up with a fast way of finding such areas. This algorithm is implemented as cv2.cornerHarris
in OpenCV.
Shi-Tomasi corner detection: Shi and Tomasi have their own idea of what are good features to track, and they usually do better than Harris corner detection by finding the N strongest corners. This algorithm is implemented as cv2.goodFeaturesToTrack
in OpenCV.
Harris corner detection works only on grayscale images, so we first want to convert our BGR image to grayscale:
参数解释
cornerHarris(src, blockSize, ksize, k, dst=None, borderType=None)
blockSize:设置角点检测像素领域大小
ksize:边缘检测的孔径大小
k: 自由参数
# 使用角点检测
img_gray = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2GRAY) #转换成灰度图
corners = cv2.cornerHarris(img_gray,2,3,0.04)
plt.imshow(corners,cmap='gray')
plt.show()
三、使用尺度不变特征变换(Scale-Invariant Feature Transform )
The algorithm works in two steps:
detect: This step identifies interesting points in an image (also known as keypoints)
compute: This step computes the actual feature values for every keypoint.
# 使用尺度不变特征变换
sift = cv2.xfeatures2d.SIFT_create()
kp = sift.detect(img_bgr) # 检测关键点
# 关键点可视化
img_kp = np.zeros_like(img_bgr)
img_kp = cv2.drawKeypoints(img_rgb,kp,img_kp,flags=cv2.cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
plt.imshow(img_kp)
plt.show()
# 计算特征描述符
kp , des = sift.compute(img_bgr,kp)
#print(des.sharp)
# 同时进行检测与计算关键点
kp2 ,des2 = sift.detectAndCompute(img_bgr,None)
四、使用加速健壮特征(Speeded Up Robust Features)
SURF比SIFT速度快,并且SURF比SIFT能检测到更多的特征。
surf = cv2.xfeatures2d.SURF_create()
kp1 = surf.detect(img_bgr)
img_kp = np.zeros_like(img_bgr)
img_kp = cv2.drawKeypoints(img_rgb, kp1, img_kp,flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
plt.figure(figsize=(12, 6))
plt.imshow(img_kp)
plt.show()
运行sift = cv2.xfeatures2d.SIFT_create()
出现AttributeError: module ‘cv2.cv2’ has no attribute ‘xfeatures2d’
解决方案参考:https://blog.csdn.net/linghugoolge/article/details/85229411
但是SIFT和SURF都受专利法律保护。可以用cv2.ORB
代替。