CamshiftDemo.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 Camshift {
  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. // set up the ROI for tracking
  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 camshift to get the new location
  41. RotatedRect rot_rect = Video.CamShift(dst, track_window, term_crit);
  42. // Draw it on image
  43. Point[] points = new Point[4];
  44. rot_rect.points(points);
  45. for (int i = 0; i < 4 ;i++) {
  46. Imgproc.line(frame, points[i], points[(i+1)%4], new Scalar(255, 0, 0),2);
  47. }
  48. HighGui.imshow("img2", frame);
  49. int keyboard = HighGui.waitKey(30);
  50. if (keyboard == 'q'|| keyboard == 27) {
  51. break;
  52. }
  53. }
  54. System.exit(0);
  55. }
  56. }
  57. public class CamshiftDemo {
  58. public static void main(String[] args) {
  59. System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  60. new Camshift().run(args);
  61. }
  62. }