Sunday, 10 January 2016

Color Filtering Using JavaCV

In this example, we will be demonstrating how to filter a single or multiple color from webcam captured image using cvInRanges() function before that we need to convert the image to HSV format and then setting the minimum and maximum value for the range to filter a particular color.

the initial set up is same as this example
http://errorsexception.blogspot.in/2016/01/basic-imagetransformation-using-javacv.html


The code:


import org.bytedeco.javacpp.Loader;
import org.bytedeco.javacv.*;
import org.bytedeco.javacv.FrameGrabber.Exception;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.opencv_core.CvPoint;
import org.bytedeco.javacpp.opencv_core.CvScalar;
import org.bytedeco.javacpp.opencv_core.CvSeq;
import org.bytedeco.javacpp.opencv_core.IplImage;
import org.bytedeco.javacpp.opencv_highgui.CvCapture;

import static org.bytedeco.javacpp.opencv_core.*;
import static org.bytedeco.javacpp.opencv_imgproc.*;
import static org.bytedeco.javacpp.opencv_calib3d.*;
import static org.bytedeco.javacpp.opencv_objdetect.*;
import static org.bytedeco.javacpp.opencv_highgui.*;
public class ColorFilter1 {

/**
* @param args
* @throws Exception 
*/
public static void main(String[] args) throws Exception {


IplImage  imghsv, imgbin;

imghsv = cvCreateImage(cvSize(640,480),8,3);
imgbin = cvCreateImage(cvSize(640,480),8,1);

OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
        grabber.start();
        IplImage grabbedImage = grabber.grab();

        CanvasFrame canvasFrame = new CanvasFrame("Cam");
        CanvasFrame canvasFrame1=new CanvasFrame("GrayImage");
        CanvasFrame canvasFrame2=new CanvasFrame("HSV Image");
        canvasFrame.setCanvasSize(grabbedImage.width(), grabbedImage.height());
        canvasFrame1.setCanvasSize(grabbedImage.width(), grabbedImage.height());
        canvasFrame2.setCanvasSize(grabbedImage.width(), grabbedImage.height());
        
        canvasFrame.setCanvasSize(grabbedImage.width(), grabbedImage.height());


while (canvasFrame.isVisible() && (grabbedImage = grabber.grab()) != null) {
//if(img1 == null) break;

cvCvtColor(grabbedImage,imghsv,CV_BGR2HSV);
CvScalar minc = cvScalar(95,150,75,0), maxc = cvScalar(145,255,255,0);//for filtering Blue color
cvInRangeS(imghsv,minc,maxc,imgbin);

canvasFrame.showImage(grabbedImage);
canvasFrame1.showImage(imgbin);
canvasFrame2.showImage(imghsv);
char c = (char)cvWaitKey(15);
if(c == 'q') break; 

}

cvReleaseImage(imghsv);
cvReleaseImage(imgbin);
}

}


Happy Coding 
for any issue please let me know

Thank you,
Ashutosh

0 comments:

Post a Comment