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

问题描述 投票:0回答:2

我一直在尝试以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十六进制,然后接下来的24个字符img1并测试所有的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的巨大图像,输出很大,我无法从终端读取或者将输出保存到文件中。

如何仅打印匹配的(True)24个字符ASCII十六进制值而不打印true,false和false ASCII十六进制值?

FFD8 FFE0 0010 4A46 4946 0001
python printing equality
2个回答
0
投票

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

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的输出,唯一的输出将是匹配的字节。如果这不是你的意思,你能准确说明你想要实现的目标吗?


1
投票

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

编辑:

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

© www.soinside.com 2019 - 2024. All rights reserved.