Python OpenCV映像到字节字符串,用于JSON传输



i使用 python3 numpy,scipy和opencv

我正在尝试通过OPENCV和连接的摄像机接口读取图像,以通过某些网络连接将其发送到JSON对象中。

我尝试将数组作为JPG和解码UTF-16字符串包含,但是我没有可用的结果。例如,使用

img = get_image()
converted = cv2.imencode('.jpg', img)[1].tostring()
print(converted)

我得到一个字节弦:

b' xff xd8 xff xf Xe0 x00 x10jfif x00 x00 x01 x01 x01 x00 x00 x00 x01 x00 x00 x01 x01 x00 x00 x00 x00x01 x01 x01 x01 x02 x01 ....

但是,这些数据不能用作JSON对象的内容,因为它包含无效的字符。有什么方法可以显示此字符串背后的真实字节?我相信 xff代表字节值ff,因此我需要像ffd8ffe0等字符串一样,等等,而不是 xff xd8 xff xe0。我在做什么错?

我尝试将其编码为上述代码之后的UTF-8和UTF16,但是我在此上遇到了几个错误:

utf_string = converted.decode('utf-16-le')

unicodedecodeerror:'utf-16-le'编解码器无法在位置0-1中解码字节:非法UTF-16代理

text = strrrrrr.decode('utf-8')

unicodedecodeerror:'utf-8'编解码器无法在位置0 x byte 0xff解码:无效启动字节

我无法找到正确的方法。

我还尝试将其转换为基本64编码的字符串,如在http://www.programcreek.com/2013/09/convert-image-to-string-in-in-python/但这也行不通。(此解决方案不是首选,因为它需要暂时写入磁盘的图像,这并不是我所需要的。优先映像只能保存在内存中,切勿在磁盘上保存。)

该解决方案应包含一种将图像编码为JSON-CONFORM字符串的方法,也应将其解码回到Numpy-array,因此可以与Cv2.imshow()。

再次使用。

感谢您的任何帮助。

您不需要将缓冲区保存到文件。以下脚本从网络摄像头捕获图像,将其编码为JPG映像,然后将数据转换为可打印的base64编码,该编码可与您的JSON一起使用:

import cv2
import base64
cap = cv2.VideoCapture(0)
retval, image = cap.read()
retval, buffer = cv2.imencode('.jpg', image)
jpg_as_text = base64.b64encode(buffer)
print(jpg_as_text)
cap.release()

给您一些开始的东西:

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCg

这可以扩展以显示如何将其转换回二进制,然后将数据写入测试文件以表明转换成功:

import cv2
import base64
cap = cv2.VideoCapture(0)
retval, image = cap.read()
cap.release()
# Convert captured image to JPG
retval, buffer = cv2.imencode('.jpg', image)
# Convert to base64 encoding and show start of data
jpg_as_text = base64.b64encode(buffer)
print(jpg_as_text[:80])
# Convert back to binary
jpg_original = base64.b64decode(jpg_as_text)
# Write to a file to show conversion worked
with open('test.jpg', 'wb') as f_output:
    f_output.write(jpg_original)

将图像作为图像缓冲区(而不是JPG格式)重新恢复原状:

jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
image_buffer = cv2.imdecode(jpg_as_np, flags=1)

上面答案对我不起作用,需要一些更新。这是对此的新答案:

编码JSON:

import base64
import json
import cv2
img = cv2.imread('./0.jpg')
string = base64.b64encode(cv2.imencode('.jpg', img)[1]).decode()
dict = {
    'img': string
}
with open('./0.json', 'w') as outfile:
    json.dump(dict, outfile, ensure_ascii=False, indent=4)

解码回到np.array

import base64
import json
import cv2
import numpy as np
response = json.loads(open('./0.json', 'r').read())
string = response['img']
jpg_original = base64.b64decode(string)
jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
img = cv2.imdecode(jpg_as_np, flags=1)
cv2.imwrite('./0.jpg', img)

希望这可以帮助某人:p

最新更新