使用 python keras 加载的 jpg 与使用 javascript 加载的 jpg 不同

jpg loaded with python keras is different from jpg loaded in javascript

我正在服务器上 python 中加载 jpg 图像。然后我在客户端加载 javascript 相同的 jpg 图像。最后,我试图将它与 python 输出进行比较。但是加载的数据不同,因此图像不匹配。我哪里出错了?

Python代码

from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array    
filename = './rcl.jpg'
original = load_img(filename)
numpy_image = img_to_array(original)
print(numpy_image)

JS代码

import * as tf from '@tensorflow/tfjs';
photo() {
    var can = document.createElement('canvas');
    var ctx = can.getContext("2d");
    var img = new Image();
    img.onload = function() {
        ctx.drawImage(img, 0, 0);
    };
    img.crossOrigin = "anonymous";
    img.src = './rcl.jpg';

    var tensor = tf.fromPixels(can).toFloat();
    tensor.print()

}

在将 canvas 渲染为张量之前,您正在 canvas 上绘制图像。在 canvas 上绘图可以改变初始图像的形状。例如,除非另有说明——您的代码就是这种情况——创建的 canvas 宽度为 300 像素,高度为 150 像素。因此,张量的最终形状将或多或少类似于以下 [150, 300, 3].

1- 使用 Canvas

Canvas 适合调整图像大小,因为可以在 canvas 上绘制全部或部分初始图像。在这种情况下,需要调整 canvas.

的大小
const canvas = document.create('canvas')
// canvas has initial width: 300px and height: 150px
canvas.width = image.width
canvas.height = image.heigth
// canvas is set to redraw the initial image
const ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0) // to draw the entire image

不过要注意一点:以上所有内容都应在图像完成加载后使用事件处理程序 onload 执行,如下所示

    const im = new Image()
    im.crossOrigin = 'anonymous'
    im.src = 'url'
    // document.body.appendChild(im) (optional if the image should be displayed)
    im.onload = () => {
      const canvas = document.create('canvas')
      canvas.width = image.width
      canvas.height = image.heigth
      const ctx = canvas.getContext('2d')
      ctx.drawImage(image, 0, 0)
    }

或使用async/await

function load(url){
  return new Promise((resolve, reject) => {
    const im = new Image()
        im.crossOrigin = 'anonymous'
        im.src = 'url'
        im.onload = () => {
          resolve(im)
        }
   })
}

// use the load function inside an async function   

(async() => {
     const image = await load(url)
     const canvas = document.create('canvas')
     canvas.width = image.width
     canvas.height = image.heigth
     const ctx = canvas.getContext('2d')
     ctx.drawImage(image, 0, 0) 
   })()

2-直接在图片上使用fromPixel

如果不调整图像大小,您可以直接在图像本身上使用fromPixel将图像渲染为张量