生椰拿铁太狼 2022-12-25 17:36 采纳率: 75%
浏览 11
已结题

训练与测试模型时所用图片的分辨率不同,运行时出错该怎么解决?

    如题,训练模型时候输入的图片分辨率是28x28的,但是测试模型时用自己拍的图片分辨率会很大,然后没法放进模型里。有没有什么办法不改变训练集的图片分辨率,但是用自己拍的照片放进去也能测试。

    现在用的是resize把图片改成28x28,但是分辨率太小会影响判断。

全部代码

import matplotlib.pyplot as plt
from keras.utils import to_categorical
from keras import models, layers, regularizers
from keras.optimizers import RMSprop
from keras.datasets import mnist
import tensorflow as tf
import os
import cv2
import dlib
import numpy as np
import tensorflow as tf
tf.compat.v1.disable_eager_execution()

# 调用GPU
config=tf.compat.v1.ConfigProto(allow_soft_placement=True)  ##:如果你指定的设备不存在,允许TF自动分配设备
config.gpu_options.allow_growth=True  ##动态分配内存
sess=tf.compat.v1.Session(config=config)

# 加载数据集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((60000, 28*28)).astype('float')
test_images = test_images.reshape((10000, 28*28)).astype('float')
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

# 搭建神经网络
estimator = models.Sequential()
estimator.add(layers.Dense(units=128, activation='relu', input_shape=(28*28, ),
                         kernel_regularizer=regularizers.l1(0.0001)))
estimator.add(layers.Dropout(0.01))
estimator.add(layers.Dense(units=32, activation='relu',
                         kernel_regularizer=regularizers.l1(0.0001)))
estimator.add(layers.Dropout(0.01))
estimator.add(layers.Dense(units=10, activation='softmax'))

# 神经网络训练
estimator.compile(optimizer=RMSprop(learning_rate=0.001),loss='categorical_crossentropy', metrics=['accuracy'])
estimator.fit(train_images, train_labels, epochs=20, batch_size=128, verbose=2)

# 保存模型
estimator.save('./model.h5')

# 加载模型
estimator = tf.keras.models.load_model('./model.h5')

# 模型评估
test_loss, test_accuracy = estimator.evaluate(test_images, test_labels)
print("test_loss:", test_loss, "test_accuracy", test_accuracy)

# 图片测试
# # 一次测试一个文件
# img_path = "./num/"
# imagepaths = os.listdir(img_path)  # 图像文件夹
# # 从图片集中一次读取图片
# for imagepath in imagepaths:
#     im = cv2.imread(os.path.join(img_path, imagepath), 1)
#     plt.imshow(im)
#     plt.show()
#     im = cv2.resize(im, (28, 28), interpolation=cv2.INTER_CUBIC)
#     im2 = cv2.cvtColor(im, cv2.cv2.COLOR_BGR2GRAY)
#     im2 = im2.reshape((1, 28 * 28)).astype('float')
#     y_pre = estimator.predict(im2)
#     # print(y_pre)
#     y = np.argmax(np.array(y_pre))
#     print(y)

# 摄像头测试
# # 打开摄像头
# cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
# # 打开cap
# cap.open(0)
# # 循环
# while cap.isOpened():
#     # 获取画面
#     flag, frame = cap.read()
#     if not flag:
#         print("Not Flag")
#         break
#     # 获取键盘上按下哪个键
#     key_pressed = cv2.waitKey(100)
#     # print('键盘上被按下的键是:', key_pressed)
#     #
#     fra = cv2.resize(frame, (28,28))
#     im = cv2.cvtColor(fra, cv2.cv2.COLOR_BGR2GRAY)
#     im = im.reshape((1, 28 * 28)).astype('float')
#     y_pre = estimator.predict(im)
#     y = np.argmax(np.array(y_pre))
#     print(y)
#     print(y)
#     cv2.imshow("camera", frame)
#     # 如果按下esc键,就退出循环
#     if key_pressed == 27:
#         break
#
# # 关闭摄像头
# cap.release()
# # 关闭图像窗口
# cv2.destroyAllWindows()

  • 写回答

1条回答 默认 最新

  • youcans_ 人工智能领域优质创作者 2022-12-25 17:54
    关注

    如果训练的图片分辨率是 28×28,那么把学习图片 resize 到28×28,不会因为分辨率太小而影响判断。

    影响判断的原因,是最好不要直接将全部像素作为输入向量,而是提取特征向量,例如 HOG 向量,这样的训练-预测精度比较高

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 3月29日
  • 已采纳回答 3月21日
  • 创建了问题 12月25日

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装