'how to return boolean if certain color exist in captured area using python
I am new to python and just started learning it on my own and I cannot find exact solution to my problem.
here's what I'm trying to do.
Capture image using
find whether certain color (eg. red, blue green) exist in the captured image
return boolean
i have spent couple of days searching for the answer but i cannot find any.
the only thing i know is to use openCV...
I guess the solution is too simple to ask. I am fairly new to computer language, so i would really appreciate as detailed as possible. thanks!
Solution 1:[1]
I came across this post while looking for a method to check if a certain color appeared in an image. I wanted to test the time it took to process either method.
Continuing with @fmw42's post:
import cv2
import numpy as np
import time
# read image
img = cv2.imread('red_brushed.png')
# set red range
lowcolor = (0,0,255)
highcolor =(128,128,255)
# threshold
thresh = cv2.inRange(img, lowcolor, highcolor)
t0 = time.process_time()
# Method 1: count number of white pixels and test if zero
count = np.sum(np.nonzero(thresh))
print(f"count = {count}")
if count == 0:
print("Not Red")
else:
print("Red")
print("")
t1 = time.process_time() - t0
print(f"Sum Method time elapsed {t1}")
t2 = time.process_time()
# Method 2: get the average of the image and test if zero
average = cv2.mean(thresh)[0]
print(f"average ={average}")
if average == 0:
print("Not Red")
else:
print("Red")
# write thresholded image to disk
cv2.imwrite("red_brushed_thresh.png", thresh)
t3 = time.process_time() - t2
print(f"Average Method time elapsed {t2}")
This produced the general output of:
Sum Method time elapsed 0.0013151379999999935
Average Method time elapsed 0.186069437
Using sum() and np.nonzero() always proved to be quicker.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joshua Willman |
