想问一下猫狗识别程序那一篇文章中代码detect-py为什么运行出错
典型的字符集不匹配
把py文件还有所有用到的txt文件全部存为utf8格式
# 第一步:导入库以及定义一些参数
import os, random
from matplotlib.pyplot import imshow
import numpy as np
import matplotlib.pyplot as plt
IMG_W,IMG_H,IMG_CH=150,150,3 #设置图片的大小,这个大小要和神经网络的第一层输入有关
# 第二步:定义一个函数,从测试文件夹内读取任意一张图片。
def read_random_image():
folder=r"./Imgs/" #修改成你的数据集地址
file_path = folder + random.choice(os.listdir(folder)) #随机获取文件内图片的地址
pil_im = Image.open(file_path, 'r') #打开这个图片
return pil_im #返回
# 第三步:定义一个预测函数
# 用训练好的模型来预测新样本
from PIL import Image
from keras.preprocessing import image
def predict(model, img, target_size):
name = ["猫", "狗"]
if img.size != target_size: #如果图片的大小不是目标大小则修改
img = img.resize(target_size)
x = image.img_to_array(img) #将图片转换成二维数组准备输入模型
x *= 1. / 255 #归一化,矩阵*1/255.0,相当于将像素值转换到0~1
x = np.expand_dims(x, axis=0) #调整图片维度为零
preds = model.predict(x) #执行模型自带的预测函数,参数为x
imshow(np.asarray(img)) #输出图片,提高可视度
print(preds) #打印预测结果
for i in range(2):
if preds[0][i]>0.5: #打印超过0.5概率的类别名字
print(name[i])
break
#第四步:载入模型并预测
# 载入训练保存的模型
from keras.models import load_model
model_path = './model.h5' #模型地址
model = load_model(model_path)
print("下面将抽五张图并预测如下:")
for i in range(5):
print("该图片的猫狗概率如下:")
predict(model,read_random_image(),(IMG_W,IMG_H)) #预测函数
plt.show()
# 评估函数下面运行后可以评估模型的平均准确率,损失函数
'''
test_datagen = ImageDataGenerator(rescale=1. / 255) # 只需要和trainset同样的scale即可,不需增强
test_data_dir="./data_oppo/train"
val_generator = test_datagen.flow_from_directory(
test_data_dir,
target_size=(IMG_W, IMG_H),
batch_size=32,
color_mode='rgb',
class_mode='categorical')
test_loss,test_acc=model.evaluate(val_generator)
print("test_acc={} test_loss={}".format(test_acc,test_loss))
'''
以下是跑通这个程序的过程。如果清楚这些步骤的过程可以略过下面