knn 模型训练
data数据集的根目录, windows这样使用
# 加载数据
data_folder = './data'
# data_folder = 'D:/\st_dev/\data'
print(data_folder)
X, y = load_data(data_folder)
da 文件夹,da是数据集的标签, da中存放一类相似的图片数据。 用于训练
re 存放两一类相似 图片数据; re是识别后的标签。
模型文件保存项目根目录
# 保存模型
model_filename = 'knn_model.pkl'
with open(model_filename, 'wb') as model_file:
pickle.dump(knn_classifier, model_file)
`
``js
import os
import pickle
from skimage import io, transform
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
导入UGOT机器人库
from ugot import ugot
import cv2
函数:从文件夹加载图像数据
def load_data(data_folder):
data = []
labels = []
for folder in os.listdir(data_folder):
folder_path = os.path.join(data_folder, folder)
print("正在:", folder_path) # 新增的打印语句
if os.path.isdir(folder_path):
label = folder
for filename in os.listdir(folder_path):
print("正在读取文件:", filename) # 新增的打印语句
img_path = os.path.join(folder_path, filename)
img = io.imread(img_path)
img = transform.resize(img, (50, 50)) # 调整图像大小为50x50像素
data.append(img.flatten()) # 将图像数据展平
labels.append(label)
return data, labels
加载数据
data_folder = './data'
data_folder = 'D:/\st_dev/\data'
print(data_folder)
X, y = load_data(data_folder)
将数据拆分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
初始化KNN分类器
knn_classifier = KNeighborsClassifier(n_neighbors=1)
训练模型
knn_classifier.fit(X_train, y_train)
评估模型
accuracy = knn_classifier.score(X_test, y_test)
print("Accuracy:", accuracy)
保存模型
model_filename = 'knn_model.pkl'
with open(model_filename, 'wb') as model_file:
pickle.dump(knn_classifier, model_file)
加载模型
with open(model_filename, 'rb') as model_file:
loaded_model = pickle.load(model_file)
函数:预测图像内容
def predict_image(img):
img = transform.resize(img, (50, 50))
flattened_img = img.flatten()
prediction = loaded_model.predict([flattened_img])
return prediction[0]
def predict_and_display_image(img):
img_resized = transform.resize(img, (50, 50))
flattened_img = img_resized.flatten()
prediction = loaded_model.predict([flattened_img])[0]
print(prediction) #调试信息
# 在图像上显示预测结果
cv2.putText(img, f'Prediction: {prediction}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
cv2.imshow('Image', img)
cv2.waitKey(1)
# cv2.destroyAllWindows()
初始化UGOT机器人
got = ugot.UGOT()
got.initialize('10.10.4.230')
got.open_camera()
try:
while True:
frame = got.read_camera_data()
if frame is not None:
nparr = np.frombuffer(frame, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
# 使用加载的模型进行预测并在图像上显示结果
predict_and_display_image(img)
# 在此处添加物体跟随和闭环控制逻辑
# print('-------:', got.get_knn_result('knn_model'))
except KeyboardInterrupt:
print('-----KeyboardInterrupt')
```