OpenCV Better Detection Of Red Color? - Stack Overflow

    1. Home
    2. Questions
    3. Tags
    4. Users
    5. Companies
    6. Labs
    7. Jobs
    8. Discussions
    9. Collectives
    10. Communities for your favorite technologies. Explore all Collectives

  1. Teams

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

    Try Teams for free Explore Teams
  2. Teams
  3. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Get early access and see previews of new features.

Learn more about Labs OpenCV better detection of red color? Ask Question Asked 9 years, 2 months ago Modified 2 years, 6 months ago Viewed 68k times 31

I have the following image:

enter image description here

I would like to detect the red rectangle using cv::inRange method and HSV color space.

int H_MIN = 0; int H_MAX = 10; int S_MIN = 70; int S_MAX = 255; int V_MIN = 50; int V_MAX = 255; cv::cvtColor( input, imageHSV, cv::COLOR_BGR2HSV ); cv::inRange( imageHSV, cv::Scalar( H_MIN, S_MIN, V_MIN ), cv::Scalar( H_MAX, S_MAX, V_MAX ), imgThreshold0 );

I already created dynamic trackbars in order to change the values for HSV, but I can't get the desired result.

Any suggestion for best values (and maybe filters) to use?

Share Improve this question Follow edited May 7, 2022 at 19:43 Jeru Luke's user avatar Jeru Luke 21.1k13 gold badges83 silver badges91 bronze badges asked Sep 11, 2015 at 11:58 Kristian Vitozev's user avatar Kristian VitozevKristian Vitozev 5,9416 gold badges37 silver badges56 bronze badges Add a comment |

2 Answers 2

Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 66

In HSV space, the red color wraps around 180. So you need the H values to be both in [0,10] and [170, 180].

Try this:

#include <opencv2\opencv.hpp> using namespace cv; int main() { Mat3b bgr = imread("path_to_image"); Mat3b hsv; cvtColor(bgr, hsv, COLOR_BGR2HSV); Mat1b mask1, mask2; inRange(hsv, Scalar(0, 70, 50), Scalar(10, 255, 255), mask1); inRange(hsv, Scalar(170, 70, 50), Scalar(180, 255, 255), mask2); Mat1b mask = mask1 | mask2; imshow("Mask", mask); waitKey(); return 0; }

Your previous result:

enter image description here

Result adding range [170, 180]:

enter image description here

Another interesting approach which needs to check a single range only is:

  • invert the BGR image
  • convert to HSV
  • look for cyan color

This idea has been proposed by fmw42 and kindly pointed out by Mark Setchell. Thank you very much for that.

#include <opencv2\opencv.hpp> using namespace cv; int main() { Mat3b bgr = imread("path_to_image"); Mat3b bgr_inv = ~bgr; Mat3b hsv_inv; cvtColor(bgr_inv, hsv_inv, COLOR_BGR2HSV); Mat1b mask; inRange(hsv_inv, Scalar(90 - 10, 70, 50), Scalar(90 + 10, 255, 255), mask); // Cyan is 90 imshow("Mask", mask); waitKey(); return 0; }

enter image description here

Share Improve this answer Follow edited May 23, 2017 at 12:26 Community's user avatar CommunityBot 11 silver badge answered Sep 11, 2015 at 12:27 Miki's user avatar MikiMiki 41.7k13 gold badges128 silver badges208 bronze badges 3
  • 4 Just a cool little trick from @fmw42 that I wanted to share... you can invert the image and look for cyans which don't wrap :-) stackoverflow.com/a/43926013/2836621 – Mark Setchell Commented May 12, 2017 at 8:12
  • 1 @MarkSetchell that's clever! Added to the answer with C++ code for completeness. Thank you very much! – Miki Commented May 12, 2017 at 8:30
  • Can you help me please? my imshow("Mask", mask) gives an error. error: (-215) size.width>0 && size.height>0 in function imshow. As far as I understood, the error is because mask.data == null . What am I doing wrong? Thanks in advance – gbossa Commented Jul 23, 2020 at 19:20
Add a comment | 3

While working with dominant colors such as red, blue, green and yellow; analyzing the two color channels of the LAB color space keeps things simple. All you need to do is apply a suitable threshold on either of the two color channels.

1. Detecting Red color

Background :

The LAB color space represents:

  • the brightness value in the image in the primary channel (L-channel)

