
import numpy as np
import cv2
f = open('textfile1.txt', 'w')
f.write('M5\nG90\nG21\n')
f.write('G1 F1000\n')
f.write('G1  X20 Y8\n')


 

def movejog(x,y) :
	f.write('M5\n')
	f.write('G1 F1000\n')
	c='G1  X%f Y%f\n'%(((x/2.5)+20),((y/2.5)+8))
	print c
	f.write(c) 
	f.write('G4 P1\n')
	

def draws(x,y) :
	f.write('M3 S90\n')
	f.write('G1 F500\n')
	c='G1  X%f Y%f\n'%(((x/2.5)+20),((y/2.5)+8))
	print c
	f.write(c) 
	f.write('G4 P1\n')

def algorithm(x0,y0,x1,y1) :
	f.write('M5\n')
	f.write('G1 F1000\n')
	c='G1  X%f Y%f \n'%(((x0/2.5)+20),((y0/2.5)+8))
	print c
	f.write(c) 
	f.write('G4 P1\n')
	f.write('M3 S90\n')
	f.write('G1 F500\n')
	c='G1  X%f Y%f\n'%(((x1/2.5)+20),((y1/2.5)+8))
	print c
	f.write(c) 
	f.write('G4 P1\n')

	
	
cap = cv2.VideoCapture(0)
m=0
w, h = 640, 480;
Matrix = [[0 for x in range(w)] for y in range(h)] 
while(True):
    # Capture frame-by-frame
    ret, img = cap.read()
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #cv2.imshow('frame',img)
    thresh = 127

    
    th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,13,2)
    cv2.imshow('frame6',th2)
    
    
    x, y =  th2.shape
    #print x,y
    
    if m == 10 : 
		print x,y
		i=0
		j=0
		k=0
		m=0
 
		

		
		while i <480 :
			while j<640 :
				print "Matrix [",i,"] [ ",j," = " , th2[i,j]
				#print "i = ", i , " j = " , j 
				Matrix [i][j] = th2[i,j]
				if th2[i,j] > 120 : 
					algorithm(k,m,i,j)
				else : 
					k=i
					m=j
				
				j=j+1
					
			j=0
			i=i+1 
		
		f.close() 
	
	
    m=m+1
    #print m
    img = cv2.threshold(img, thresh, 1027, cv2.THRESH_BINARY)[1]
    # Our operations on the frame come here
    ret,thresh1 = cv2.threshold(img,20,1028,cv2.THRESH_BINARY)
    #cv2.imshow('frame1',thresh1)
    ret,thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
    #cv2.imshow('frame2',thresh2)
    ret,thresh3 = cv2.threshold(img,127,255,cv2.THRESH_TRUNC)
    #cv2.imshow('frame3',thresh3)
    ret,thresh4 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
    #cv2.imshow('frame4',thresh4)
    ret,thresh5 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV)
    #cv2.imshow('frame5',thresh5)
    img = cv2.medianBlur(img,5)
    afterFourier =  np.log (np.abs(np.fft.fft2 (img)))
    afterFourier = afterFourier.astype(np.uint8)
    
    #ret1, th1 = cv2.threshold (afterFourier, 127, 255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY)
    #th2 = cv2.adaptiveThreshold(afterFourier, 255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 1, 1);
    #cv2.imshow('frame5',th2)
    #th3 = cv2.adaptiveThreshold(afterFourier,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,1,1)
    #cv2.imshow('frame5',th3)

    # Display the resulting frame
    #cv2.imshow('frame',img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
