简单的实现JavaFX与OpenCV结合的实例

package com.xiuye.image;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

import org.opencv.core.Mat;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;


public class OpenCVImageViewer extends Application {

	public static String title;
	public static Mat img;

	@Override
	public void start(Stage primaryStage) throws Exception {

		//验证mat是不是为空
		if (img == null) {
			throw new NullPointerException("imshow img(Mat) is null");
		}
		//输出args获取的参数
		//log(this.getParameters().getRaw());
		if (title == null) {
			title = "ImageViewer";
		}

		//mat的宽度和高度
		int width = img.cols();
		int height = img.rows();

		//将mat的数据保存到BufferedImage对象中
		//注意mat的type(主要是通道数)和BufferedImage的type一致
		BufferedImage bf = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
		byte []data = new byte[width*height*(int)img.elemSize()];
		img.get(0, 0, data);
		//以下方法设置颜色有问题,原图像显示偏蓝,不正常
		//bf.getRaster().setDataElements(0, 0, width, height, data);
		//此方式设置的颜色能正常显示没问题
		byte[] tartgetData = ((DataBufferByte)bf.getRaster().getDataBuffer()).getData();
		System.arraycopy(data, 0, tartgetData, 0, data.length);

		//将BufferedImage转换为JavaFX能的显示的Image图像!
		Image image = SwingFXUtils.toFXImage(bf, null);
		ImageView iv = new ImageView(image);

		//采用流式布局(layout)
		FlowPane root = new FlowPane();
		root.getChildren().add(iv);

		Scene scene = new Scene(root,width,height);
		//给舞台设置场景
		primaryStage.setScene(scene);
		primaryStage.setTitle(title);
		primaryStage.show();

	}

	private static  void log(T t) {
		System.out.println(t);
	}

}


package com.xiuye.image;

import org.opencv.core.Mat;

import javafx.application.Application;

public class IV {

	/**
	 * 如果mat是图像,则输出mat
	 *
	 * JavaFX Application 代码中只能写一个launch(...),而且State
	 * 只能在Application线程中运行,所以现在的代码应该只能输出一个图像,即应该只能
	 * 调用一次imshow方法.
	 * @param t
	 * @param mat
	 * @param args
	 */
	public static void imshow(String t, final Mat mat, String... args) {
		OpenCVImageViewer.img = mat;
		// log(mat.dump());
		OpenCVImageViewer.title = t;
		Application.launch(OpenCVImageViewer.class, args);
	}

//	private static  void log(T t) {
//		System.out.println(t);
//	}

}

package com.xiuye.image;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;

public class ImageOp2 {
	static {
		System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
	}

	public static void main(String[] args) {
		Mat mat = Highgui.imread("p1.jpg");
		IV.imshow("User-Defined Imshow", mat);
	}

}


简单的实现JavaFX与OpenCV结合的实例_第1张图片





你可能感兴趣的:(Java)