MeanshiftDemo.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import java.util.Arrays;
  2. import org.opencv.core.*;
  3. import org.opencv.highgui.HighGui;
  4. import org.opencv.imgproc.Imgproc;
  5. import org.opencv.video.Video;
  6. import org.opencv.videoio.VideoCapture;
  7. class Meanshift {
  8. public void run(String[] args) {
  9. String filename = args[0];
  10. VideoCapture capture = new VideoCapture(filename);
  11. if (!capture.isOpened()) {
  12. System.out.println("Unable to open file!");
  13. System.exit(-1);
  14. }
  15. Mat frame = new Mat(), hsv_roi = new Mat(), mask = new Mat(), roi;
  16. // take the first frame of the video
  17. capture.read(frame);
  18. //setup initial location of window
  19. Rect track_window = new Rect(300, 200, 100, 50);
  20. // setup initial location of window
  21. roi = new Mat(frame, track_window);
  22. Imgproc.cvtColor(roi, hsv_roi, Imgproc.COLOR_BGR2HSV);
  23. Core.inRange(hsv_roi, new Scalar(0, 60, 32), new Scalar(180, 255, 255), mask);
  24. MatOfFloat range = new MatOfFloat(0, 256);
  25. Mat roi_hist = new Mat();
  26. MatOfInt histSize = new MatOfInt(180);
  27. MatOfInt channels = new MatOfInt(0);
  28. Imgproc.calcHist(Arrays.asList(hsv_roi), channels, mask, roi_hist, histSize, range);
  29. Core.normalize(roi_hist, roi_hist, 0, 255, Core.NORM_MINMAX);
  30. // Setup the termination criteria, either 10 iteration or move by atleast 1 pt
  31. TermCriteria term_crit = new TermCriteria(TermCriteria.EPS | TermCriteria.COUNT, 10, 1);
  32. while (true) {
  33. Mat hsv = new Mat() , dst = new Mat();
  34. capture.read(frame);
  35. if (frame.empty()) {
  36. break;
  37. }
  38. Imgproc.cvtColor(frame, hsv, Imgproc.COLOR_BGR2HSV);
  39. Imgproc.calcBackProject(Arrays.asList(hsv), channels, roi_hist, dst, range, 1);
  40. // apply meanshift to get the new location
  41. Video.meanShift(dst, track_window, term_crit);
  42. // Draw it on image
  43. Imgproc.rectangle(frame, track_window, new Scalar(255, 0, 0), 2);
  44. HighGui.imshow("img2", frame);
  45. int keyboard = HighGui.waitKey(30);
  46. if (keyboard == 'q' || keyboard == 27) {
  47. break;
  48. }
  49. }
  50. System.exit(0);
  51. }
  52. }
  53. public class MeanshiftDemo {
  54. public static void main(String[] args) {
  55. System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  56. new Meanshift().run(args);
  57. }
  58. }