Ask Your Question
0

How to Detect video image in real-time. Using OpenCV

asked 2018-05-15 03:33:14 -0600

sniper101 gravatar image

updated 2018-05-15 09:59:23 -0600

This is the complete Source Code of the Project. It works, it detects the camera, frame set. But my problem is on how to detect the real-time detection of the image captured. I hope someone will help me regarding on this project. If you do, thanks a lot for helping me.. Best regards...

public class OpenCV extends Application {

static {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}

private boolean isStart = false;
private VideoCapture capture;
private ScheduledExecutorService timer;
private BorderPane root;
private VBox vboxCenter;
private ImageView frame;
private HBox hboxBottom;
private Button videoButton, exitButton;

@Override
public void start(Stage primaryStage) {

    initGui();

    capture = new VideoCapture();

    exitButton.setOnAction((ActionEvent event) -> {
        System.exit(0);
    });
    videoButton.setOnAction((ActionEvent event) -> {
        if (!isStart) {
            frame.setFitWidth(640);
            frame.setFitWidth(480);
            frame.setPreserveRatio(true);

            capture.open(0);
            capture.set(Videoio.CAP_PROP_FRAME_WIDTH, 640);
            capture.set(Videoio.CAP_PROP_FRAME_HEIGHT, 480);

            if (capture.isOpened()) {
                isStart = true;
                Runnable frameGrabber = new Runnable() {
                    @Override
                    public void run() {

                    //This code detect the camera and load the frame set
                    Image imageToShow = grabFrame();
                    frame.setImage(imageToShow); 

                CascadeClassifier faceDetector = 
                new CascadeClassifier("C:/Users/BEREDJ/Documents/NetBeansProjects/"
                        + "openCV/src/lbpcascades/lbpcascade_frontalcatface.xml");

                Mat image = Imgcodecs.imread("C:/Users/BEREDJ/Documents/"
                        + "NetBeansProjects/openCV/src/lbpcascades/image.png");  

                MatOfRect faceDetections = new MatOfRect();
                faceDetector.detectMultiScale(image, faceDetections);

                System.out.println(String.format("Detected %s faces",
                faceDetections.toArray().length));

                // Draw a bounding box around each face.
                    for (Rect rect : faceDetections.toArray()) {
                        Imgproc.rectangle(image, new Point(rect.x, rect.y),
                        new Point(rect.x + rect.width,
                        rect.y + rect.height), 
                        new Scalar(0, 255, 0));
                    }
                        //Save the visualized detection.
                        String filename = "faceDetection.png";
                        System.out.println(String.format("Writing %s", filename));
                        Imgcodecs.imwrite("faceDetection.png", image);         
                    }
                };
                timer = Executors.newSingleThreadScheduledExecutor();
                timer.scheduleAtFixedRate(frameGrabber, 0, 33, TimeUnit.MILLISECONDS);
                videoButton.setText("Stop");
            } else {
                System.err.println("Open Camera Error!");
            }
        } else {
            isStart = false;
            videoButton.setText("Start");
            try {
                timer.shutdown();
                timer.awaitTermination(33, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                System.err.println(e);
            }
            capture.release();
            frame.setImage(null);
        }
    });
    Scene scene = new Scene(root, 800, 640);
    primaryStage.setTitle("Video Capture Demo");
    primaryStage.setScene(scene);
    primaryStage.show();
}

private Image grabFrame() {
    Image result = null;
    Mat image = new Mat();

    if (capture.isOpened()) {
        capture.read(image);
        if (!image.empty()) {

            result = mat2Image(".png", image);

            //It save to the project directory
            Imgcodecs.imwrite("capture.png", image);
            HighGui.imshow("capture.png", image);
        }
    }
    return result;
}

public static Image mat2Image(String ext, Mat image) {
    MatOfByte buffer = new MatOfByte();
    Imgcodecs.imencode(ext, image, buffer);
    return new Image(new ByteArrayInputStream(buffer.toArray()));
}

private void initGui() {
    root = new BorderPane();
    vboxCenter = new VBox();
    vboxCenter.setAlignment(Pos.CENTER);
    vboxCenter.setPadding(javafx.geometry.Insets.EMPTY);
    frame = new ImageView();
    vboxCenter.getChildren().addAll(frame);
    root.setCenter(frame);

    hboxBottom = new HBox();
    hboxBottom.setAlignment(Pos.CENTER);
    hboxBottom.setPadding(javafx.geometry.Insets.EMPTY);
    videoButton = new Button("Start");
    exitButton = new Button ("Exit");
    hboxBottom.getChildren().addAll(videoButton,exitButton );
    root.setBottom(hboxBottom);
}

public static void main(String[] args) {
    launch(args);
}

}

edit retag flag offensive close merge delete

Comments

" But my problem is on how to detect the real-time detection of the image captured" -- sorry, but it's unclear, what you mean here. what do you want to detect ?

berak gravatar imageberak ( 2018-05-15 03:36:52 -0600 )edit

I mean your camera detected (real you) when you face the camera...

sniper101 gravatar imagesniper101 ( 2018-05-15 03:45:11 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
0

answered 2018-05-15 03:45:40 -0600

kbarni gravatar image

You are using an image read from the disk. You should read it from the capture device.

....
if (capture.isOpened()) {
   isStart = true;
   Mat image;
   capture.read(image);
   MatOfRect faceDetections = new MatOfRect();
   faceDetector.detectMultiScale(image, faceDetections);
   .....
}
edit flag offensive delete link more

Comments

This is the error sir @kbarni

Detected 0 faces
Writing faceDetection.png
Detected 0 faces
Writing faceDetection.png
Detected 0 faces
Writing faceDetection.png
Detected 0 faces
Writing faceDetection.png
Detected 0 faces
Writing faceDetection.png
Detected 0 faces
Writing faceDetection.png
Detected 0 faces
Writing faceDetection.png
libpng warning: Image width is zero in IHDR
[ INFO:0] Initialize OpenCL runtime...
libpng warning: Image height is zero in IHDR
libpng error: Invalid IHDR data
sniper101 gravatar imagesniper101 ( 2018-05-15 04:09:18 -0600 )edit

Do you get images from the webcam? Just check the image.empty() and then display the image without any processing.

That's the way programming works: write a basic code (image capture from webcam), check if it works, then add the additional features (face detection).

kbarni gravatar imagekbarni ( 2018-05-15 08:50:34 -0600 )edit

Yes, I got an image from the webcam. The camera captured but there is no detection happen. Maybe you're right no processing at all. I think that the camera capture the image first and then save it to the disk and that captured image will determine the real you (detection happens) once you face to the camera. I'm working on this very intuitively because I'm new to Java Programming... By the way, Thank you so much @kbarni for the advice. Very much appreciated...God bless...

sniper101 gravatar imagesniper101 ( 2018-05-15 09:31:13 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2018-05-15 03:33:14 -0600

Seen: 999 times

Last updated: May 15 '18