2014-01-15 55 views
2

我堆积了以当前颜色区间查找像素位置的问题。 这是非常缓慢:以当前颜色区间快速查找像素位置

def inRange(self, tgColor, excColor, jump): 
    if tgColor[0] > excColor[0] - jump and tgColor[0] < excColor[0] + jump and tgColor[1] > excColor[1] - jump and tgColor[1] < excColor[1] + jump and tgColor[2] > excColor[2] - jump and tgColor[2] < excColor[2] + jump: 
      return True 
    return False 

for iy in xrange(self.pilImage.size[1]): 
     for ix in xrange(self.pilImage.size[0]): 
      if self.inRange(data[ix, iy], self.targetColor, self.jump): 

所以,你可以帮我提高这个代码,使其运行得更快。 (图像大小 - 640 x 480) 也许另一个lib:OpenCV,pygame,PIL?

+1

这个问题似乎是题外话,因为它属于上http://codereview.stackexchange.com – jonrsharpe

回答

2

你的代码可以是超慢

OpenCV的自带功能cv2.inRange()。你传递最小和最大像素值,你会得到一个二值图像,其像素为白色,失败像素为黑色。

然后,您可以使用numpy.where()来查找白色像素的索引。

下面是一个灰度值的例子。它也可以扩展到彩色图像。 [Link]

例子:

>>> import cv2 
>>> import numpy as np 
>>> x = np.random.randint(1,10, (5,5)) 
>>> x 
array([[9, 5, 1, 3, 1], 
     [7, 7, 2, 1, 7], 
     [9, 1, 4, 7, 4], 
     [3, 6, 6, 7, 2], 
     [3, 4, 2, 3, 1]]) 
>>> y = cv2.inRange(x,4,8) 
>>> y 
array([[ 0, 255, 0, 0, 0], 
     [255, 255, 0, 0, 255], 
     [ 0, 0, 255, 255, 255], 
     [ 0, 255, 255, 255, 0], 
     [ 0, 255, 0, 0, 0]], dtype=uint8) 

>>> z = np.transpose(np.where(y>0)) 
>>> z 
array([[0, 1], 
     [1, 0], 
     [1, 1], 
     [1, 4], 
     [2, 2], 
     [2, 3], 
     [2, 4], 
     [3, 1], 
     [3, 2], 
     [3, 3], 
     [4, 1]]) 
+0

是的,我的代码是很慢的,因为它必须这样做307200次的迭代在周期:(但你的建议是非常有用的,谢谢。 – Megaxela