while colors are expressed in the two remaining channels:

  • the color variations between red and green are expressed in the secondary channel (A-channel)
  • the color variations between yellow and blue are expressed in the third channel (B-channel)

Code :

import cv2 img = cv2.imread('red.png') # convert to LAB color space lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) # Perform Otsu threshold on the A-channel th = cv2.threshold(lab[:,:,1], 127, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

Result:

I have placed the LAB converted image and the threshold image besides each other.

enter image description here

2. Detecting Blue color

Now lets see how to detect blue color

Sample image:

enter image description here

Since I am working with blue color:

  • Analyze the B-channel (since it expresses blue color better)
  • Perform inverse threshold to make the blue region appear white

(Note: the code changes below compared to the one above)

Code :

import cv2 img = cv2.imread('blue.jpg') # convert to LAB color space lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) # Perform Otsu threshold on the A-channel th = cv2.threshold(lab[:,:,2], 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

Result:

Again, stacking the LAB and final image:

enter image description here

Conclusion :

  • Similar processing can be performed on green and yellow colors
  • Moreover segmenting a range of one of these dominant colors is also much simpler.
Share Improve this answer Follow edited May 27, 2022 at 19:35 answered May 7, 2022 at 19:59 Jeru Luke's user avatar Jeru LukeJeru Luke 21.1k13 gold badges83 silver badges91 bronze badges Add a comment |

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid …

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Draft saved Draft discarded

Sign up or log in

Sign up using Google Sign up using Email and Password Submit

Post as a guest

Name Email

Required, but never shown

Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.

  • The Overflow Blog
  • We'll Be In Touch - A New Podcast From Stack Overflow!
  • The app that fights for your data privacy rights
  • Featured on Meta
  • More network sites to see advertising test
  • We’re (finally!) going to the cloud!
  • Call for testers for an early access release of a Stack Overflow extension...

Linked

0 Convert single BGR color to HSV C++ OpenCV 4 1 OpenCV can't detect color red correctly 24 How to detect two different colors using `cv2.inRange` in Python-OpenCV? 5 How to find the RED color regions using OpenCV? 3 using histogram to determine colored object presence? 4 OpenCV inRange() function 5 How to accurately detect the positions of hollow circles (rings) with OpenCV Python? 2 Color thresholding of red rimmed traffic signs 2 whats the ranges of the red in HSV? 0 Find first red pixel and crop picture See more linked questions 0 Separating out Red component image from an RGB image in opencv 2.3 6 Color detection opencv 2 Most efficient method to detect color using OpenCV? 0 Detect red color in different illumination or background 23 efficiently threshold red using HSV in OpenCV 3 Color detection in opencv 2 OpenCV color detection with similar color background 39 Finding red color in image using Python & OpenCV 2 Color detection of object in Image 1 How To Detect Red Color In OpenCV Python?

Hot Network Questions

  • Does Windows 11 PIN Behavior Break Password Security Conventions?
  • Asymptotic Expansion of a Recurrence Relation Involving a Square Root
  • How SMA (or RF) connector's impedance is measured and rated?
  • Undesired blank space
  • Why do some people write text all in lower case?
  • Commencement and repeal dates in UK Acts of Parliament - meaning of "From and after"
  • 1980s or 90s space cartoon with a space prince and princess
  • Bleeding radiators
  • What are the ethical considerations regarding mandatory class participation?
  • User temp folder is 103GB. Is it safe to delete?
  • Does the earliest known use of an "average" occur after the invention of calculus?
  • C# basic calculator
  • Generator breaker trips when hooked up for backfeed
  • Why「记」for shop names?
  • Is my evaluation for this multiple linear regression correct?
  • Why does glm in R with family binomial(link="log") sometimes require start values?
  • Does a touch spell have advantage when delivered by an invisible Familiar?
  • How to create a thesis flowchart using Mathematica?
  • Suggestion for catching a flight with short layover in Amsterdam
  • block nvme0n1: no uuid available providing old nguid - after disk cloning
  • How to protect against fake gold bars?
  • Can a contradiction exist in the antecedent of a sequent?
  • Brushing pastries with jam
  • What is it called when you have a hobby where you're good enough at to impress others but you yourself know you're only beginning?
more hot questions Question feed Subscribe to RSS Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-cpp

Từ khóa » Hsv Color Space Red