OpenCV.相机使用

相机使用
相机的使用依赖VideoCapture类与具体的硬件设备

VideoCapture类

new VideoCapture对象的时候,一个构造器为index的构造器决定了初始化时摄像头位置,0代表前置(面向用户),1代表后置。isOpened() 方法返回是否可用避免竞争资源。

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();

        runInSubThread(file.getPath());

    }

    private void runInSubThread(String filePath){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    WritableImage writableImage = cameraCapture();

                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            imageView.setImage(writableImage);
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private WritableImage cameraCapture(){
        WritableImage WritableImage = null;

        // Loading the OpenCV core library
        System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

        // Instantiating the VideoCapture class (camera:: 0)
        VideoCapture capture = new VideoCapture(0);

        // Reading the next video frame from the camera
        Mat matrix = new Mat();
        capture.read(matrix);

        // If camera is opened
        if( capture.isOpened()) {
            // If there is next video frame
            if (capture.read(matrix)) {
                // Creating BuffredImage from the matrix
                BufferedImage image = new BufferedImage(matrix.width(),
                        matrix.height(), BufferedImage.TYPE_3BYTE_BGR);

                WritableRaster raster = image.getRaster();
                DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
                byte[] data = dataBuffer.getData();
                matrix.get(0, 0, data);
 
                // Creating the Writable Image
                WritableImage = SwingFXUtils.toFXImage(image, null);
            }
        }
        return WritableImage;

    }

}


相关图片

EarPods包装盒相机捕捉图

图1 - 捕捉图
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值