JavaCV: Image Thresholding HSV color space

JavaCV (OpenCv) example of image thresholding based on color in HSV-A Space - to detect red color spot on given image. Useful in object tracking.
In this post, I’m going to show you how to detect a red‑colored spot in an image using JavaCV (OpenCV) and HSV color space thresholding – a building block for many object tracking applications.

Instead of struggling with RGB values that change drastically under different lighting, we switch to the HSV color model. Hue (H) represents the pure pigment, while Saturation and Value are separated. That makes color filtering far more robust. Red is special: its hue wraps around 0°, so the full range is 0–10° and 160–180°. In this example we target only the upper range (160–180) for bright red.

Java Source Code:

//imports
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
import com.googlecode.javacv.cpp.opencv_core.CvScalar;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

public class ColorDetect {
    // color range of red like color
    static int hueLowerR = 160;
    static int hueUpperR = 180;
    public static void main(String[] args) {
        IplImage orgImg = cvLoadImage("finding-red-color-spot.JPG");
        cvSaveImage("hsvthreshold.jpg", hsvThreshold(orgImg));

    }
    static IplImage hsvThreshold(IplImage orgImg) {
        // 8-bit, 3- color =(RGB)
        IplImage imgHSV = cvCreateImage(cvGetSize(orgImg), 8, 3);
        System.out.println(cvGetSize(orgImg));
        cvCvtColor(orgImg, imgHSV, CV_BGR2HSV);
        // 8-bit 1- color = monochrome
        IplImage imgThreshold = cvCreateImage(cvGetSize(orgImg), 8, 1);
        // cvScalar : ( H , S , V, A)
        cvInRangeS(imgHSV, cvScalar(hueLowerR, 100, 100, 0), cvScalar(hueUpperR, 255, 255, 0), imgThreshold);
        cvReleaseImage(imgHSV);
        cvSmooth(imgThreshold, imgThreshold, CV_MEDIAN, 13);
        // save
        return imgThreshold;
    }
}


How it works step by step:
1. We load the original image with cvLoadImage.
2. A blank HSV image of the same size is created, then we convert the BGR input to HSV using cvCvtColor.
3. The core thresholding is done by cvInRangeS: any pixel whose H, S, and V values fall inside the defined ranges becomes white (255) in the output mask – everything else becomes black (0). Here we accept H between 160 and 180, S between 100 and 255, and V between 100 and 255.
4. A median blur (cvSmooth with CV_MEDIAN and a kernel size of 13) cleans up the mask, removing salt‑and‑pepper noise and small false detections.
5. The resulting binary image is saved as hsvthreshold.jpg and returned.

After running the code, you’ll get a black‑and‑white image where the red spots appear as bright white blobs. Ready to be used for blob analysis or object tracking!

One thing to keep in mind: For a complete red detector that also catches the 0–10° hue range, you would need a second cvInRangeS and combine both masks with cvOr. The upper range alone works fine for bright, saturated reds.

Similar example but on RGB space is given here :

6 comments :

  1. Are you making software based on
    image processing ? Then you need to threshold the image
    for initial background subtraction, this
    task is really cumbersome as it is
    dynamic. But no more! With help of this
    software you can change the
    threshold values dynamically while
    camera is capturing live images! In short everything is dynamic and
    live. Enjoy!

    sourceforge.net/projects/dthresh/

    Description
    With help of active trackbars you can
    change the values of RGB and HSV to
    threshold the live image feed from
    your camera!

    ReplyDelete
    Replies
    1. Hi Dhaval, I tried using your app. But i could not run it at my Win7- 64bit machine.
      Its saying -
      The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail.

      Thanks.

      Delete
  2. this example is give me a blank image....means a black image.
    what is the problem....??

    ReplyDelete
    Replies
    1. This code uses thresholding operation to detect red color spot on given image. You need to change the color range :

      static int hueLowerR = YOUR_VALUE_LOWER;
      static int hueUpperR = YOUR_VALUE_UPPER;

      Delete
  3. wht to do to detect all the position of the red spot in the image!!
    i am having a image with the multiple red spot

    ReplyDelete
  4. Hi Ganesh ,
    Nice code thanks for the upload. If you dont mind my asking, in the line
    cvInRangeS(imgHSV, cvScalar(hueLowerR, 100, 100, 0), cvScalar(hueUpperR, 255, 255, 0), imgThreshold);

    WHy are there four variables ? and what would I need to change to make it detect green ??
    thanks
    Paddy

    ReplyDelete

Your Comment and Question will help to make this blog better...