2011-06-04 71 views
2

我试图使用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()中花费的,因为它只在那里执行拷贝。如果它只是一个懒惰的写入时复制操作,那么它会更快。

有没有办法更快地做到这一点?

回答

0

更快的方法是手工比较像素 - 你做的副本是浪费的。假设你想找到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图像。 QImages和PIL图像之间的转换很简单并且有详细记录。

+0

这是唠叨我的问题。 Python循环很慢并且没有优化。 – Xolve 2011-06-05 12:15:41

+0

但是这个算法比你使用的算法好得多,尽管你的一部分被推入了C++。否则使用我建议的PIL方法。 – PAG 2011-06-05 12:29:43