在javafx

时间:2018-05-08 13:40:51

标签: java javafx motion-detection

我需要帮助来检测JavaFX中的运动。仅在检测到运动时开始记录,并且在某段时间没有检测到运动时停止记录。 一切正常,但运动检测部分效果不佳。

我使用了sarxos库:https://github.com/sarxos/webcam-capture

有任何建议吗?

这是javafx控制器类。

public class MonitorController implements Initializable {

    private static double v;
    @FXML
    private VBox monitor;
    @FXML
    JFXButton btnStartCamera, btnStopCamera;
    @FXML
    JFXComboBox<WebCamInfo> cbCameraOptions;
    @FXML
    BorderPane bpWebCamPaneHolder;
    @FXML
    FlowPane fpBottomPane;
    @FXML
    ImageView imgWebCamCapturedImage;
    int i = 0;
    @FXML
    private JFXSlider jfxSlider;
    private BufferedImage grabbedImage, grabbedImage2;
    private boolean stopCamera = false, stopCamera2 = false;
    private Webcam selWebCam = null;
    private ObjectProperty<Image> imageProperty = new SimpleObjectProperty<Image>();
    private IMediaWriter writer, writer2;
    private String cameraListPromptText = "Choose Camera";
    private File file = null, file2 = null;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy hh-mm-ss aa");

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {
        fpBottomPane.setDisable(true);
        ObservableList<WebCamInfo> options = FXCollections.observableArrayList();
        int webCamCounter = 0;
        for (Webcam webcam : Webcam.getWebcams()) {
            WebCamInfo webCamInfo = new WebCamInfo();
            webCamInfo.setWebCamIndex(webCamCounter);
            webCamInfo.setWebCamName(webcam.getName());
            options.add(webCamInfo);
            webCamCounter++;
        }
        cbCameraOptions.setItems(options);
        cbCameraOptions.setPromptText(cameraListPromptText);
        cbCameraOptions.getSelectionModel().selectedItemProperty().addListener((arg01, arg11, arg2) -> {
            if (arg2 != null) {
                System.out.println("WebCam Index: " + arg2.getWebCamIndex() + ": WebCam Name:" + arg2.getWebCamName());
                initializeWebCam(arg2.getWebCamIndex());
            }
        });
    }

    protected void setImageViewSize() {

        double height = bpWebCamPaneHolder.getHeight();
        double width = bpWebCamPaneHolder.getWidth();
        imgWebCamCapturedImage.setFitHeight(height);
        imgWebCamCapturedImage.setFitWidth(width);
        imgWebCamCapturedImage.setSmooth(true);
        imgWebCamCapturedImage.setPreserveRatio(false);
    }

    private void initializeWebCam(final int webCamIndex) {

        Task<Void> webCamIntilizer = new Task<Void>() {

            @Override
            protected Void call() throws Exception {
                if (selWebCam == null) {
                    selWebCam = Webcam.getWebcams().get(webCamIndex);
                    selWebCam.open();
                } else {
                    closeCamera();
                    selWebCam = Webcam.getWebcams().get(webCamIndex);
                    selWebCam.open();
                }
                startWebCamStream();
                return null;
            }

        };

        new Thread(webCamIntilizer).start();
        fpBottomPane.setDisable(false);
        btnStartCamera.setDisable(true);
    }

