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

Can't read Base64 encoded image in Node.js which is sent from Python

我正在尝试实现 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())
});

这是 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))

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

您的脚本很可能 运行 使用 python 2,但您使用的库使用的是 python3,您的字符串看起来像 b'aGVsbG8=' 而不是 aGVsbG8=.

试试 运行 从你的 shell

python3 engine.py
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'))

这就是我想出来的。使用 OpenCV 的 imencode 方法对图像进行编码并使用 .tobytes() 将其转换为字节是 curial。此外,作为字节的图像需要编码和解码为 'ascii' 以便在 NodeJS 部分读取。

python代码#cv.py

import cv2 as cv2
import base64

source = cv2.imread('0.png', cv2.IMREAD_GRAYSCALE)
success, encoded_image = cv2.imencode('.png', source)
content = encoded_image.tobytes()
print(base64.b64encode(content).decode('ascii'))

nodejs代码

const spawn = require('child_process').spawn;
const fs = require('fs');

const process = spawn('python', ['./cv.py']);

process.stdout.on('data', data => {
  console.log(data.toString()); 
  fs.writeFile("test.png", Buffer.from(data.toString(), "base64"), function(err) {});
});