我已经在这里提出问题的帮助下为RobotFramework写了我自己的图像比较功能。
from PIL import Image, ImageChops, ImageDraw, ImageFont
def check_image_files(self, file1, file2, file3) :
''' Check two image files
``file1``: absolute path to the first file
``file2``: absolute path to the second file
``file3``: absolute path to the compare file
'''
self.builtin.log("File1: %s" %file1)
self.builtin.log("File2: %s" %file2)
point_table = ([0] + ([255] * 255))
f1 = Image.open(file1)
f2 = Image.open(file2)
diff = ImageChops.difference(f1, f2)
diff = diff.convert('L')
diff = diff.point(point_table)
f3 = diff.convert('RGB')
f3.paste(f2, mask=diff)
f3.save(file3)
如果在文件中找不到任何差异,最终结果现在是一个完整的黑屏,但我想得到一个真/假。因此,如果2个文件不相同,我可以让测试用例通过/失败。现在,如果文件对于一小部分不相同而且不是我想要的那样,那么测试用例就会成功。
我已经阅读了PIL文档,但无法得到我需要的东西(顺便说一句,我是一名对编程感兴趣的测试人员)
答案 0 :(得分:0)
以下示例来自basic image comparison上的RossetaCode.org,他们在那里计算差异。这当然是确定图像是否相同的前兆。如果是,则返回0,0。
from itertools import izip
from PIL import Image
i1 = Image.open("image1.png")
i2 = Image.open("image2.png")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = izip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
# for gray-scale jpegs
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print "Difference (percentage):", (dif / 255.0 * 100) / ncomponents