    //main method that will record the videos
    private synchronized void startWebCamStream() {
        stopCamera = false;
        stopCamera2 = false;
        Date date = new Date();
        File folder = new File("VideoRecordings");

        //without motion detection video
        Task<Void> task = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                file = new File(folder,"NormalVideo("+dateFormat.format(date.getTime())+").mp4");
                writer = ToolFactory.makeWriter(file.getName());
                Dimension size = WebcamResolution.QVGA.getSize();
                writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_H264, size.width, size.height);
                long start = System.currentTimeMillis();
                try {
                    while (!stopCamera) {
                        if ((grabbedImage = selWebCam.getImage()) != null) {
                            Platform.runLater(() -> {
                                final Image mainiamge = SwingFXUtils.toFXImage(grabbedImage, null);
                                imageProperty.set(mainiamge);
                            });
                            BufferedImage image = ConverterFactory.convertToType(grabbedImage, BufferedImage.TYPE_3BYTE_BGR);
                            IConverter converter = ConverterFactory.createConverter(image, IPixelFormat.Type.YUV420P);
                            IVideoPicture frame = converter.toPicture(image, ((System.currentTimeMillis() - start) * 1000));
                            frame.setKeyFrame(true);
                            frame.setQuality(0);
                            writer.encodeVideo(0,frame);
                        }
//                        grabbedImage.flush();
                    }
                } catch (Exception e) {
                } finally {
                }
                return null;
            }
        };
        //display video and pictures
        imgWebCamCapturedImage.imageProperty().bind(imageProperty);

        //with motion detection video
        Task<Void> task1 = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                WebcamMotionDetector detector = new WebcamMotionDetector(selWebCam);
                detector.setInterval(100); 

                jfxSlider.valueProperty().addListener((observable, oldValue, newValue) -> {
                    v = (double) newValue;
                    detector.setPixelThreshold((int) v);
                    });
                detector.start();

                file2 = new File(folder,"motionDetected("+dateFormat.format(date.getTime())+").mp4");
                writer2 = ToolFactory.makeWriter(file2.getName());
                Dimension size = WebcamResolution.QVGA.getSize();
                writer2.addVideoStream(0, 0, ICodec.ID.CODEC_ID_H264, size.width, size.height);


                long start = System.currentTimeMillis();
                while (!stopCamera2) {
                    if ((grabbedImage2 = selWebCam.getImage()) != null) {
                        if(detector.isMotion()){
                            while (detector.isMotion()) {
                                BufferedImage image = ConverterFactory.convertToType(grabbedImage2, BufferedImage.TYPE_3BYTE_BGR);
                                IConverter converter = ConverterFactory.createConverter(image, IPixelFormat.Type.YUV420P);
                                IVideoPicture frame = converter.toPicture(image, ((System.currentTimeMillis() - start) * 1000));
                                frame.setKeyFrame(true);
                                frame.setQuality(0);
                                writer2.encodeVideo(0, frame);
                            }
                            grabbedImage2.flush();
//                            writer2.close();
                        }
                    }
                }
                return null;
            }
        };


        Thread th = new Thread(task);
        Thread th2 = new Thread(task1);
        th.setDaemon(true);
        th.start();
        th2.setDaemon(true);
        th2.start();

    }

    private void closeCamera() {
        if (selWebCam != null) {
            selWebCam.close();
        }
    }

    @FXML
    private void stopCamera(ActionEvent event) {
        stopCameraAndRecording();
        btnStopCamera.setDisable(true);
        btnStartCamera.setDisable(false);
    }

    @FXML
    private void startCamera(ActionEvent event) {
        if(selWebCam.close()){
        }else{
            startWebCamStream();
            btnStopCamera.setDisable(false);
            btnStartCamera.setDisable(true);
        }
    }

    class WebCamInfo {
        private String webCamName;
        private int webCamIndex;

        public String getWebCamName() {
            return webCamName;
        }

        public void setWebCamName(String webCamName) {
            this.webCamName = webCamName;
        }

        public int getWebCamIndex() {
            return webCamIndex;
        }

        public void setWebCamIndex(int webCamIndex) {
            this.webCamIndex = webCamIndex;
        }

        @Override
        public String toString() {
            return webCamName;
        }

    }

    private void stopCameraAndRecording(){
        stopCamera = true;
        stopCamera2 = true;
        if (writer2!=null && writer2.isOpen()) {
            writer2.close();
        }
        if (writer!=null && writer.isOpen()) {
            writer.close();
        }
        closeCamera();
        Webcam.shutdown();
    }

}

0 个答案:

没有答案