# 提取特征并保存 def get_feat(image_list, name_list, label_list, savePath): i = 0 for image in image_list: try: # 如果是灰度图片 把3改为-1 image = np.reshape(image, (image_height, image_width, 3)) except: print('发送了异常,图片大小size不满足要求:',name_list[i]) continue gray = rgb2gray(image) / 255.0 # 这句话根据你的尺寸改改 fd = hog(gray, orientations=12,block_norm='L1', pixels_per_cell=[8, 8], cells_per_block=[4, 4], visualize=False, transform_sqrt=True) fd = np.concatenate((fd, [label_list[i]])) fd_name = name_list[i] + '.feat' fd_path = os.path.join(savePath, fd_name) joblib.dump(fd, fd_path) i += 1 print("Test features are extracted and saved.")加入颜色特征代码
时间: 2024-02-14 08:15:28 浏览: 129
以下是添加颜色特征的代码示例:
```python
import cv2
import glob
import os
import numpy as np
from skimage.feature import hog
from skimage.color import rgb2gray
from sklearn.externals import joblib
def get_feat(image_list, name_list, label_list, savePath):
i = 0
for image in image_list:
try:
# 如果是灰度图片 把3改为-1
image = np.reshape(image, (image_height, image_width, 3))
except:
print('发送了异常,图片大小size不满足要求:',name_list[i])
continue
gray = rgb2gray(image) / 255.0
# 添加颜色特征
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
color_hist = cv2.calcHist([hsv], [0, 1, 2], None, [8, 8, 8], [0, 180, 0, 256, 0, 256])
color_hist = cv2.normalize(color_hist, color_hist).flatten()
# 使用 HOG 特征
hog_feat = hog(gray, orientations=12, block_norm='L1', pixels_per_cell=[8, 8], cells_per_block=[4, 4], visualize=False, transform_sqrt=True)
# 组合特征向量
feat = np.concatenate((hog_feat, color_hist, [label_list[i]]))
feat_name = name_list[i] + '.feat'
feat_path = os.path.join(savePath, feat_name)
joblib.dump(feat, feat_path)
i += 1
print("Features are extracted and saved.")
```
在这个示例中,首先使用 OpenCV 的 cvtColor 函数将图像从 RGB 转换为 HSV,然后使用 calcHist 函数计算 HSV 颜色直方图。接下来,使用 normalize 函数对颜色直方图进行归一化,并将其展平为一维数组。最后,将 HOG 特征和颜色特征连接起来,形成最终的特征向量。
阅读全文