Python script to check if RED color is present in Image and call other function

Viewed 3153

Am learning Python and Open CV now. My problem is I need to find if my image as RED color, If it has red color call one function if it doesnot have RED color call an other function. I have code to find the RED color in my image, problem is am not able to write If condition like if image as RED do this else do this.

Can anyone help me with this ? Below is the code am trying with this am able to detect RED color and print the image but not able to add condition in my script. Please help me to solve this issue.

import cv2
import numpy as np
img = cv2.imread("Myimage.png")
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask1 = cv2.inRange(img_hsv, (0,50,20), (5,255,255))
mask2 = cv2.inRange(img_hsv, (175,50,20), (180,255,255))
mask = cv2.bitwise_or(mask1, mask2 )
croped = cv2.bitwise_and(img, img, mask=mask)
cv2.imshow("mask", mask)
cv2.imshow("croped", croped)
cv2.waitKey()
2 Answers

Assuming the variable mask contains the areas that are RED and is a binary array then you can just sum the elements that are 1 and compare the sum to zero. If no elements are 1 than your image does not contain RED

if (mask == 1).sum() > 1:
    # do your stuff

The idea is to check the mask image for white pixels with cv2.countNonZero(). After color thresholding with cv2.inRange(), you will get a binary mask with any pixels within the lower and upper HSV thresholds in white. So you can simply check if white pixels exist on the mask to determine if red is present in the image

# Binary mask with pixels matching the color threshold in white
mask = cv2.bitwise_or(mask1, mask2)

# Determine if the color exists on the image
if cv2.countNonZero(mask) > 0:
    print('Red is present!')
else:
    print('Red is not present!')
Related