我试图使用QImage来加载图像,并检查与整个图像上移动的模板子图像的相等性。代码如下:
for i in range(image.height() - backgroundMask.height() + 1):
for j in range(image.width() - backgroundMask.width() + 1):
subsection = image.copy(j, i, j + backgroundMask.width() - 1, i + backgroundMask.height() - 1)
if subsection == backgroundMask:
print 'equality action here'
else:
print 'non-equality action here'问题是这样做花费了太多的时间。使用Python图像库进行类似的操作太快了。两个主要操作是copy()和operator==()。我认为大部分时间都花在copy()中,因为它只在那里执行复制。如果它只是一个懒惰的写时复制操作,那么它会更快。
有没有更快的方法呢?
发布于 2011-06-05 18:33:17
更快的方法是手动比较像素-你正在做的副本是浪费的。假设你想找到backgroundMask作为'image‘的子图。你从左上角开始。现在您发现图像的像素(0,0)与backgroundMask的(0,0)不匹配。如果你手工比较像素,你只需继续到图像的(0,1),并将其与(0,0)进行比较,依此类推。但是在你的例子中,你已经浪费了复制宽度x高度像素的时间。
start = time.time()
for i in xrange(image.height() - backgroundMask.height() + 1):
for j in xrange(image.width() - backgroundMask.width() + 1):
success = True
for y in xrange(backgroundMask.height()):
for x in xrange(backgroundMask.width()):
if image.pixel(j + x, i + y) != backgroundMask.pixel(x, y):
success = False
break
if not success:
break
if success:
print 'match'
else:
print 'no match'诚然,在Python中每像素的访问速度很慢,相等运算符是用C编写的,但它仍然比您发布的要快得多。对于我尝试的图像,你的代码花了27秒,我的花了0.8秒。
但是,最好的解决方案可能是将QImage转换为PIL Image (如果在那里实现了此功能)。QImages和PIL图像之间的转换很简单,并且有很好的文档记录。
https://stackoverflow.com/questions/6239538
复制相似问题