首页 > 解决方案 > 数字识别:我从画布图像中得到相同的输出

问题描述

我正在 Flask 中为 ML 中的 hello world 创建一个简单的 Web 应用程序,即数字识别。

在训练模型并使用来自 mnist 的看不见的图像测试模型之后,它正确地预测了它们,但是在使用 html canvas 绘制数字时,对于绘制的任何数字,我一直得到相同的输出。

在此处输入图像描述

<canvas id="myCanvas" width="280" height="280" style="border:8px solid; float: left; margin: 70px; margin-top:160px;  border-radius: 5px; cursor: crosshair;"></canvas>



<script type="text/javascript">
     var mousePressed = false;
     var lastX, lastY;
     var ctx;

     function InitThis() {
         ctx = document.getElementById('myCanvas').getContext("2d");

         $('#myCanvas').mousedown(function (e) {
             mousePressed = true;
             Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
         });

         $('#myCanvas').mousemove(function (e) {
             if (mousePressed) {
                 Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
             }
         });

         $('#myCanvas').mouseup(function (e) {
             mousePressed = false;
         });

         $('#myCanvas').mouseleave(function (e) {
             mousePressed = false;
         });
     }

     function Draw(x, y, isDown) {
         if (isDown) {
             ctx.beginPath();
             ctx.strokeStyle = 'black';
             ctx.lineWidth = 5;
             ctx.lineJoin = "round";
             ctx.moveTo(lastX, lastY);
             ctx.lineTo(x, y);
             ctx.closePath();
             ctx.stroke();
         }
         lastX = x;
         lastY = y;
     }

     function clearArea() {
         // Use the identity matrix while clearing the canvas
         ctx.setTransform(1, 0, 0, 1, 0, 0);
         ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
     }

     </script>

这是python代码

def convertImage(imgData1):
    imgstr = re.search(b'base64,(.*)',imgData1).group(1)
    with open('output.png','wb') as output:
        output.write(base64.b64decode(imgstr))


def predict():
    imgData = request.get_data()

    convertImage(imgData)
    imgArr = cv2.imread("output.png", 0)
    imgArr = cv2.resize(imgArr, dsize=(28, 28), interpolation=cv2.INTER_CUBIC)
    #print(imgArr)
    imgArr = np.expand_dims(imgArr, axis=0)
    new_model = tf.keras.models.load_model('my-model.model')
    prediction = new_model.predict(imgArr)
    return np.array_str(prediction[0])

这是我不断获得的所有图像的输出

Predicted Output: [0.01503093 0.09207787 0.08750388 0.0216067  0.02371381 0.5564784 0.01984628 0.16058393 0.00308483 0.02007343]

expecting an output like [0 0 0 1 0 0 0 0 0 0]

使用 plt.imshow(imgArr) 显示 output.png 返回空白图像 在此处输入图像描述

标签: python-3.xtensorflowmachine-learningimage-processingcomputer-vision

解决方案


推荐阅读