Invisibility_Cloak.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include "opencv2/opencv.hpp"
  2. #include "opencv2/imgproc/imgproc.hpp"
  3. #include "opencv2/highgui/highgui.hpp"
  4. #include <iostream>
  5. using namespace std;
  6. using namespace cv;
  7. const char* keys = "{ video | | Path to the input video file. Skip this argument to capture frames from a camera.}";
  8. int main(int argc, char** argv){
  9. // Parse command line arguments
  10. CommandLineParser parser(argc,argv,keys);
  11. // Create a VideoCapture object and open the input file
  12. VideoCapture cap;
  13. if (parser.has("video")){
  14. cap.open(parser.get<String>("video"));
  15. }
  16. else
  17. cap.open(0);
  18. // Check if camera opened successfully
  19. if(!cap.isOpened()){
  20. cout << "Error opening video stream or file" << endl;
  21. return -1;
  22. }
  23. Mat background;
  24. for(int i=0;i<60;i++)
  25. {
  26. cap >> background;
  27. }
  28. //flip(background,background,1);
  29. while(1)
  30. {
  31. Mat frame;
  32. // Capture frame-by-frame
  33. cap >> frame;
  34. // If the frame is empty, break immediately
  35. if (frame.empty())
  36. break;
  37. Mat hsv;
  38. //flip(frame,frame,1);
  39. cvtColor(frame, hsv, COLOR_BGR2HSV);
  40. Mat mask1,mask2;
  41. inRange(hsv, Scalar(0, 120, 70), Scalar(10, 255, 255), mask1);
  42. inRange(hsv, Scalar(170, 120, 70), Scalar(180, 255, 255), mask2);
  43. mask1 = mask1 + mask2;
  44. Mat kernel = Mat::ones(3,3, CV_32F);
  45. morphologyEx(mask1,mask1,cv::MORPH_OPEN,kernel);
  46. morphologyEx(mask1,mask1,cv::MORPH_DILATE,kernel);
  47. bitwise_not(mask1,mask2);
  48. Mat res1, res2, final_output;
  49. bitwise_and(frame,frame,res1,mask2);
  50. bitwise_and(background,background,res2,mask1);
  51. addWeighted(res1,1,res2,1,0,final_output);
  52. imshow("Magic !!!",final_output);
  53. // Display the resulting frame
  54. //imshow( "Frame", frame );
  55. // Press ESC on keyboard to exit
  56. char c=(char)waitKey(25);
  57. if(c==27)
  58. break;
  59. // Also relese all the mat created in the code to avoid memory leakage.
  60. frame.release(),hsv.release(),mask1.release(),mask2.release(),res1.release(),res2.release(),final_output.release();
  61. }
  62. // When everything done, release the video capture object
  63. cap.release();
  64. // Closes all the frames
  65. destroyAllWindows();
  66. return 0;
  67. }