Megaxela
Megaxela

Reputation: 97

Fast finding pixel position with current color interval

I stacked with problem of finding pixel position with current color interval. This is very slow:

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):

So, can you help me to improve this code, to make it work faster. (Image size - 640 x 480) Maybe another lib: OpenCV, pygame, PIL?

Upvotes: 3

Views: 1321

Answers (1)

Abid Rahman K
Abid Rahman K

Reputation: 52646

Your code can be super-slow

OpenCV comes with a function cv2.inRange(). You pass the minimum and maximum pixel values and you get a binary image with passed pixels as white and failed pixels as black.

Then you can use numpy.where() to find the indices of pixels who are white.

Below is an example with grayscale values. It can be extended to color images also. [Link]

Example:

>>> 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]])

Upvotes: 2

Related Questions