Skip to content

Instantly share code, notes, and snippets.

@abdul-rehman-2050
Created April 19, 2016 03:29
Show Gist options
  • Save abdul-rehman-2050/922024f8fe74fdf8fd830035cdd3eaba to your computer and use it in GitHub Desktop.
Save abdul-rehman-2050/922024f8fe74fdf8fd830035cdd3eaba to your computer and use it in GitHub Desktop.
import numpy as np
import cv2
import cv
import sys
import os
video_capture = cv2.VideoCapture(0)
SZ=20
bin_n = 16 # Number of bins
samples= np.empty((0,2500))
responses=[]
class StatModel(object):
'''parent class - starting point to add abstraction'''
def load(self, fn):
self.model.load(fn)
def save(self, fn):
self.model.save(fn)
class SVM(StatModel):
'''wrapper for OpenCV SimpleVectorMachine algorithm'''
def __init__(self):
self.model = cv2.SVM()
def train(self, samples, responses):
#setting algorithm parameters
params = dict( kernel_type = cv2.SVM_LINEAR,
svm_type = cv2.SVM_C_SVC,
C = 1 )
self.model.train(samples, responses, params = params)
def predict(self, samples):
return np.float32( [self.model.predict(s) for s in samples])
def predict2(self, samples):
return np.float32( self.model.predict(samples))
def hog(img):
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)
mag, ang = cv2.cartToPolar(gx, gy)
# quantizing binvalues in (0...16)
bins = np.int32(bin_n*ang/(2*np.pi))
# Divide to 4 sub-squares
bin_cells = bins[:10,:10], bins[10:,:10], bins[:10,10:], bins[10:,10:]
mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:]
hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)]
hist = np.hstack(hists)
return hist
# keyboard mappings for 0-9; user may type in this range when prompted
keys = [i for i in range(48, 58)]
clf = SVM()
#clf.train(np.asarray(samples,dtype=np.float32), np.asarray(responses,dtype=np.float32))
if __name__ == '__main__':
#global samples
res=[]
dfi=0
while True:
#=============================================================
# Capture frame-by-frame
#--------------------------------------------------------------
ret, frame = video_capture.read()
#===================================
#do all processing Here
#-----------------------------------
#pre processing
#prepare image for motion Detection
#--------------------------------------
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
cv2.rectangle(frame,(300,300),(100,100),(0,255,0),0)
crop_img = frame[100:300, 100:300]
sil_gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)
kernel = (25, 25)
sil_blur = cv2.GaussianBlur(sil_gray, kernel, 0)
_, sil_bin = cv2.threshold(sil_blur, 127, 255,
cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
roi_small=cv2.resize(sil_bin,(50,50))
roi_q = roi_small.reshape((1,2500))
roi_q = np.float32(roi_q)
if dfi>5:
y_val = clf.predict(roi_q)
print y_val
#print y_val
hog_hist=hog(sil_bin)
#print hog_hist
#==============================================
#display area
#----------------------------------------------
cv2.imshow('Video', frame)
cv2.imshow('vid',sil_bin)
#cv2.imshow('hist',hog_hist)
k=cv2.waitKey(1)
if k & 0xFF == ord('q'):
break
elif k in keys:
if hog_hist.any():
sp = hog_hist.reshape(1,64)
samples = np.append(samples,roi_q,0)
responses.append(int(chr(k)))
print samples
dfi=dfi+1
if dfi> 2:
clf.train(np.asarray(samples,dtype=np.float32), np.asarray(responses,dtype=np.float32))
#res = res.append(int(chr(k)))
# responses=responses.append(int(chr(k)))
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
#========================================================================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment