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

标签 python opencv

我无法将使用 cv2 打开的 jpeg 以字节形式发送到服务器。服务器提示不支持该文件类型。我可以使用 Python 的“open”功能毫无问题地发送它,但不能使用 OpenCV。我怎样才能让它发挥作用?

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.

最佳答案

我想首先让您的测试用例正常工作,我们将使用无压缩的无损格式来完成此操作,因此我们将进行逐一比较:

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. 

这并不理想,因为压缩对于移动字节来说是理想的,但它表明您的编码没有本质上的错误。

如果不知道服务器的详细信息,就很难知道为什么它不接受 opencv 编码的图像。一些建议是:

  • 提供 docs 中描述的格式特定编码参数,可用标志为 here
  • 尝试不同的扩展

关于python - 如何使用 Python 将 OpenCV 图像编码为字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59259786/

相关文章:

java - 为什么我的BGR2GRAY Mat在基本阈值函数中返回蓝色? [OPENCV]

opencv - 在OpenCV中在640x480和640x360分辨率之间切换

opencv - 对 CvStatModel train() 使用行或列特征?

c++ - 检查相机标定效率,用opencv

python - 将附近的散点合并为一个并增加其大小

python - 无法使用池更改共享内存对象

python - tensorflow.python.framework.errors_impl.NotFoundError : Op type not registered 'FertileStatsResourceHandleOp' in binary running on NS80011718

python - "The truth value of an array with more than one element is ambiguous"- 在 Pandas 数据框中搜索 NaN

python - 如何通过 C API 在 Python 类中创建静态变量?

c++ - OpenCV从矩阵获取条件库最大元素位置