Tracking White Color Using Python Opencv - 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 Tracking white color using python opencv Ask Question Asked 10 years, 8 months ago Modified 5 years, 1 month ago Viewed 100k times 37

I would like to track white color using webcam and python opencv. I already have the code to track blue color.

_, frame = cap.read() hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # define range of blue color in HSV lower_blue = np.array([110,100,100]) upper_blue = np.array([130,255,255]) #How to define this range for white color # Threshold the HSV image to get only blue colors mask = cv2.inRange(hsv, lower_blue, upper_blue) # Bitwise-AND mask and original image res = cv2.bitwise_and(frame,frame, mask= mask) cv2.imshow('frame',frame) cv2.imshow('mask',mask) cv2.imshow('res',res)

what values should I give as lower bound and upper bound to track white color!!?? I tried changing values and I got other colors but no luck with the white color!!!

is that HSV values or BGR values specified as lower and upper bounds???

PS : I must get the last result as a binary image for further processing!!

Please help me !!!

Share Improve this question Follow edited May 24, 2014 at 12:50 Alessandro Jacopson's user avatar Alessandro Jacopson 18.6k16 gold badges104 silver badges155 bronze badges asked Mar 23, 2014 at 7:23 user3429616's user avatar user3429616user3429616 3811 gold badge4 silver badges8 bronze badges 1
  • Just fixed my code so it now indeed produces low saturation and high value :) – Legat Commented Mar 23, 2014 at 9:12
Add a comment |

3 Answers 3

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

Let's take a look at HSV color space:

enter image description here

You need white, which is close to the center and rather high. Start with

sensitivity = 15 lower_white = np.array([0,0,255-sensitivity]) upper_white = np.array([255,sensitivity,255])

and then adjust the threshold to your needs.

You might also consider using HSL color space, which stands for Hue, Saturation, Lightness. Then you would only have to look at lightness for detecting white and recognizing other colors would stay easy. Both HSV and HSL keep similar colors close. Also HSL would probably prove more accurate for detecting white - here is why:

enter image description here

Share Improve this answer Follow edited Mar 23, 2014 at 9:24 answered Mar 23, 2014 at 8:01 Legat's user avatar LegatLegat 1,4393 gold badges12 silver badges20 bronze badges 3
  • How to reduce the useless noise !!!! everythingis getting tracked when i use a webcam – user3429616 Commented Mar 23, 2014 at 9:13
  • With new color components as well. You can set the thresholds higher. Let me edit the answer once more to clarify :) – Legat Commented Mar 23, 2014 at 9:16
  • Ready. Used sensitivity instead of threshold. Lower sensitivity gives less noise. – Legat Commented Mar 23, 2014 at 9:24
Add a comment | 22

Here's an HSV color thresholder script to determine the lower and upper bounds using sliders

enter image description here

Results

Using this sample image

With these lower/upper thresholds

lower_white = np.array([0,0,168]) upper_white = np.array([172,111,255])

We get isolated white pixels (left) and the binary mask (right)

Here's the script, remember to change the input image path

import cv2 import sys import numpy as np def nothing(x): pass # Load in image image = cv2.imread('1.jpg') # Create a window cv2.namedWindow('image') # create trackbars for color change cv2.createTrackbar('HMin','image',0,179,nothing) # Hue is from 0-179 for Opencv cv2.createTrackbar('SMin','image',0,255,nothing) cv2.createTrackbar('VMin','image',0,255,nothing) cv2.createTrackbar('HMax','image',0,179,nothing) cv2.createTrackbar('SMax','image',0,255,nothing) cv2.createTrackbar('VMax','image',0,255,nothing) # Set default value for MAX HSV trackbars. cv2.setTrackbarPos('HMax', 'image', 179) cv2.setTrackbarPos('SMax', 'image', 255) cv2.setTrackbarPos('VMax', 'image', 255) # Initialize to check if HSV min/max value changes hMin = sMin = vMin = hMax = sMax = vMax = 0 phMin = psMin = pvMin = phMax = psMax = pvMax = 0 output = image wait_time = 33 while(1): # get current positions of all trackbars hMin = cv2.getTrackbarPos('HMin','image') sMin = cv2.getTrackbarPos('SMin','image') vMin = cv2.getTrackbarPos('VMin','image') hMax = cv2.getTrackbarPos('HMax','image') sMax = cv2.getTrackbarPos('SMax','image') vMax = cv2.getTrackbarPos('VMax','image') # Set minimum and max HSV values to display lower = np.array([hMin, sMin, vMin]) upper = np.array([hMax, sMax, vMax]) # Create HSV Image and threshold into a range. hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, lower, upper) output = cv2.bitwise_and(image,image, mask= mask) # Print if there is a change in HSV value if( (phMin != hMin) | (psMin != sMin) | (pvMin != vMin) | (phMax != hMax) | (psMax != sMax) | (pvMax != vMax) ): print("(hMin = %d , sMin = %d, vMin = %d), (hMax = %d , sMax = %d, vMax = %d)" % (hMin , sMin , vMin, hMax, sMax , vMax)) phMin = hMin psMin = sMin pvMin = vMin phMax = hMax psMax = sMax pvMax = vMax # Display output image cv2.imshow('image',output) # Wait longer to prevent freeze for videos. if cv2.waitKey(wait_time) & 0xFF == ord('q'): break cv2.destroyAllWindows() Share Improve this answer Follow answered Oct 1, 2019 at 23:12 nathancy's user avatar nathancynathancy 46.3k15 gold badges131 silver badges153 bronze badges 0 Add a comment | 21

