# -*- coding: utf-8 -*-
"""
Created on Fri Dec 19 21:17:45 2014
' code based on snippets and ideas taken from
http://docs.opencv.org/index.html and stackoverflow.com
"""
import numpy as np
import cv2
# Threshold the HSV image to get only selected colour
# Actual values selected after using the calibration program
hmin, hmax = (75, 139)
smin, smax = (44, 255)
vmin, vmax = (104, 255)
lower_thr = np.array([hmin, smin, vmin], dtype=np.uint8)
upper_thr = np.array([hmax,smax,vmax], dtype=np.uint8)
# Create window and start webcam
cv2.namedWindow('Laser')
webcam = cv2.VideoCapture(0)
webcam.grab()
kernel = np.ones((4,4),np.uint8)
# Select colour of the laser sword
#sword_color = (255,0,0) #Blue
sword_color = (0,255,0) #Green
#sword_color = (0,0,255) #Red
while(True):
try:
ret, frame = webcam.retrieve(channel=0)
#Convert to HSV and create a mask based on the selected threshold values
image_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(image_hsv, lower_thr, upper_thr)
#Opening is the same as erosion and dilation. Plus dilation again for good measure :-)
opening = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
dilation = cv2.dilate(opening,kernel,iterations = 1)
# Change the pixels in the original frame and show in the window
frame[zip(np.nonzero(dilation))] = sword_color
cv2.imshow('Laser', frame)
#WaitKey is an important part of OpenCV. many people feel they don't
#need to wait for a keystroke and omit it, but the GUI won't run
#without it and your window will never show up. Found this the hard way...
if cv2.waitKey(5)==27:
break
except:
print 'error'
break
webcam.release()
cv2.destroyAllWindows()