Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么同一图像的Base64编码输出不同?_Python_Opencv_Base64_Tobase64string - Fatal编程技术网

Python 为什么同一图像的Base64编码输出不同?

Python 为什么同一图像的Base64编码输出不同?,python,opencv,base64,tobase64string,Python,Opencv,Base64,Tobase64string,下面的函数读取图像并将其转换为base64图像字符串 def getBase64Image(filePath): with open(filePath, "rb") as img_file: my_string = base64.b64encode(img_file.read()) my_string = my_string.decode('utf-8') return my_string def convertToBase64(image):

下面的函数读取图像并将其转换为base64图像字符串

def getBase64Image(filePath):
    with open(filePath, "rb") as img_file:
        my_string = base64.b64encode(img_file.read())
        my_string = my_string.decode('utf-8')
    return my_string
def convertToBase64(image):
    image.tobytes()
    my_string = base64.b64encode(image)
    my_string = my_string.decode('utf-8')
    return my_string
但是,下面的函数将图像作为OpenCV中的arrayloaded,并将其转换为base64图像字符串

def getBase64Image(filePath):
    with open(filePath, "rb") as img_file:
        my_string = base64.b64encode(img_file.read())
        my_string = my_string.decode('utf-8')
    return my_string
def convertToBase64(image):
    image.tobytes()
    my_string = base64.b64encode(image)
    my_string = my_string.decode('utf-8')
    return my_string
第一个函数的输出字符串与第二个函数生成的字符串不同。为什么呢

理想情况下,我希望第二个函数生成与第一个函数相同的base64字符串


请问,有人能指导我如何做到这一点吗?

您正在编码根本不同的结构。第一种方法是读取压缩图像格式(如jpeg或png)的字节。即使是位图图像,图像中也存储了大量未包含在原始数组数据中的额外数据


第二种方法是获取像素数据的hxwx3数组,将其转换为字节字符串,然后对其进行64位编码。通过比较黑白数据数组的字节字符串与保存的位图图像,可以看到差异

第一个函数按原样使用PNG/JPG图像数据并对其进行编码

第二个函数使用图像的RGB或灰度表示中的原始字节,并对其进行编码。如果要将原始RGB转换为图像,可以使用cv2.imencode,它将输出PNG或JPG或任何您喜欢的内容

def convertToBase64(image):
    #image.tobytes() -- don't need this
    _, converted = cv2.imencode( '.png', image)  # here the magic happens
    my_string = base64.b64encode(converted)  # and here
    my_string = my_string.decode('utf-8')
    return my_string

是的,以防万一还不清楚。您不必将编码图像保存在任何地方,它都发生在内存中。

这是否意味着,我唯一的选择就是保存图像并将其读回?我正在逐帧处理视频。保存帧并加载备份似乎只会增加延迟并减少输出。请将其保存到io.BytesIO对象,然后读回数据。