Search code examples
scalaopencvhistogramjavacv

How to create a HSV-Histogram with JavaCV


I'm new in JavaCV and want to create a Histogram from a image.

I tried to translate some C++ code into Java but JavaCV don't have methods like cvCVtPixToPlane.

Can someone help me to create a histogram?


Solution

  • a translatet OpenCV-Code from the OpenCV-Wiki must be run.

    I give you my code snipet to create a 1D-Diagram from the h-channel:

    private CvHistogram getHueHistogram(IplImage image){
        if(image==null || image.nChannels()<3) new Exception("Error!");
        IplImage hsvImage= cvCreateImage(image.cvSize(), image.depth(), 3);
        cvCvtColor(image, hsvImage, CV_BGR2HSV);
        // Split the 3 channels into 3 images
        IplImageArray hsvChannels = splitChannels(hsvImage);
        //bins and value-range
        numberOfBins=255;
        float minRange= 0f;
        float maxRange= 180f;
        // Allocate histogram object
       int dims = 1;
       int[]sizes = new int[]{numberOfBins};
       int histType = CV_HIST_ARRAY;
       float[] minMax = new  float[]{minRange, maxRange};
       float[][] ranges = new float[][]{minMax};
        int uniform = 1;
        CvHistogram hist = cvCreateHist(dims, sizes, histType, ranges, uniform);
        // Compute histogram
        int accumulate = 1;
        IplImage mask = null;
        cvCalcHist(hsvChannels.position(0),hist, accumulate, null);
        return hist;
    }
    

    And my splitChannels-Method, i used in this snipet:

    private IplImageArray splitChannels(IplImage hsvImage) {
        CvSize size = hsvImage.cvSize();
        int depth=hsvImage.depth();
        IplImage channel0 = cvCreateImage(size, depth, 1);
        IplImage channel1 = cvCreateImage(size, depth, 1);
        IplImage channel2 = cvCreateImage(size, depth, 1);
        cvSplit(hsvImage, channel0, channel1, channel2, null);
        return new IplImageArray(channel0, channel1, channel2);
    }
    

    If you want to draw a picture from the histogram you can iterate the bins. With cvQueryHistValue_1D() you can get the sum of pixels from bin_i