简体   繁体   English

如何使用 Python 将 OpenCV 图像编码为字节

[英]How to encode OpenCV Image as bytes using Python

I am having difficulty sending a jpeg opened with cv2 to a server as bytes.我无法将使用 cv2 打开的 jpeg 作为字节发送到服务器。 The server complains that the file type is not supported.服务器抱怨文件类型不受支持。 I can send it without problems using Python's "open" function, but not with OpenCV.我可以使用 Python 的“打开”函数毫无问题地发送它,但不能使用 OpenCV。 How can I get this to work?我怎样才能让它发挥作用?

import cv2

path = r".\test\frame1.jpg"

with open(path, "rb") as image:
    image1 = image.read()
image2 = cv2.imread(path, -1)
image2 = cv2.imencode(".jpg", image2)[1].tobytes() #also tried tostring()

print(image1 == image2)
#This prints False. 
#I want it to be True or alternatively encoded in a way that the server accepts.

I want to start by getting your test case working, we will do this by using a lossless format with no compression so we are comparing apples to apples:我想首先让你的测试用例工作,我们将通过使用没有压缩的无损格式来做到这一点,所以我们将苹果与苹果进行比较:

import cv2

path_in = r".\test\frame1.jpg"
path_temp = r".\test\frame1.bmp"
img = cv2.imread(path_in, -1)
cv2.imwrite(path_temp, img) # save in lossless format for a fair comparison

with open(path_temp, "rb") as image:
    image1 = image.read()

image2 = cv2.imencode(".bmp", img)[1].tobytes() #also tried tostring()

print(image1 == image2)
#This prints True. 

This is not ideal since compression is desirable for moving around bytes, but it illustrates that there is nothing inherently wrong with your encoding.这并不理想,因为压缩对于移动字节是可取的,但它说明您的编码没有本质上的错误。

Without knowing the details of your server it is hard to know why it isn't accepting the opencv encoded images.如果不知道服务器的详细信息,就很难知道为什么它不接受 opencv 编码的图像。 Some suggestions are:一些建议是:

  • provide format specific encoding parameters as described in the docs , available flags are here提供文档中描述的格式特定的编码参数,可用标志在这里
  • try different extensions尝试不同的扩展

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM