使用 OpenCV 的 Java 中的 Back Projection
2022-09-01 17:49:16
我想使用反向投影使用OpenCV检测图像中的特征。
首先,我很乐意计算单个彩色小图像的直方图,然后将其应用于较大的图像。然后,我可以在此基础上构建更多内容。C++中有一个例子,我想在Java中做这样的事情。可悲的是,OpenCV的Java接口没有得到很好的记录。
以下是我到目前为止拥有的代码,但它不起作用(显然,否则我不会寻求帮助)。如果有人能帮助我让它工作或为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;
}
}