I want to detect features in an image with OpenCV using back projection.
For a start I would be very happy to compute a histogram of a single colored small image and then apply it on a larger image. Then I can build more on top of that. There is a example in C++ and I would like to do something like this in Java. Sadly, the Java interface to OpenCV is not very well documented.
Below is the code I have so far, but it is not working (obviously, else I wouldn't ask for help). It would be very great if someone could help me get it working or find some good documentation for the Java API!
import java.util.ArrayList;
import org.opencv.core.*;
import org.opencv.imgproc.Imgproc;
public class ColorHistogramDetector extends ColorThresholdDetector {
//private cvHistogram histogram;
//histogram resolution for hue and saturation
static final int hbins = 30;//, sbins = 32;
public synchronized Mat detect(Mat inputFrame) {
Mat calcFrame = new Mat();
Imgproc.cvtColor(inputFrame, calcFrame, Imgproc.COLOR_RGB2HSV);
Mat hue = calcFrame;
ArrayList<Mat> dst = new ArrayList<Mat>();
dst.add(hue);
//create single color image
Mat fillImg = new Mat(16, 16, CvType.CV_8UC3);
fillImg.setTo(hsvColor);
MatOfInt histSize=new MatOfInt(hbins,hbins);
// hue varies from 0 to 179, see cvtColor
// saturation varies from 0 (black-gray-white) to
// 255 (pure spectrum color)
MatOfFloat ranges = new MatOfFloat( 0,180,0,256 );
Mat hist = new Mat();
// we compute the histogram from the 0-th and 1-st channels
MatOfInt channels = new MatOfInt(0, 1);
ArrayList<Mat> fillImgs=new ArrayList<Mat>();
fillImgs.add(fillImg);
Imgproc.calcHist(fillImgs, channels, new Mat(), hist, histSize, ranges);
outputFrame = new Mat();
Imgproc.calcBackProject(dst, channels, hist, calcFrame, ranges, 1);
int w = inputFrame.cols(); int h = inputFrame.rows();
int bin_w = (int) Math.round( (double) w / hbins );
Mat histImg = new Mat( w, h, CvType.CV_8UC3 );
for( int i = 0; i < hbins; i ++ ) {
Core.rectangle( histImg, new Point( i*bin_w, h ),
new Point( (i+1)*bin_w,
h - Math.round( hist.get(0, i)[0]*h/255.0 ) ),
new Scalar( 0, 0, 255 ), -1 );
}
hist.release();
fillImg.release();
Imgproc.cvtColor(histImg, calcFrame, Imgproc.COLOR_RGB2HSV);
return calcFrame;
}
}