gpt4 book ai didi

python - Base64 图像比较

转载 作者:行者123 更新时间:2023-12-01 06:37:54 27 4
gpt4 key购买 nike

假设我有两个图像 A 和 B,大小相同、 channel 数相同且格式相同(例如,PNG 中大小均为 25x25 的 RGB 图像)。

我想比较这两个图像,并根据每个像素的差异总和对这两个图像的差异程度进行评分。然而,这些图像被编码为 Base64格式(如 HTML 页面中的图像)。

我的问题是,总结 Base64 格式中每个字符的差异是否一定能估算出 A 和 B 的不同或相似之处?

最佳答案

我用 Python 编写了一个测试来生成三个随机图像 img1、img2、img3。然后首先逐像素比较它们,然后比较它们的 Base64 版本。我尝试查看 img1 是否与 img2img3 更相似,然后测试两个比较是否相关。

答案是。它们不相关。在我的测试中,1000 次测试中有 488 次它们不相关。

import numpy as np
import base64

# Generates an image with random values
def generate_image():
img = np.random.random((10,10,3)) * 255
return np.uint8(img)

# First comparison method based on pixel to pixel comparison
def compare_numpy(img1, img2):
return np.sum( np.abs( img1 - img2 ) )

# Second comparison method based on comparing Base64 versions
def compare_base64(img1, img2):
b1 = list(base64.b64encode(img1))
b2 = list(base64.b64encode(img2))
return sum( abs(b1[i] - b2[i]) for i in range(len(b1)))

# Test if both methods says if img1 is closer to img2 or img3
def correlation_test():
img1 = generate_image()
img2 = generate_image()
img3 = generate_image()

# img1 is closer to img2 or img3

# Testing pixel to pixel comparison
cmp12 = compare_numpy(img1, img2)
cmp13 = compare_numpy(img1, img3)
if cmp12 < cmp13:
result1 = 2
else:
result1 = 3

# Testing Base64 comparison
cmp12 = compare_base64(img1, img2)
cmp13 = compare_base64(img1, img3)
if cmp12 < cmp13:
result2 = 2
else:
result2 = 3

return result1 == result2

true_cnt = 0
false_cnt = 0

# Running the test 1000 times
for i in range(1000):
if correlation_test():
true_cnt += 1
else:
false_cnt += 1

print(f"They are correlated {true_cnt} times")
print(f"They are not correlated {false_cnt} times")

# They are correlated 512 times
# They are not correlated 488 times

关于python - Base64 图像比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59584735/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com