比较图像是否相等,但输出很大



我一直在尝试读取 ASCII 值中的图像,并比较两个图像以获得精确的 ASCII 值匹配。但是,输出非常大,我的硬件很旧,无法读取输出,我尝试将输出保存到文件中,文件很大。这是我正在尝试做的:

orig = sys.stdout
f = open('output.txt','w')
sys.stdout = f
# Load the two Images 
with open("image1.jpg", "rb") as b:
with open("image2.jpg", "rb") as a:
# Convert the two images from binary to ascii
chunk1 = binascii.b2a_hex(b.read())
chunk2 = binascii.b2a_hex(a.read())
# split the two chunks of ascii values into a list of 24 bytes 
chunkSize = 24
for i in range (0,len(chunk1),chunkSize):
for j in range (0,len(chunk2),chunkSize):
# Print them
list1 = chunk1[i:i+chunkSize]
print "List1: "+ list1
list2 = chunk2[j:j+chunkSize]
print "List2: " + list2
# Compare the two images for equality 
list = list1 == list2
# print whether its a match or false
print list
sys.stdout = orig
f.close()
# Saved to a file

工作原理:

img1 具有以下十六进制: FFD8 FFE0 0010 4A46 4946 0001 0200 0064 0064 0000 FFEC 0011 img2 具有以下十六进制: FFD8 FFE0 0010 4A46 4946 0001 0210 0064 0064 0000 FFEC 0012

它将获取 img1 的前 24 个字符,并针对 24 个字符中的所有 img2 十六进制对其进行测试,然后获取 img1 的下一个 24 个字符并针对所有 img2 十六进制进行测试。例:

List1: FFD8 FFE0 0010 4A46 4946 0001 
List2: FFD8 FFE0 0010 4A46 4946 0001 
True 
List1: FFD8 FFE0 0010 4A46 4946 0001 
List2: 0210 0064 0064 0000 FFEC 0012 
False
List1: 0200 0064 0064 0000 FFEC 0011 
List2: FFD8 FFE0 0010 4A46 4946 0001 
False 
List1: 0200 0064 0064 0000 FFEC 0011 
List2: 0210 0064 0064 0000 FFEC 0012 
False

但是,考虑到具有 40k 十六进制和 20k 等大图像,输出很大,我也无法从终端读取,也无法将输出保存到文件中。

如何仅打印匹配的(真(24 个字符 ASCII 十六进制值而不打印真、假和假 ASCII 十六进制值?

FFD8 FFE0 0010 4A46 4946 0001

您可以一次从每个图像中读取 24 个字节,而不是一次读取整个文件。file.read()接受一个参数,该参数允许它一次只读取几个字节。您可以在循环中运行它,直到read()返回一个空字符串,这意味着已到达文件末尾。请参阅文档。

编辑

如果您想要只是简单地检查两个文件是否相同,为什么不查看校验和呢?相同的文件将始终具有相同的校验和。有关更多详细信息,请参阅此答案。

如果我理解这个问题,怎么样:

orig = sys.stdout
f = open('output.txt','w')
sys.stdout = f
# Load the two Images 
with open("image1.jpg", "rb") as b:
with open("image2.jpg", "rb") as a:
# Convert the two images from binary to ascii
chunk1 = binascii.b2a_hex(b.read())
chunk2 = binascii.b2a_hex(a.read())
# split the two chunks of ascii values into a list of 24 bytes 
chunkSize = 24
for i in range (0,len(chunk1),chunkSize):
for j in range (0,len(chunk2),chunkSize):
list1 = chunk1[i:i+chunkSize]
list2 = chunk2[j:j+chunkSize]
# Compare the two images for equality 
list = list1 == list2
# print bytes once only if they were the same in both list1 and list2
if list:
print list1
sys.stdout = orig
f.close()

这将省略原始示例中的任何 False 输出,唯一的输出将是匹配的字节。如果这不是你的意思,你能澄清一下你想要实现的目标吗?

最新更新