BackgroundSubtractionDemo.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import org.opencv.core.Core;
  2. import org.opencv.core.Mat;
  3. import org.opencv.core.Point;
  4. import org.opencv.core.Scalar;
  5. import org.opencv.highgui.HighGui;
  6. import org.opencv.imgproc.Imgproc;
  7. import org.opencv.video.BackgroundSubtractor;
  8. import org.opencv.video.Video;
  9. import org.opencv.videoio.VideoCapture;
  10. import org.opencv.videoio.Videoio;
  11. class BackgroundSubtraction {
  12. public void run(String[] args) {
  13. String input = args.length > 0 ? args[0] : "../data/vtest.avi";
  14. boolean useMOG2 = args.length > 1 ? args[1] == "MOG2" : true;
  15. //! [create]
  16. BackgroundSubtractor backSub;
  17. if (useMOG2) {
  18. backSub = Video.createBackgroundSubtractorMOG2();
  19. } else {
  20. backSub = Video.createBackgroundSubtractorKNN();
  21. }
  22. //! [create]
  23. //! [capture]
  24. VideoCapture capture = new VideoCapture(input);
  25. if (!capture.isOpened()) {
  26. System.err.println("Unable to open: " + input);
  27. System.exit(0);
  28. }
  29. //! [capture]
  30. Mat frame = new Mat(), fgMask = new Mat();
  31. while (true) {
  32. capture.read(frame);
  33. if (frame.empty()) {
  34. break;
  35. }
  36. //! [apply]
  37. // update the background model
  38. backSub.apply(frame, fgMask);
  39. //! [apply]
  40. //! [display_frame_number]
  41. // get the frame number and write it on the current frame
  42. Imgproc.rectangle(frame, new Point(10, 2), new Point(100, 20), new Scalar(255, 255, 255), -1);
  43. String frameNumberString = String.format("%d", (int)capture.get(Videoio.CAP_PROP_POS_FRAMES));
  44. Imgproc.putText(frame, frameNumberString, new Point(15, 15), Core.FONT_HERSHEY_SIMPLEX, 0.5,
  45. new Scalar(0, 0, 0));
  46. //! [display_frame_number]
  47. //! [show]
  48. // show the current frame and the fg masks
  49. HighGui.imshow("Frame", frame);
  50. HighGui.imshow("FG Mask", fgMask);
  51. //! [show]
  52. // get the input from the keyboard
  53. int keyboard = HighGui.waitKey(30);
  54. if (keyboard == 'q' || keyboard == 27) {
  55. break;
  56. }
  57. }
  58. HighGui.waitKey();
  59. System.exit(0);
  60. }
  61. }
  62. public class BackgroundSubtractionDemo {
  63. public static void main(String[] args) {
  64. // Load the native OpenCV library
  65. System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  66. new BackgroundSubtraction().run(args);
  67. }
  68. }