Can';t读取从Python发送的Node.js中的Base64编码图像

Can';t读取从Python发送的Node.js中的Base64编码图像,python,node.js,opencv,base64,buffer,Python,Node.js,Opencv,Base64,Buffer,我正在尝试实现Node.js和Python之间的通信。对于这个任务,我使用Node.js的PythonShell NPM模块运行python脚本并读取打印输出。我想在Python上做一些OpenCV图像处理的工作,将图像发送到Node.js并在应用程序上提供 以下是Node.js部分: let {PythonShell} = require('python-shell') let options = { mode: 'text', pythonOptions: ['-u'], // g

我正在尝试实现Node.js和Python之间的通信。对于这个任务,我使用Node.js的PythonShell 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=

试着逃离你的壳

python3 engine.py
我就是这样想出来的。使用OpenCV的imencode方法对图像进行编码,并使用.tobytes()将其转换为字节,这是很常见的。此外,作为字节的图像需要编码并解码为“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'))
节点代码

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) {});
});

不,该项目位于Python3.7.4上的virtualenv中。我可以传递base64字符串,就像您的示例一样,它以
b'JDJMRkVTUU9R
开头,但是我仍然无法在Node.js上使用它。试图将其写入文件,但仍然没有图像。因为当您想在节点中使用它时,最后必须删除
b'
'
。你已经这样做了吗?是的,字符串开头有“b”,结尾有“b”,我试图删除它们并从中创建一个缓冲区来写入图像,但我仍然无法打开图像文件。
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) {});
});