Home > front end >  Check whether all pixels in a cropped image have a specific color (OpenCV/Python)
Check whether all pixels in a cropped image have a specific color (OpenCV/Python)

Time:08-18

import cv2
import numpy as np


cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    
    tag = frame[235:245, 315:325]
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    lower_red = np.array([20, 20, 50])
    upper_red = np.array([255, 255, 130])
    
    for i in range (235,245):
        for j in range (315,325):
                if cv2.inRange(tag[i][j],lower_red,upper_red):
                    break
        
        cv2.imshow('image',frame)
    
        if cv2.waitKey(1) == ord('q'):
            break
        
    cap.release()
    cv2.destroyAllWindows()

i want to check my middle 100 pixels in my 480,640 camera to see if they all fall in a certain color range and if they do to end the program but i cant find i way to compare the values of the middle 100 pixels with the values that i want

CodePudding user response:

Problems with your approach:

1. Improper variable handling: You are cropping your image to tag before converting to HSV color space

2. Wrong usage of cv2.inRange(): The function returns a binary image of values either 0 or 255.

  • 0 -> if the pixels do not fall in range

  • 255 -> if the pixels fall in range

Thumb rule: Avoid using for loops


Solution:

Since cv2.inRange() returns a binary image, just find the average of the pixel values within the cropped image. If the average is 255 (all the pixels are white and within the color range) -> break!


You can alter your code using the following snippet:

ret, frame = cap.read()

hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_red = np.array([20, 20, 50])
upper_red = np.array([255, 255, 130])

tag = hsv[235:245, 315:325]
mask = cv2.inRange(tag, lower_red, upper_red)

if np.mean(mask) == 255:
    print("All the pixels are within the color range")
    break
  • Related