document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Fri Dec 19 21:17:45 2014
  4. ' code based on snippets and ideas taken from
  5. http://docs.opencv.org/index.html and stackoverflow.com
  6. """
  7.  
  8. import numpy as np
  9. import cv2
  10.  
  11. # Threshold the HSV image to get only selected colour
  12. # Actual values selected after using the calibration program
  13. hmin, hmax = (75, 139)
  14. smin, smax = (44, 255)
  15. vmin, vmax = (104, 255)
  16. lower_thr = np.array([hmin, smin, vmin], dtype=np.uint8)
  17. upper_thr = np.array([hmax,smax,vmax], dtype=np.uint8)
  18.  
  19. # Create window and start webcam
  20. cv2.namedWindow('Laser')
  21. webcam = cv2.VideoCapture(0)
  22. webcam.grab()
  23.  
  24. kernel = np.ones((4,4),np.uint8)
  25.  
  26. # Select colour of the laser sword
  27. #sword_color = (255,0,0) #Blue
  28. sword_color = (0,255,0) #Green
  29. #sword_color = (0,0,255) #Red
  30.  
  31. while(True):
  32.  
  33.  
  34. try:
  35. ret, frame = webcam.retrieve(channel=0)
  36. #Convert to HSV and create a mask based on the selected threshold values
  37. image_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
  38. mask = cv2.inRange(image_hsv, lower_thr, upper_thr)
  39.  
  40. #Opening is the same as erosion and dilation. Plus dilation again for good measure :-)
  41. opening = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
  42. dilation = cv2.dilate(opening,kernel,iterations = 1)
  43.  
  44. # Change the pixels in the original frame and show in the window
  45. frame[zip(np.nonzero(dilation))] = sword_color
  46. cv2.imshow('Laser', frame)
  47.  
  48. #WaitKey is an important part of OpenCV. many people feel they don't
  49. #need to wait for a keystroke and omit it, but the GUI won't run
  50. #without it and your window will never show up. Found this the hard way...
  51. if cv2.waitKey(5)==27:
  52. break
  53. except:
  54. print 'error'
  55. break
  56.  
  57. webcam.release()
  58. cv2.destroyAllWindows()
');