QImage:有没有任何懒惰的复制裁剪方法

时间:2011-06-04 21:34:53

标签: qt image-processing pyqt pyqt4 qimage

我试图使用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 Imaging Library的类似操作太快了。两个主要操作是copy()和operator ==()。我认为主要时间花在copy()上,因为它只在那里执行复制。如果它只是一个懒惰的写时复制操作,那么它会更快。

有没有办法更快地完成?

1 个答案:

答案 0 :(得分:0)

更快的方法是手动比较像素 - 你正在做的副本是浪费的。假设你想找到backgroundMask作为'image'的子图像。你从左上角开始。现在你发现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图像。 QImages和PIL图像之间的转换很简单,并且有很好的文档记录。