【问题标题】:Can't read Base64 encoded image in Node.js which is sent from Python无法读取从 Python 发送的 Node.js 中的 Base64 编码图像
【发布时间】:2019-09-17 19:15:36
【问题描述】:

我正在尝试实现 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 node.js opencv base64 buffer


    【解决方案1】:
    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() 将其转换为字节是很实用的。此外,作为字节的图像需要编码和解码为“ascii”才能在 NodeJS 部分读取。

    【讨论】:

      【解决方案2】:

      您很可能使用python 2 运行您的脚本,但您使用的库使用的是python3,您的字符串将类似于b'aGVsbG8=' 而不是aGVsbG8=

      尝试从你的 shell 运行

      python3 engine.py
      

      【讨论】:

      • 不,该项目位于 Python 3.7.4 上的 virtualenv 中。我可以像您的示例一样传递base64 字符串,它以b'JDJMRkVTUU9R 开头,但是我仍然无法在Node.js 上使用它。尝试将其写入文件但仍然没有图像。
      • 因为当你想在节点中使用它时,你必须在最后删除b''。你已经这样做了吗?
      • 是的,字符串开头有'b'',结尾有''',我试图删除它们并从中创建一个缓冲区来写入图像,但我仍然无法打开图片文件。
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-27
        • 1970-01-01
        • 2017-03-20
        • 2011-10-02
        • 1970-01-01
        • 1970-01-01
        • 2018-09-01
        相关资源
        最近更新 更多