PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, May 10, 2022

[FIXED] how to return boolean if certain color exist in captured area using python

 May 10, 2022     colors, detection, image, opencv, python     No comments   

Issue

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.

  1. Capture image using

  2. find whether certain color (eg. red, blue green) exist in the captured image

  3. 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

Here are two ways to do that in Python/OpenCV.

Use color thresholding with cv2.inRange(). Then either count the number of white pixels using np.nonzero() or test the average over the thresholded image with cv2.mean().

Input:

enter image description here

import cv2
import numpy as np

# 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)

# Method 1: count number of white pixels and test if zero
count = np.sum(np.nonzero(thresh))
print("count =",count)
if count == 0:
    print("Not Red")
else:
    print("Red")

print("")

# Method 2: get the average of the image and test if zero
average = cv2.mean(thresh)[0]
print("average =",average)
if average == 0:
    print("Not Red")
else:
    print("Red")

# write thresholded image to disk
cv2.imwrite("red_brushed_thresh.png", thresh)

# display it
cv2.imshow("IMAGE", img)
cv2.imshow("THRESH", thresh)
cv2.waitKey(0)


Thresholded image:

enter image description here

Textual Results:

count = 3534485
Red

average = 6.933746337890625
Red




Answered By - fmw42
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing