David Kachlon
David Kachlon

Reputation: 619

Python, RGB color comparisons

I have a pixel from an OpenCV image with the RGB format in [r,g,b]. I would like to run a test so that if i find a color darker than [150,150,150] i stop a for loop.

This is what I have so far:

def test():
    for l in range(y, y+h):
        for d in range(x, x+w):
            print(image[l,d][0])
            if image[l,d] <= [150,150,150]:
                return;
            image[l,d] = [0,0,0]

Doesn't work though. Any ideas?

Upvotes: 3

Views: 3715

Answers (1)

Dan Mašek
Dan Mašek

Reputation: 19041

Since OpenCV images in Python are represented as numpy arrays, each pixel value will also be a numpy array. That means that the comparison operation will be vectorized, and return an array of boolean values, for example

>>> image[l,d] <= [150,150,150]
array([ True,  True,  True], dtype=bool)

Now, you want to check that the condition is satisfied for all the item pairs. That's where numpy.all comes into play.

>>> np.all(image[l,d] <= [150,150,150])
True

In fact, numpy arrays have a member method all(), which does the same thing.

>>> (image[l,d] <= [150,150,150]).all()
True

Upvotes: 4

Related Questions