无法读取从 Python 发送的 Node.js 中的 Base64 编码图像

Oğu*_*lik 4 python base64 buffer opencv node.js

我正在尝试实现 Node.js 和 Python 之间的通信。对于此任务,我使用 Node.js 的 python-shell NPM 模块来运行 Python 脚本并读取打印输出。我想在 Python 上做一些 OpenCV 图像处理的东西,将图像发送到 Node.js 并在应用程序上提供它。

这是 Node.js 部分:

let {PythonShell} = require('python-shell')

let options = {
  mode: 'text',
  pythonOptions: ['-u'], // get print results in real-time
  args: ['value1', 'value2', 'value3']
};

PythonShell.run('engine.py', options, function (err, results) {
  if (err) throw err;
  // results is an array consisting of messages collected during execution
/*   var fs = require("fs");

  fs.writeFile("arghhhh.jpeg", Buffer.from(results, "base64"), function(err) {}); */
  console.log(results.toString())
});
Run Code Online (Sandbox Code Playgroud)

这是Python部分:

from PIL import Image
import cv2 as cv2
import base64

source = cv2.imread("60_3.tif", cv2.IMREAD_GRAYSCALE)
# tried making it a PIL image but didn't change anything
# source = Image.fromarray(source)
print(base64.b64encode(source))
Run Code Online (Sandbox Code Playgroud)

理论上一切看起来都不错,但是,我尝试在 Node.js 端编写图像,但无法打开图像。还检查了两个字符串的大小,Node.js 端有 3 个字符差异。我是否需要在两者之间做其他事情来在两种语言之间共享一个简单的图像?

Oğu*_*lik 5

import cv2 as cv2
import base64

source = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
success, encoded_image = cv2.imencode('.png', source)
content = encoded_image.tobytes()
print(base64.b64encode(content).decode('ascii'))
Run Code Online (Sandbox Code Playgroud)

我就是这样想出来的。使用 OpenCV 的 imencode 方法编码图像并使用 .tobytes() 将其转换为字节是古怪的。此外,作为字节的图像需要编码和解码为“ascii”才能在 NodeJS 部分读取。