使用python提取批量图片的纹理特征和颜色特征并以此为标准去分类成熟番茄和不成熟番茄
时间: 2023-11-11 17:05:37 浏览: 116
下面是使用Python提取批量图片的纹理特征和颜色特征并以此为标准去分类成熟番茄和不成熟番茄的示例代码:
```python
import cv2
import numpy as np
import os
# 定义成熟番茄和不成熟番茄文件夹路径
ripe_path = 'ripe_tomatoes/'
unripe_path = 'unripe_tomatoes/'
# 定义特征向量维度
feature_dimension = 10
# 提取纹理特征
def extract_texture_feature(image_path):
img = cv2.imread(image_path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_gray = cv2.GaussianBlur(img_gray, (5, 5), 0)
img_canny = cv2.Canny(img_gray, 100, 200)
texture_feature = np.zeros(feature_dimension)
for i in range(feature_dimension):
row_start = i * img_canny.shape[0] // feature_dimension
row_end = (i + 1) * img_canny.shape[0] // feature_dimension
texture_feature[i] = np.sum(img_canny[row_start:row_end, :]) / 255
return texture_feature
# 提取颜色特征
def extract_color_feature(image_path):
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
color_feature = np.zeros(feature_dimension)
for i in range(feature_dimension):
h_start = i * 180 // feature_dimension
h_end = (i + 1) * 180 // feature_dimension
mask = cv2.inRange(img, (h_start, 50, 50), (h_end, 255, 255))
color_feature[i] = np.sum(mask) / 255
return color_feature
# 生成特征向量并保存到文件中
def generate_feature_vectors_and_labels(path, label):
feature_vectors = []
labels = []
for file in os.listdir(path):
if file.endswith('.jpg'):
image_path = os.path.join(path, file)
texture_feature = extract_texture_feature(image_path)
color_feature = extract_color_feature(image_path)
feature_vector = np.concatenate((texture_feature, color_feature))
feature_vectors.append(feature_vector)
labels.append(label)
return feature_vectors, labels
# 生成训练数据和测试数据
ripe_feature_vectors, ripe_labels = generate_feature_vectors_and_labels(ripe_path, 1)
unripe_feature_vectors, unripe_labels = generate_feature_vectors_and_labels(unripe_path, 0)
feature_vectors = np.concatenate((ripe_feature_vectors, unripe_feature_vectors))
labels = np.concatenate((ripe_labels, unripe_labels))
data = list(zip(feature_vectors, labels))
np.random.shuffle(data)
feature_vectors, labels = zip(*data)
feature_vectors = np.array(feature_vectors)
labels = np.array(labels)
train_feature_vectors = feature_vectors[:int(len(feature_vectors) * 0.8)]
train_labels = labels[:int(len(labels) * 0.8)]
test_feature_vectors = feature_vectors[int(len(feature_vectors) * 0.8):]
test_labels = labels[int(len(labels) * 0.8):]
# 训练分类器并测试
svm = cv2.ml.SVM_create()
svm.setType(cv2.ml.SVM_C_SVC)
svm.setKernel(cv2.ml.SVM_LINEAR)
svm.train(train_feature_vectors, cv2.ml.ROW_SAMPLE, train_labels)
_, accuracy = svm.predict(test_feature_vectors)
print('Accuracy:', accuracy)
```
这个代码中,我们首先定义了成熟番茄和不成熟番茄的文件夹路径,并定义了特征向量维度。然后,我们定义了函数 `extract_texture_feature()` 和 `extract_color_feature()`,分别用于提取纹理特征和颜色特征。接着,我们使用这两个函数提取每张图片的特征向量,并将其与标签一起保存到数组中。然后,我们随机打乱数据,将其分为训练数据和测试数据。最后,我们使用 `cv2.ml.SVM_create()` 函数创建一个 SVM 分类器,并使用训练数据训练该分类器。训练完成后,我们使用测试数据测试该分类器的准确率并输出结果。
阅读全文