调整图像大小并更改为灰度

2024-04-19 18:30:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在react native中使用我的训练模型,其输入大小为48,48,1。输入值是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)

Tags: 模型图像tfrgbresultawaitreactlet
2条回答

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

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

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

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

之前:RGB image input

之后:Grayscale 48x48

您可以将操作符链接在一起以将图像转换为灰度,然后需要使用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]

相关问题 更多 >