Invisibility_Cloak.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import cv2
  2. import numpy as np
  3. import time
  4. import argparse
  5. parser = argparse.ArgumentParser()
  6. # Input argument
  7. parser.add_argument("--video", help = "Path to input video file. Skip this argument to capture frames from a camera.")
  8. args = parser.parse_args()
  9. print("""
  10. Harry : Hey !! Would you like to try my invisibility cloak ??
  11. Its awesome !!
  12. Prepare to get invisible .....................
  13. """)
  14. # Creating an VideoCapture object
  15. # This will be used for image acquisition later in the code.
  16. cap = cv2.VideoCapture(args.video if args.video else 0)
  17. # We give some time for the camera to setup
  18. time.sleep(3)
  19. count = 0
  20. background=0
  21. # Capturing and storing the static background frame
  22. for i in range(60):
  23. ret,background = cap.read()
  24. #background = np.flip(background,axis=1)
  25. while(cap.isOpened()):
  26. ret, img = cap.read()
  27. if not ret:
  28. break
  29. count+=1
  30. #img = np.flip(img,axis=1)
  31. # Converting the color space from BGR to HSV
  32. hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
  33. # Generating mask to detect red color
  34. lower_red = np.array([0,120,70])
  35. upper_red = np.array([10,255,255])
  36. mask1 = cv2.inRange(hsv,lower_red,upper_red)
  37. lower_red = np.array([170,120,70])
  38. upper_red = np.array([180,255,255])
  39. mask2 = cv2.inRange(hsv,lower_red,upper_red)
  40. mask1 = mask1+mask2
  41. # Refining the mask corresponding to the detected red color
  42. mask1 = cv2.morphologyEx(mask1, cv2.MORPH_OPEN, np.ones((3,3),np.uint8),iterations=2)
  43. mask1 = cv2.dilate(mask1,np.ones((3,3),np.uint8),iterations = 1)
  44. mask2 = cv2.bitwise_not(mask1)
  45. # Generating the final output
  46. res1 = cv2.bitwise_and(background,background,mask=mask1)
  47. res2 = cv2.bitwise_and(img,img,mask=mask2)
  48. final_output = cv2.addWeighted(res1,1,res2,1,0)
  49. cv2.imshow('Magic !!!',final_output)
  50. k = cv2.waitKey(10)
  51. if k == 27:
  52. break