python-3.x - 数字识别:我从画布图像中得到相同的输出
问题描述
我正在 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]
解决方案
推荐阅读
- android-studio-4.0 - 运行模拟器时出现此错误:原因:无效类型代码:1D
- json - 路径具有时髦字符时的 TSQL OPENJSON
- java - paintComponent() 没有正确绘制矩形
- php - 错误:类 App\Http\Resources\ProductAttributeResource 的对象无法转换为 int
- javascript - Jquery - $.When 不触发 ajax on done menthod
- php - ErrorException 非法偏移类型 - Laravel
- php - 无法使用 ajax 源填充数据表
- javascript - 如何在 HTML5 Canvas 中展开模糊滤镜半径?
- r - 在 R 的函数中使用 else if
- python - Python XMLRPC:即使在allow_none = True之后也不允许None