Home > Blockchain >  Find RGB pixels with same r,g and b value
Find RGB pixels with same r,g and b value

Time:08-04

I've a basic image:

enter image description here

Is there a way to quickly get the list of pixels (a mask) that have the same r, g and b pixel value?

In the example this corresponds to the gray square in the center of the image because each pixel in the gray square has the value (100, 100, 100)

The resulting mask should be something like this:

enter image description here

I have no clue how to do this (fast), I've isolated the r,g,b channels but I have no ideas

This is my code so far:

import numpy as np
from matplotlib import pyplot as plt

#Make the test image
img = np.full((512,512,3), dtype = np.uint8, fill_value = (255,0,255))
img[200:300, 200:300] = (100,100,100)

#get r,g,b
red = img[...,0]
green = img[...,1]
blue = img[...,2]

plt.imshow(img)
plt.show()

CodePudding user response:

Absolutely!

All you need to do is check that the data in column 0, 1, and 2 are equal. Since numpy arrays have an ambiguous truth value, you won't be able to chain the == operators like you can do with vanilla-python data types, so you're going to have to compare two colors at a time, and then elementwise-and them:

equal_mask = (red == green) & (green == blue)

Using np.logical_and instead, you could do:

rg = np.logical_and(red, green)
equal_mask = np.logical_and(rg, blue)

or, in one line:

equal_mask = np.logical_and(np.logical_and(red, green), blue)
  • Related