【问题标题】:Resizing image and changing into grayscale调整图像大小并更改为灰度
【发布时间】:2021-10-19 04:14:49
【问题描述】:

我在输入大小为 48、48、1 的 React Native 中使用我训练有素的模型。输入值是 rgb 图像。所以我尝试将图像转换为 tensor3d,然后转换为灰度并调整其大小。但是在调整模型大小后总是给出相同的预测值。我不明白我的代码哪里出了问题。我的模型精度还可以。

const imageDataArrayBuffer = await response.arrayBuffer();
const imageData = new Uint8Array(imageDataArrayBuffer);
let imageTensor = decodeJpeg(imageData).resizeBilinear([48,48]).reshape([48,48,3])
//let imag=imageTensor
imageTensor=tf.ones([48,48,3])
rgb_weights=[0.2989, 0.5870, 0.1140]
imageTensor = tf.mul(imageTensor, rgb_weights)
imageTensor = tf.sum(imageTensor, -1)
imageTensor = tf.expandDims(imageTensor, -1)
imageTensor=imageTensor.resizeBilinear([48,48]).reshape([-1,48,48,1])

let result = await model.predict(imageTensor).data()
alert("Result " +result)

【问题讨论】:

    标签: python react-native rgb tensorflow.js grayscale


    【解决方案1】:

    您可以将运算符链接在一起以将图像转换为灰度图像,然后您需要使用dataSync() 提取预测。

    const imageDataArrayBuffer = await response.arrayBuffer();
    const imageData = new Uint8Array(imageDataArrayBuffer);
    const imageTensor = decodeJpeg(imageData).resizeBilinear([48,48]).reshape([48,48,3])
    
    # grayscale = (1, width, height, 1)
    const grayscale = tf.browser.fromPixels(imageTensor)
        .mean(2)
        .toFloat()
        .expandDims(0)
        .expandDims(-1)
    
    # Extract the results out
    const result = await model.predict(imageTensor).dataSync()[0]
    

    【讨论】:

    • 除非您将链式操作包装在 tf.tidy() 中,否则最终会导致内存泄漏-链中的每个操作都会创建一个永远不会被释放的新张量-在您的情况下,您最终会得到 4内存中图像的版本
    【解决方案2】:

    我注意到的一件事是你最终得到了一个 float32 张量,因为你将 Uint8Array 与 rgb_weights 相乘,结果得到了一个 float32 张量。如果将 toInt() 添加到 tf.mul 中,则将 int32 结构保留在张量中。

    查看我制作的这个示例,您的代码在创建灰度图像时可以正常工作LINK TO CODE

    如果你删除了我的示例代码第 8 行的toInt(),图像不再在正确的范围内。

    这也引出了一个问题,您的模型希望imageTensor 采用什么格式?您是否需要将张量归一化为 0 到 1 之间的值,以便您的模型预测准确?确保您尊重每个张量和模型的类型。

    之前:

    之后:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      相关资源
      最近更新 更多