python 图像识别分类_使用Python轻松完成垃圾分类(基于图像识别)
时间: 2024-05-09 15:16:46 浏览: 155
使用Python轻松完成垃圾分类(基于图像识别)
垃圾分类是一项非常重要的环保工作,而图像识别技术能够在垃圾分类中发挥重要作用。本文将介绍如何使用Python及其相关库实现垃圾分类的图像识别分类。
首先,我们需要准备一些垃圾图片数据集,可以从网上下载或者自己拍摄收集。数据集需要包括有害垃圾、可回收垃圾、厨余垃圾和其他垃圾等分类。
接下来,我们需要使用Python的图像处理库Pillow和机器学习库scikit-learn来进行图像分类。具体步骤如下:
1.导入所需库
```python
from PIL import Image
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
```
2.读取图片数据集
```python
def load_data():
# 图片大小
size = (64, 64)
# 数据集路径
data_path = 'data/'
# 分类标签
labels = {'harmful': 0, 'recyclable': 1, 'kitchen': 2, 'other': 3}
X, y = [], []
for label, tag in labels.items():
for i in range(1, 201):
img_path = data_path + label + '/' + str(i) + '.jpg'
img = Image.open(img_path).convert('RGB').resize(size)
X.append(np.array(img))
y.append(tag)
return np.array(X), np.array(y)
```
3.数据集划分
将读取到的数据集划分为训练集和测试集,一般采用8:2的比例。
```python
def split_data(X, y):
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
return X_train, X_test, y_train, y_test
```
4.特征提取
使用灰度化、去噪等技术提取图像的特征。
```python
def feature_extraction(X):
# 灰度化
gray = np.mean(X, -1)
# 去噪
blur = np.array([Image.fromarray(gray[i]).filter(ImageFilter.BLUR) for i in range(gray.shape[0])])
return blur.reshape(blur.shape[0], -1)
```
5.模型训练和预测
使用KNN算法进行模型训练和预测。
```python
def knn(X_train, X_test, y_train):
# KNN分类器
clf = KNeighborsClassifier(n_neighbors=5)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
return y_pred
```
6.结果评估
使用accuracy_score函数计算模型的准确率。
```python
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
完整代码如下:
```python
from PIL import Image, ImageFilter
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
# 加载数据集
def load_data():
# 图片大小
size = (64, 64)
# 数据集路径
data_path = 'data/'
# 分类标签
labels = {'harmful': 0, 'recyclable': 1, 'kitchen': 2, 'other': 3}
X, y = [], []
for label, tag in labels.items():
for i in range(1, 201):
img_path = data_path + label + '/' + str(i) + '.jpg'
img = Image.open(img_path).convert('RGB').resize(size)
X.append(np.array(img))
y.append(tag)
return np.array(X), np.array(y)
# 数据集划分
def split_data(X, y):
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
return X_train, X_test, y_train, y_test
# 特征提取
def feature_extraction(X):
# 灰度化
gray = np.mean(X, -1)
# 去噪
blur = np.array([Image.fromarray(gray[i]).filter(ImageFilter.BLUR) for i in range(gray.shape[0])])
return blur.reshape(blur.shape[0], -1)
# KNN训练和预测
def knn(X_train, X_test, y_train):
# 特征提取
X_train = feature_extraction(X_train)
X_test = feature_extraction(X_test)
# KNN分类器
clf = KNeighborsClassifier(n_neighbors=5)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
return y_pred
if __name__ == '__main__':
# 加载数据集
X, y = load_data()
# 数据集划分
X_train, X_test, y_train, y_test = split_data(X, y)
# 模型训练和预测
y_pred = knn(X_train, X_test, y_train)
# 结果评估
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
运行上述代码后,模型将对测试集进行预测并输出准确率。这样我们就实现了基于图像识别的垃圾分类。
阅读全文