机器学习day2
使用KNN算法实现机器学习 给我一个苹果的图片 我能预测出这个是一个苹果
代码:
# 导入需要的库
# 读图
import os
import cv2
# 绘图
import matplotlib.pyplot as plt
import seaborn as sns
# 数组
import numpy as np
from skimage.feature import hog
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier# 设置主题
sns.set_theme(style="darkgrid")
# 设置中文
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False# 获取苹果数据集
def apple_analysis(apple,no_apple):xx,yy=[],[]# 苹果图像处理# os.listdir() 列出指定目录下的所有文件和子目录名称for file in os.listdir(apple):if file.endswith(('.jpg','.png')):features = feature_engine(os.path.join(apple,file))xx.append(features)yy.append(1) # 苹果标签为1# 处理非苹果图片for file in os.listdir(no_apple):if file.endswith(('.jpg', '.png')):features = feature_engine(os.path.join(no_apple,file))xx.append(features)yy.append(0) # 非苹果标签为0return np.array(xx),np.array(yy)
# 特征工程
def feature_engine(path,target_size=(128,128)):# 读取图像img=cv2.imread(path)# 转换图像格式为RGBimg=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)# 统一图像大小img_resized=cv2.resize(img,target_size)# 灰度图和hsv图image_gray=cv2.cvtColor(img_resized,cv2.COLOR_RGB2GRAY)image_hsv=cv2.cvtColor(img_resized,cv2.COLOR_RGB2HSV)# HOG特征hog_feat=hog(image_gray,orientations=9, # 将180°角度划分为9个区间 捕获苹果圆形轮廓渐变方向特征pixels_per_cell=(16, 16), # 图像划分为16✖16像素细胞单元 平衡捕捉苹果纹理cells_per_block=(2, 2), # 每个特征块包含2✖2个细胞单元 归一化,增强光照不变性,适合不同光线下的苹果visualize=False # 不返回特征可视化图像)# 颜色直方图hist_feat = cv2.calcHist([image_hsv],[0, 1, 2],None,[8, 8, 8],[0, 256, 0, 256, 0, 256]).flatten()# 合并特征return np.hstack([hog_feat, hist_feat])if __name__ == '__main__':# 数据准备apple_dir = "./apple/apple"non_apple_dir = "./apple/no_apple"x,y=apple_analysis(apple_dir,non_apple_dir)# 数据集划分x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=15)# 模型训练KNN_model=KNeighborsClassifier(n_neighbors=5)KNN_model.fit(x_train,y_train)# 模型评估y_predict=KNN_model.predict(x_test)print("对比:",y_predict == y_test)# 预测示例test_path='./banana.png' # test_path='./apple.png'test_features = feature_engine(test_path)test_predict=KNN_model.predict(test_features)print(f"\nThe image is: {'Apple' if test_predict[0] == 1 else 'not Apple'}")# 可视化测试图片img = cv2.cvtColor(cv2.imread(test_path), cv2.COLOR_BGR2RGB)plt.imshow(img)plt.title(f" Prediction: {'Is Apple' if test_predict[0] == 1 else 'Not Apple'}")plt.axis('off')plt.show()
运行结果: