Home > Software engineering >  Python If Value of pixel in an image is then print
Python If Value of pixel in an image is then print

Time:09-03

I have a small image that I would like to find all RGB values that are the same and then compare that against my variable and if the match print match or similar.

Below is a little snippet that I have put together from other sources.

I am able to print that I found the colour but it will print a line for every time that value is found in the image.

Is there a better way to search an image and match that to a single RGB value? Then if found do a thing.

import cv2

path = '3.png'

blue = int(224)
green = int(96)
red = int(32)
img = cv2.imread(path)
x,y,z = img.shape

for i in range(x):
  for j in range(y):
    if img[i,j,0]==blue & img[i,j,1]==green & img[i,j,1]==red:
      print("Found colour at ",i,j)

CodePudding user response:

I think this may help you with small touching :)

import cv2
import numpy as np

r = int(255)
g = int(255)
b = int(255)

img = 255*np.ones((5,5,3), np.uint8)

[rows, cols] = img.shape[:2]
print(img.shape[:2])
print(img.shape)

for i in range(rows):
    for j in range(cols):
        if img[i, j][0] == r and img[i, j][1] == g and img[i, j][2] == b:
            print(img[i, j])
            print(i, j)

CodePudding user response:

General Python advice: do not say blue = int(224). Just say blue = 224

Your program expects to find those exact values. In any kind of photo, nothing is exact. You need to find ranges of values.

cv.imread returns data in BGR order. Be aware of that if you access individual values in the numpy array.

Use this:

import numpy as np
import cv2 as cv

img = cv.imread("3.png")

lower_bound = (224-20, 96-20, 32-20) # BGR
upper_bound = (224 20, 96 20, 32 20) # BGR
mask = cv.inRange(img, lower_bound, upper_bound)
count = cv.countNonZero(mask)
print(f"picture contains {count} pixels of that color")

And if you need to know where pixels of that color are, please explain what you need that for. A list of those points is generally useless. There are more useful ways to get these locations but they depend on why you need this information, what for.

  • Related