详解OpenCV实现特征提取的方法

1. 颜色

a. HSV（色相饱和度值）

：描述颜色的强度

```import cv2

hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
cv2_imshow(hsv_image)```

RGB 与 HSV 颜色空间

b. LAB

L：描述颜色的亮度，与强度互换使用

A : 颜色成分范围，从绿色到品红色

B：从蓝色到黄色的颜色分量

```import cv2

lab_image = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
cv2_imshow(lab_image)```

RGB 与 LAB 色彩空间

YCrCb

Y : 伽马校正后从 RGB 颜色空间获得的亮度

Cr：描述红色 (R) 分量与亮度的距离

Cb：描述蓝色 (B) 分量与亮度的距离

```import cv2

ycrcb_image = cv2.cvtColor(image, cv2.COLOR_BGR2YCrCb)
cv2_imshow(ycrcb_image)```

RGB 与 YCrCb 颜色空间

```import cv2
import numpy as np
import plotly.figure_factory as ff

# Check the distribution of red values
red_values = []
for i in range(len(images)):
red_value = np.mean(images[i][:, :, 0])
red_values.append(red_value)

# Check the distribution of green values
green_values = []
for i in range(len(images)):
green_value = np.mean(images[i][:, :, 1])
green_values.append(green_value)

# Check the distribution of blue values
blue_values = []
for i in range(len(images)):
blue_value = np.mean(images[i][:, :, 2])
blue_values.append(blue_value)

# Plotting the histogram
fig = ff.create_distplot([red_values, green_values, blue_values], group_labels=["R", "G", "B"], colors=["red", "green", "blue"])
fig.update_layout(showlegend=True, template="simple_white")
fig.update_layout(title_text="Distribution of channel values across images in RGB")
fig.data[0].marker.line.color = "rgb(0, 0, 0)"
fig.data[0].marker.line.width = 0.5
fig.data[1].marker.line.color = "rgb(0, 0, 0)"
fig.data[1].marker.line.width = 0.5
fig.data[2].marker.line.color = "rgb(0, 0, 0)"
fig.data[2].marker.line.width = 0.5
fig```

```import cv2

cv2_imshow(image_spot)

# Converting it to HSV color space
hsv_image_spot = cv2.cvtColor(image_spot, cv2.COLOR_BGR2HSV)
cv2_imshow(hsv_image_spot)

# Setting the black pixel mask and perform bitwise_and to get only the black pixels
mask = cv2.inRange(hsv_image_spot, (0, 0, 0), (180, 255, 40))

RGB vs HSV vs Masked 图像使用 cv2.inRange() 检索黑点

```import cv2

image_spot_reshaped = image_spot.reshape((image_spot.shape[0] * image_spot.shape[1], 3))

# convert to np.float32
Z = np.float32(image_spot_reshaped)
# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 2
ret, label, center = cv2.kmeans(Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((image_spot.shape))

cv2_imshow(res2)```

1. 轮廓面积
2. 轮廓周长
3. 轮廓近似
4. 凸包
5. 凸性检测
6. 矩形边界
7. 最小外接圆
8. 拟合椭圆
9. 拟合直线

3. 纹理

a. GLCM

```import cv2

gray = cv2.cvtColor(image_spot, cv2.COLOR_BGR2GRAY)

# Find the GLCM
import skimage.feature as feature

# Param:
# source image
# List of pixel pair distance offsets - here 1 in each direction
# List of pixel pair angles in radians
graycom = feature.greycomatrix(gray, [1], [0, np.pi/4, np.pi/2, 3*np.pi/4], levels=256)

# Find the GLCM properties
contrast = feature.greycoprops(graycom, "contrast")
dissimilarity = feature.greycoprops(graycom, "dissimilarity")
homogeneity = feature.greycoprops(graycom, "homogeneity")
energy = feature.greycoprops(graycom, "energy")
correlation = feature.greycoprops(graycom, "correlation")
ASM = feature.greycoprops(graycom, "ASM")

print("Contrast: {}".format(contrast))
print("Dissimilarity: {}".format(dissimilarity))
print("Homogeneity: {}".format(homogeneity))
print("Energy: {}".format(energy))
print("Correlation: {}".format(correlation))
print("ASM: {}".format(ASM))```

b.  LBP

• https://www.pyimagesearch.com/2015/12/07/local-binary-patterns-with-python-opencv/
• https://towardsdatascience.com/face-recognition-how-lbph-works-90ec258c3d6b

```import cv2

class LocalBinaryPatterns:
self.numPoints = numPoints

def describe(self, image, eps = 1e-7):
lbp = feature.local_binary_pattern(image, self.numPoints, self.radius, method="uniform")
(hist, _) = np.histogram(lbp.ravel(), bins=np.arange(0, self.numPoints+3), range=(0, self.numPoints + 2))

# Normalize the histogram
hist = hist.astype("float")
hist /= (hist.sum() + eps)

return hist, lbp

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
desc = LocalBinaryPatterns(24, 8)
hist, lbp = desc.describe(gray)
print("Histogram of Local Binary Pattern value: {}".format(hist))

contrast = contrast.flatten()
dissimilarity = dissimilarity.flatten()
homogeneity = homogeneity.flatten()
energy = energy.flatten()
correlation = correlation.flatten()
ASM = ASM.flatten()
hist = hist.flatten()

features = np.concatenate((contrast, dissimilarity, homogeneity, energy, correlation, ASM, hist), axis=0)
cv2_imshow(gray)
cv2_imshow(lbp)```