模板匹配
模板匹配属于模式识别算法,用以从已定义的图片中与模板寻找相似内容。其函数声明如下:
matchTemplate(src, templ, result, method);
其中src为输入图片(大小W X H),templ为模板图像(大小w X h),result为输出的结果,大小为(W - w + 1) X (H - h + 1);method为计算方法。
Java代码(JavaFX Controller层)
public class Controller{
@FXML private Text fxText;
@FXML private ImageView imageView;
@FXML private TextArea textArea;
@FXML public void handleButtonEvent(ActionEvent actionEvent) throws IOException {
Node source = (Node) actionEvent.getSource();
Window theStage = source.getScene().getWindow();
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.png");
fileChooser.getExtensionFilters().add(extFilter);
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("JPG Files(*.jpg)", "*.jpg"));
File file = fileChooser.showOpenDialog(theStage);
runInSubThread(file.getPath());
}
private void runInSubThread(String filePath){
new Thread(new Runnable() {
@Override
public void run() {
try {
WritableImage writableImage = histogramCompared(filePath);
Platform.runLater(new Runnable() {
@Override
public void run() {
imageView.setImage(writableImage);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private WritableImage templateMatch(String filePath) throws IOException {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// Read source image to src.
Mat src = Imgcodecs.imread(filePath);
Mat dst = new Mat();
Mat template = Imgcodecs.imread("E:/Chrome/lenna_test.jpg");
int height = src.rows() - template.rows() + 1;
int width = src.cols() - template.cols() + 1;
Mat result = new Mat(height, width, CvType.CV_32FC1);
Imgproc.matchTemplate(src, template, result, Imgproc.TM_CCOEFF_NORMED);
Core.MinMaxLocResult minMaxLocResult = Core.minMaxLoc(result);
Point maxloc = minMaxLocResult.maxLoc;
Point minloc = minMaxLocResult.minLoc;
Point matchloc = null;
if (Imgproc.TM_CCOEFF_NORMED == Imgproc.TM_SQDIFF || Imgproc.TM_CCOEFF_NORMED == Imgproc.TM_SQDIFF_NORMED){
matchloc = minloc;
} else {
matchloc = maxloc;
}
src.copyTo(dst);
Imgproc.rectangle(dst, matchloc, new Point(matchloc.x + template.cols(), matchloc.y + template.rows()), new Scalar(255,255,0), 2);
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", dst, matOfByte);
byte[] bytes = matOfByte.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage bufImage = ImageIO.read(in);
WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
return writableImage;
}
}
相关图片