python图像水果识别分类
时间: 2023-06-17 15:07:56 浏览: 134
要进行图像水果识别分类,可以使用深度学习模型,比如卷积神经网络(Convolutional Neural Network, CNN)。以下是一个用CNN进行水果识别分类的Python代码示例:
1. 导入必要的库:
```python
import os
import cv2
import numpy as np
from sklearn.model_selection import train_test_split
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
```
2. 定义数据集路径和类别:
```python
# 数据集路径
data_path = "./fruits-360/Training/"
# 定义类别
classes = sorted(os.listdir(data_path))
num_classes = len(classes)
```
3. 加载数据集:
```python
images = []
labels = []
for i, fruit_class in enumerate(classes):
path = data_path + fruit_class + "/"
for img in os.listdir(path):
img = cv2.imread(path + img)
img = cv2.resize(img, (100, 100))
images.append(img)
labels.append(i)
X = np.array(images)
y = np.array(labels)
# 将标签转换成one-hot编码
y = np_utils.to_categorical(y, num_classes)
```
4. 划分数据集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
```
5. 构建CNN模型:
```python
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
```
6. 编译模型:
```python
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
```
7. 训练模型:
```python
model.fit(X_train, y_train, batch_size=64, epochs=10, validation_data=(X_test, y_test))
```
8. 测试模型:
```python
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
以上就是一个简单的图像水果识别分类的Python代码示例,你可以按照以上步骤进行实现。
阅读全文