无法读取Python发送的Node.js中的Base64编码图像 [英] Can't read Base64 encoded image in Node.js which is sent from Python

查看:104
本文介绍了无法读取Python发送的Node.js中的Base64编码图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to achieve communication between Node.js and Python. For this task, I'm using Node.js's python-shell NPM module to run a Python script and read the print output. I want to do some OpenCV image processing stuff on Python, send the image to Node.js and serve it on an application.

这是Node.js的一部分:

Here is the Node.js part:

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部分:

Here is the Python part:

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个字符差异. 我是否需要在两者之间做一些其他事情以在两种语言之间共享一个简单的图像?

Everything looks good in theory, however, I tried to write the image on Node.js side and I can't open the image. Also checked sizes of the both strings and there was 3 character difference on Node.js side. Do I need to do something else in between to share a simple image between two languages?

推荐答案

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部件上读取.

This is how I figured it out. Encoding image with OpenCV's imencode method and converting it to bytes with .tobytes() is curial. Also, the image as bytes needs to be encoded and decoded as 'ascii' to be read on the NodeJS part.

这篇关于无法读取Python发送的Node.js中的Base64编码图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