我将base64字符串作为图像发送到node express服务器,以使用tensorflow进行物体检测。如何在Node.js中将base64图像更改为cocossd模型的张量以进行物体检测。
服务器端的NodeJs
可以将Base64字符串转换为二进制,然后使用tf.node
读取为张量。
const b = Buffer.from(base64str, 'base64')
// get the tensor
const t = tf.node.decodeImage(b)
const b = atob(base64str)
let byteNumbers = new Array(b.length);
for (let i = 0; i < b.length; i++) {
byteNumbers[i] = b.charCodeAt(i);
}
let tensor = tf.tensor(byteNumbers)
第一种选项是同步的。对于大图像,它可能会冻结主线程。为了缓解这个问题,可以在 Web Worker 中执行此操作。
另一个选项是创建一个图像元素,并将其 href 属性设置为 base64str
,然后使用 tf.browser.fromPixels
。
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)
let tensor = await tf.browser.fromPixels(image)
})()
const readImage = path => {
//reads the entire contents of a file.
//readFileSync() is synchronous and blocks execution until finished.
const imageBuffer = fs.readFileSync(path);
//Given the encoded bytes of an image,
//it returns a 3D or 4D tensor of the decoded image. Supports BMP, GIF, JPEG and PNG formats.
const tfimage = tfnode.node.decodeImage(imageBuffer);
return tfimage;
}
[高度,宽度,通道]
。您需要知道图像的宽度和高度。您可以添加一个批处理维度(最左侧位置),这将使形状变为[b,高度,宽度,通道]
。当您使用tf.fromPixels时,它会直接返回3d或4d张量,与之不同。 - edkevekedlet buff = Buffer.from(data.photo.base64,'base64') let tensor = tf.tensor(buff,[data.photo.height,data.photo.width,3])
但是我在获取张量时遇到了错误,错误信息为根据提供的形状[1280,722,3],张量应该有2772480个值,但只有610963个。 - Jayaprakash