首页 > 解决方案 > 流光画布图像尺寸转换

问题描述

我正在 python 上构建一个数字识别器神经网络模型。当我通过流光画布将测试图像输入模型时,我必须将 3D 图像转换为 2D,然后再转换为 (1,28,28)。但在那之后,我的模型即使有 97% 的准确率也无法预测图像。有人可以帮助我。这是我的代码:-

%%writefile app.py
import pandas as pd
from PIL import Image
import streamlit as st
from streamlit_drawable_canvas import st_canvas
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow import keras
# Specify canvas parameters in application
stroke_width = st.sidebar.slider("Stroke width: ", 1, 25, 3)
stroke_color = '#ffffff'
bg_color = '#000000'
drawing_mode = st.sidebar.selectbox(
    "Drawing tool:", ("freedraw", "line", "rect", "circle", "transform")
)
realtime_update = st.sidebar.checkbox("Update in realtime", True)
model_new=keras.models.load_model('digitrecognizer_mnist.hdf5')

# Create a canvas component
canvas_result = st_canvas(
    fill_color="#000000",  # Fixed fill color with some opacity
    stroke_width=stroke_width,
    stroke_color=stroke_color,
    background_color=bg_color,
    update_streamlit=realtime_update,
    height=150,width=150,
    drawing_mode=drawing_mode,
    key="canvas",
)
import cv2 
import matplotlib.pyplot as plt
from google.colab.patches import cv2_imshow
a=np.ones([150,150],dtype='uint8')*255
st.write(canvas_result.image_data.shape)
img=np.asarray(canvas_result.image_data).astype(np.uint8)
img.resize((28,28))
st.write(img.shape)
img=img.reshape(1,28,28)
k=model_new.predict_classes(img)[0]
if st.button('PREDICT'):
  st.write('Predicted value is') 
  st.write(k)

标签: pythonneural-networkstreamlit

解决方案


您可以使用PIL.Image来重塑图像。就我而言,我将其image_date转换为图像,调整大小,然后将其转换为一维数组,其中包含像素的颜色(因为它是灰度的,所以 R、G 和 B 的值是相同的) :

    from PIL import Image
    import numpy as np
    pic = Image.fromarray(image_data, 'RGBA').convert('L')
    pic.thumbnail((28, 28), Image.ANTIALIAS)
    arr = np.asarray(pic)
    arr = arr.flatten()

thumbnail方法使用比例来调整图像大小,记住这一点

如果你这样做arr.shape,你会得到 784 (28 x 28)

    arr.shape
    >> (784)

推荐阅读