I wrote this for tracking white color :

import cv2 import numpy as np cap = cv2.VideoCapture(0) while(1): _, frame = cap.read() hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # define range of white color in HSV # change it according to your need ! lower_white = np.array([0,0,0], dtype=np.uint8) upper_white = np.array([0,0,255], dtype=np.uint8) # Threshold the HSV image to get only white colors mask = cv2.inRange(hsv, lower_white, upper_white) # Bitwise-AND mask and original image res = cv2.bitwise_and(frame,frame, mask= mask) cv2.imshow('frame',frame) cv2.imshow('mask',mask) cv2.imshow('res',res) k = cv2.waitKey(5) & 0xFF if k == 27: break cv2.destroyAllWindows()

I tried to track the white screen of my phone and got this :

enter image description here

You can try changing the HSV values You might also try HSL color space as Legat said, it would be more accurate

Share Improve this answer Follow answered Mar 23, 2014 at 8:35 Vipul's user avatar VipulVipul 4,1489 gold badges34 silver badges56 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...
Visit chat

Linked

2 counting total pixel numbers of white color in an image 1 Color Space Segmentation not detecting white spaces? 0 Detecting color in ycbcr in python 1 Missing part of a contour in finding Contour opencv (affected by white background, document scanner) 1 how to detect clouds in image using opencv python 0 Tracking two different colors using OpenCV 2.3 and Python 13 color detection using opencv python 15 Python OpenCV Color Tracking 4 OpenCv Python Color Detection 1 MultiColor tracking using opencv and python 8 Tracking yellow color object with OpenCV python 0 Color Detection And Comaparision In Python 0 How to accurately detect brown/black/grey/white on this picture with openCV 1 Color values for opencv detection 0 Color detection using opencv-python

Hot Network Questions

  • Is my evaluation for this multiple linear regression correct?
  • How to create a thesis flowchart using Mathematica?
  • Does the canonical distribution assign probability to microstates or macrostates?
  • How SMA (or RF) connector's impedance is measured and rated?
  • Prove or disprove that the envelope of some chords of a conic section is another conic section
  • Why constrain the unit type by a generic trait bound in a where clause (as in `where () : Trait<…>`)?
  • Suggestion for catching a flight with short layover in Amsterdam
  • Why do some people write text all in lower case?
  • Why don't routers answer ARP requests for IP addresses they can handle even if they aren't assigned that IP address themselves?
  • Bleeding radiators
  • Why「记」for shop names?
  • Do the surreal numbers enjoy the transfer principle in ZFC?
  • Commencement and repeal dates in UK Acts of Parliament - meaning of "From and after"
  • Stable points in GIT: geometric picture
  • Do rediscoveries justify publication?
  • Can Netanyahu use sovereign or diplomatic immunity as his defence to evade the arrest warrant issued by the ICC?
  • How to handle a campaign where the players are trapped inside a monster controlled by another player?
  • Testing Puzzles for Puzzle Book: Enigmatic Puzzle
  • Why am I getting no output in tcpdump even though there is data being sent and received when using network namespaces?
  • Scandinavian film, 1980s, possibly called Royal Toilet?
  • A dark animated movie about an orphaned girl working in an oppressive factory
  • Chain skipping when pedaling hard
  • Why would you not issue orders to a facility?
  • NginX Permission denied
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-py

Từ khóa » Hsv Color Space White