我无法将使用 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 编码的图像。一些建议是:
关于python - 如何使用 Python 将 OpenCV 图像编码为字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59259786/