def viewsinglecam(camname): """Video streaming home page.""" accountid = session.get('userid') print(accountid) dbs = dbops() cm = camname #Get All View List for User camviewlist = dbs.get_camViews(accountid) listview = [] if len(camviewlist) != 0: for camview in camviewlist: listview.append(camview[1]) #List All Cameras camdlist = dbs.get_Camera_list_by_userid(str(accountid)) camname = [] for cam in camdlist: print(cam) camname.append(cam[1].upper()) return render_template('viewsinglecam.html', cameras=camname, camviews=listview, camnm=cm)
def do_enrollment(): fc = facerec() print("doing enrollment") dbs = dbops() img = request.form['image'] print(img) name = request.form['name'] email = request.form['email'] mobile = request.form['mobile'] address = request.form['address'] nationalid = request.form['nationalid'] imgs = str(img).split("image/") imgs = str(img).split(";base64,") print(imgs[1]) imgbase = base64.b64decode(imgs[1]) userid = str(datetime.now().strftime("%d%H%M%S")) rootDir = os.path.dirname(os.path.realpath(__file__)) usersRDir = os.path.join(rootDir, "./img/users") usersDir = os.path.join(usersRDir, str(userid)) if not os.path.exists(usersDir): try: os.makedirs(usersDir) except: print("unable to create directory", usersDir) filename = "user.jpg" imgpath = os.path.join(usersDir, filename) image_result = open(imgpath, 'wb') image_result.write(imgbase) image_result.close() fc.train(name, address, mobile, email, str(userid)) return render_template('enrolluser.html')
def __init__(self, name): self.name = name.upper() dbs = dbops() # create a directory for camera settingdetails = dbs.get_settingsdetails() self.rootpathprimary = settingdetails[0][2] self.rootpathsecondary = settingdetails[0][3] self.rootpathtertiary = settingdetails[0][4]
def __init__(self): self.fileDir = os.path.dirname(os.path.realpath(__file__)) self.modelDir = os.path.join(self.fileDir, 'openface/models') self.dlibModelDir = os.path.join(self.modelDir, 'dlib') self.openfaceModelDir = os.path.join(self.modelDir, 'openface') self.dlibFacePredictor = os.path.join( self.dlibModelDir, "shape_predictor_68_face_landmarks.dat") self.networkModel = os.path.join(self.openfaceModelDir, 'nn4.small2.v1.t7') self.workDir = os.path.join(self.fileDir, 'openface/generated-embeddings') self.WDInputImage = os.path.join(self.fileDir, 'openface/training-images') self.WDAlignedImages = os.path.join(self.fileDir, 'openface/aligned-images') self.WDutils = os.path.join(self.fileDir, 'openface/util') self.WDembeddings = os.path.join(self.fileDir, 'openface/generated-embeddings') self.WDbatchrepresent = os.path.join( self.fileDir, 'openface/batch-represent/main.lua') self.imgDim = 96 self.cuda = False self.verbose = False self.ldaDim = -1 self.classifier = 'LinearSvm' # GridSearchSvm,GMM,RadialSvm,DecisionTree,GaussianNB,DBN self.inferParser = "infer" # Predict who an image contains from a trained classifier. self.classifierModel = os.path.join( self.fileDir, 'openface/generated-embeddings/classifier.pkl') multi = False # -Infer multiple faces in image" self.dbs = dbops() self.mode = "infer" self.face_cascade = cv2.CascadeClassifier( './models/haarcascades/haarcascade_frontalface_default.xml') #self.x = preproc() #start = time.time() if self.verbose: print("Argument parsing and import libraries took {} seconds.". format(time.time() - self.start)) if self.mode == 'infer' and self.classifierModel.endswith(".t7"): raise Exception( """Use `--networkModel` to set a non-standard Torch network model.""" ) self.align = openface.AlignDlib(self.dlibFacePredictor) self.net = openface.TorchNeuralNet(self.networkModel, imgDim=self.imgDim, cuda=self.cuda) #Open classifier model if os.path.exists(self.classifierModel): with open(self.classifierModel, 'rb') as f: if sys.version_info[0] < 3: (self.le, self.clf) = pickle.load(f) else: (self.le, self.clf) = pickle.load(f, encoding='latin1')
def __init__(self): self.face_cascade = cv2.CascadeClassifier('./models/haarcascades/haarcascade_frontalface_default.xml') self.firsttime=True if os.path.isfile("./models/gini/trainingData.yml"): #self.recognizer.load("./models/gini/trainingData.yml") self.firsttime=False #self.recognizer.setThreshold(100) self.font= cv2.FONT_HERSHEY_SIMPLEX self.dbaction=dbops()
def __init__(self,parent=None): super( MyApp_AddCamera, self).__init__(parent) self.dbs = dbops() # Set up the user interface from Designer. self.ui = Ui_AddCamera() self.ui.setupUi(self) self.ui.save.clicked.connect(self.savecamera) self.ui.cancel.clicked.connect(self.closecamera) self.ui.record.clicked.connect(self.testcamera)
def __init__(self): self.face_cascade = cv2.CascadeClassifier('./models/haarcascades/haarcascade_frontalface_default.xml') self.recognizer=cv2.face.createLBPHFaceRecognizer() self.recognizer_local=cv2.face.createLBPHFaceRecognizer() self.firsttime=True if os.path.isfile("./models/gini/trainingData.yml"): self.recognizer.load("./models/gini/trainingData.yml") self.firsttime=False self.font= cv2.FONT_HERSHEY_SIMPLEX self.dbaction=dbops()
def viewshared(): """Video streaming home page.""" accountid = session.get('userid') print(accountid) dbs = dbops() camdlistshared = dbs.get_Camera_list_sharedtome(str(accountid)) camnameshared = [] for cam in camdlistshared: print(cam[1]) camnameshared.append(cam[1]) return render_template('viewcamshared.html', sharedcameras=camnameshared)
def __init__(self,parent=None): super( MyApp_trackuser, self).__init__(parent) # Set up the user interface from Designer. self.dbs = dbops() self.ui = Ui_trackuser() self.ui.setupUi(self) self.ui.record.setVisible(False) self.ui.record.clicked.connect(self.selectimage) self.ui.save.clicked.connect(self.savetracker) self.ui.cancel.clicked.connect(self.canceltracker) self.ui.recorduser.clicked.connect(self.recordimages)
def addview(): """Video streaming home page.""" accountid = session.get('userid') print(accountid) dbs = dbops() camdlist = dbs.get_Camera_list_by_userid(str(accountid)) camname = [] for cam in camdlist: print(cam[1]) camname.append(cam[1].upper()) return render_template('addviews.html', cameras=camname)
def __init__(self,parent=None): super( MyApp_ViewCamera, self).__init__(parent) # Set up the user interface from Designer. self.ui = Ui_ViewCamera() self.ui.setupUi(self) self.dbs = dbops() camlist=list(self.dbs.get_Camera_list()) names=[] for cam in camlist: names.append(str(cam[1])) print (names) self.ui.viewcameralist.addItems(names) self.ui.View.clicked.connect(self.showvideo)
def run(self): connectport = self.url print (connectport) dbs = dbops() ids = 9 # this is camera id # Getting camera details camdetails = dbs.get_Camera_details(ids) camname = camdetails[0].upper() camid = camdetails[1] camlocation = camdetails[2].upper() cam_type = camdetails[3] Camtype = cam_type # Load Model fileDir = os.path.dirname(os.path.realpath(__file__)) while (True): try: if self.type == "webcam": success, img = self.video.read() elif self.type == "rtsp": success, img = self.video.read() elif self.type == "http": imgResp = urllib.urlopen(connectport) imgNp = np.array(bytearray(imgResp.read()), dtype=np.uint8) img = cv2.imdecode(imgNp, -1) else: # camera.capture(rawCapture, format="bgr") # img = rawCapture.array time.sleep(0.1) # put the image on screen gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.putText(img, "TENSOR LABS BANGALORE", (100, 40), self.font, 0.9, (0, 0, 150)) datefield = "Date:" + str(date.today()) cv2.putText(img, datefield, (700, 40), self.font, 0.6, (0, 0, 150)) cv2.putText(img, camname + ":" + camlocation, (700, 60), self.font, 0.6, (0, 0, 150)) rgbImage = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) convertToQtFormat = QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0], QImage.Format_RGB888) convertToQtFormat = QPixmap.fromImage(convertToQtFormat) p = convertToQtFormat.scaled(self.length, self.height, Qt.KeepAspectRatio) self.changePixmap.emit(p) except: print("unable to get feeds") cv2.destroyAllWindows() return
def savecamview(): accountid = session.get('userid') dbs = dbops() viewname = request.form['name'] cam1id = request.form['cam1'] cam2id = request.form['cam2'] cam3id = request.form['cam3'] cam4id = request.form['cam4'] cam5id = request.form['cam5'] cam6id = request.form['cam6'] try: cam1id = dbs.get_Camera_details_byname(cam1id) cam2id = dbs.get_Camera_details_byname(cam2id) cam3id = dbs.get_Camera_details_byname(cam3id) cam4id = dbs.get_Camera_details_byname(cam4id) cam5id = dbs.get_Camera_details_byname(cam5id) cam6id = dbs.get_Camera_details_byname(cam6id) camid = str(cam1id[4]) + ":" + str(cam2id[4]) + ":" + str( cam3id[4]) + ":" + str(cam4id[4]) + ":" + str( cam5id[4]) + ":" + str(cam6id[4]) dbs.Add_camViews(viewname, camid, accountid) rd = "/camview/" + viewname accountid = session.get('userid') print(accountid) dbs = dbops() camdlist = dbs.get_Camera_list_by_userid(str(accountid)) camname = [] for cam in camdlist: print(cam[1]) camname.append(cam[1].upper()) return render_template('addviews.html', cameras=camname) except Exception as e: print e return render_template("404.html", errormessage=e)
def Track_user(self, img): dbs = dbops() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Show faces faces = self.face_cascade.detectMultiScale(gray, 1.3, 5, minSize=(30, 30)) for (x, y, w, h) in faces: #id = -1 img = cv2.rectangle(img, (x, y), (x + w + 10, y + h + 10), (0, 255, 255), thickness=3) norm_image2 = img[y:y + h, x:x + w] norm_image2 = cv2.resize(norm_image2, (96, 96)) rgb = norm_image2[:, :, ::-1] facelocations = face_recognition.face_locations(rgb, model="cnn") print(facelocations) if facelocations: faceencodes = face_recognition.face_encodings( rgb, facelocations) predictions = self.clf.predict_proba(faceencodes).ravel() maxI = np.argmax(predictions) maxvalue = np.max(predictions) print(predictions) print(maxvalue) print("maxI values are here", maxI) uid = self.le.inverse_transform(maxI) confidence = predictions[maxI] if confidence < 0.95: uid = -1 if maxvalue <= 0.95: uid = -1 else: uid = -1 confidence = 0 print("uid is here", uid) #getting track id's from get_Transactions_id db ids = dbs.get_Transactions_id() print(ids) for r in ids: print(r) if uid == r[0]: print("cam name", self.camname) dbs.update_Transactions(uid, 'Found', 'call', self.camname) return img
def __init__(self,parent=None): super(MyApp, self).__init__(parent) # Set up the user interface from Designer. self.ui = Ui_MainWindow() self.ui.setupUi(self) self.trackuser_obj = MyApp_trackuser() self.addcamera_obj = MyApp_AddCamera() self.viewcamera_obj= MyApp_ViewCamera() self.ui.viewuser.setVisible(False) self.ui.VisitorLog.setVisible(False) self.dbs=dbops() self.ui.trackuser.clicked.connect(self.show_trackuser) self.ui.addcamera.clicked.connect(self.show_addcamera) self.ui.viewcamera.clicked.connect(self.show_viewcamera) self.ui.attendence.clicked.connect(self.generatereport)
def do_trackuser(): fc = facerec() print("doing Track user") dbs = dbops() name = request.form['name'] print(name) email = request.form['email'] print(email) mobile = request.form['mobile'] print(mobile) address = request.form['address'] print(address) nationalid = request.form['nationalid'] print(nationalid) userid = str(datetime.now().strftime("%d%H%M%S")) rootDir = os.path.dirname(os.path.realpath(__file__)) usersRDir = os.path.join(rootDir, "./img/users") usersDir = os.path.join(usersRDir, str(userid)) print(usersDir) if not os.path.exists(usersDir): try: os.makedirs(usersDir) except: print("unable to create directory", usersDir) img = photos.save(request.files['photo']) #Files are copy from the static/img source = './static/img/' dest = './img/users/' + str(userid) files = os.listdir(source) for f in files: shutil.move(source + f, dest) SOURCE = './img/users/' + str(userid) BACKUP = './img/trackusers/' files = os.listdir(SOURCE) for f in files: fpath = SOURCE + "/" + f shutil.copy(fpath, BACKUP) #os.rename(user.jpg,userid +'.jpg' ) dbs.Transactions("null", userid, name, address, email, mobile, nationalid, "Searching", "email", "cam1") fc.train(name, address, mobile, email, str(userid)) return render_template('trackuser.html')
def savesettings(): dbs = dbops() name = request.form['name'] ps = request.form['ps'] ss = request.form['ss'] ts = request.form['ts'] dur = request.form['dur'] try: dbs.save_settings(name, ps, ss, ts, dur) Headings = "Success !!!!" Messages = "Settings Saved successfully" return render_template('404.html', top=Headings, msg=Messages) except Exception as e: print(e) Headings = "Error !!!!" Messages = e return render_template('404.html', top=Headings, msg=Messages)
def camplay(viewname): """Video streaming home page.""" accountid = session.get('userid') print(accountid) dbs = dbops() # Get List of cameras for Views view = dbs.get_camViews_byname(viewname) camname_forview = [] print(view) if len(view) > 0: camids = view[0][2].split(":") for camid in camids: try: camdetails = dbs.get_Camera_details(int(camid)) camname_forview.append(camdetails[0].upper()) except: print("Error in Querying Camera details") #Get All View List for User camviewlist = dbs.get_camViews(accountid) listview = [] if len(camviewlist) != 0: for camview in camviewlist: listview.append(camview[1]) #List All Cameras camdlist = dbs.get_Camera_list_by_userid(str(accountid)) allcamname = [] for cam in camdlist: print(cam) allcamname.append(cam[1].upper()) return render_template('playcam.html', cameras=allcamname, camviews=listview, camlistforviews=camname_forview, NameView=viewname)
def __init__(self, ids, threadid): #CAmera ID to be provided threading.Thread.__init__(self) self.threadID = threadid self.face_cascade = cv2.CascadeClassifier( './models/haarcascades/haarcascade_frontalface_default.xml') #self.recognizer=cv2.face.LBPHFaceRecognizer_create() #self.recognizer.read("./models/gini/trainingData.yml") self.font = cv2.FONT_HERSHEY_SIMPLEX dbs = dbops() #Getting camera details camdetails = dbs.get_Camera_details(ids) self.camname = camdetails[0].upper() camid = camdetails[1] print(camid) self.camlocation = camdetails[2].upper() cam_type = camdetails[3] print(cam_type) self.Camtype = cam_type if self.Camtype == "nonipcam": self.ur = int(camid) self.video = cv2.VideoCapture(self.ur) elif self.Camtype == "ipcam": self.ur = camid self.imgResp = urllib.urlopen(self.ur) #self.imgResp= requests.get(self.ur,stream=True,verify=True) else: #camera = PiCamera() #rawCapture = PiRGBArray(camera) # allow the camera to warmup time.sleep(0.1) self.thread_cancel = False #self.thread=Thread(target=self.run) self.thread.setDaemon(True) self._is_running = True print(self.Camtype + "_camera initialized")
def do_registration(): dbs = dbops() fname = request.form['firstname'] lname = request.form['lastname'] email = request.form['email'] pwd = request.form['password'] #pwd = base64.b64encode(bytes(request.form['password'],"utf-8")) #pwd = base64.b64encode(request.form['password']) active = True adate = str(datetime.datetime.now()) astart = str(datetime.datetime.now()) aend = str(datetime.datetime.now()) try: dbs.createAccount(fname, lname, email, pwd, adate, astart, aend, active) return render_template('login.html') except Exception as e: print(e) return render_template('register.html')
def do_admin_login(): dbs = dbops() email = request.form['email'] print("email_id", email) x = dbs.get_Account_details_byname(str(email)) if len(x) > 0: pwd = x[0][4] print("pwd here", pwd) #pwd=base64.b64decode(x[0][4]).decode("utf-8", "ignore") if request.form['password'] == pwd: session['logged_in'] = True session['user'] = request.form['email'] session['userid'] = x[0][0] user = request.form['email'] return render_template('index.html', usr=user) else: return 'wrong password!' return render_template('login.html') else: return 'wrong password!' return render_template('login.html')
def CamSettings(): dbs = dbops() accountid = session.get('userid') accountid = int(accountid) if request.method == 'POST': f = request.files['file'] filename = f.filename path = './static' f.save(os.path.join(path, filename)) f = path + '/' + filename input_file = open(f, "r+") reader_file = csv.reader(input_file) #data = pd.read_csv(f) #row=data.iloc[1] for r in list(reader_file): print r[0] dbs.Add_Camera(r[0], r[1], r[2], r[3], accountid) data = dbs.get_Camera_list() return render_template('CamSettings.html', result=data) if request.method == 'GET': data = dbs.get_Camera_list() print(data) return render_template('CamSettings.html', result=data)
def trackstatus(): dbs = dbops() data = dbs.get_Transactions() print(data) return render_template("trackstatus.html", result=data)
import pickle from datetime import time,timedelta,date,datetime from imutils.video import WebcamVideoStream ,VideoStream,FileVideoStream from imutils.video import FPS #import pyttsx import imutils import mysql.connector from mysql.connector import Error,MySQLConnection from ginilib.db import dbops import mysql.connector from Functions.Face import facelib from datetime import datetime flib=facelib() dbs=dbops() counter=0 i=0 count=0 fourcc = cv2.VideoWriter_fourcc("M", "J", "P", "G") while (True): if len(os.listdir('./Input')) == 0: print("Directory is empty") #time.sleep(72000)#for 30min in seconds #time.sleep(1) else: print("Directory is not empty") files=os.listdir("./Input")
def run(self): print ("Starting " + self.name) #threadLock.acquire() dbs=dbops() counter = 0 self.trids, self.trname, self.trencodes = dbs.get_Track_user_list() self.yr = str(date.today().strftime("%Y")) self.mn = str(date.today().strftime("%m")) self.dy = str(date.today().strftime("%d")) self.FYear = self.root_hist + "/" + self.yr self.monpath = self.FYear + "/" + self.mn self.dypath = self.monpath + "/" + self.dy self.createdir(self.FYear) self.createdir(self.monpath) self.createdir(self.dypath) self.start = datetime.now().strftime("%Y%m%d%H%M%S") self.delta = timedelta(minutes=10) # - configuration part self.end = datetime.strptime(self.start, "%Y%m%d%H%M%S") + self.delta self.filename = self.dypath + "/" + self.start + ".avi" # Define the codec and create VideoWriter object self.fourcc = cv2.VideoWriter_fourcc("M", "J", "P", "G") self.out = cv2.VideoWriter(self.filename, self.fourcc, 26.0, (320, 240)) #0x00000021 while (True): img=None try: if self.Camtype=="webcam": try: img = self.video.read() except: print("Unable to read " + str(self.camname)) elif self.Camtype == "rtsp": try: img = self.video.read() except: print("Unable to read " + str(self.camname)) elif self.Camtype=="http": try: imgResp = urllib.urlopen(self.ur) imgNp = np.array(bytearray(imgResp.read()),dtype=np.uint8) img = cv2.imdecode(imgNp,-1) except: print("Unable to read "+ str(self.camname)) elif self.Camtype=="pi": #camera.capture(rawCapture, format="bgr") #img = rawCapture.array time.sleep(0.1) # put the image on screen cv2.waitKey(100) if np.all(img == None): print("Image value is empty for : " + self.camname) else: #img = self.facerec(img) # Do the face prediction img=self.Track_user(img) self.fps.update() width = 800 height = 600 img = cv2.resize(img, (width, height)) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.putText(img, "TENSOR LABS - BANGALORE", (int(width / 3.5), 60), self.font, 0.8, (0, 255, 255),thickness=2) datefield = "Date :" + str(date.today().strftime("%d-%m-%Y")) cv2.putText(img, datefield, (width - 180, height-40), self.font, 0.5, (255, 255, 255),thickness=2) cv2.putText(img, self.camname , ((width - 120), 60), self.font, 0.8,(0, 0, 255),thickness=2) # self.out.write(img) # cv2.imshow(camname, img) #Save Live Image saveto = self.root +"/live"+ str(counter) + ".jpg" if counter >= 3: counter = 0 else: counter += 1 #create directory if not exist cv2.imwrite(saveto, img) print(saveto) # Save backup frame = cv2.resize(img, (320, 240)) tod=datetime.now().strftime("%Y%m%d%H%M%S") tod=datetime.strptime(tod, "%Y%m%d%H%M%S") if tod >= self.end: # Reset the directory path self.yr = str(date.today().strftime("%Y")) self.mn = str(date.today().strftime("%m")) self.dy = str(date.today().strftime("%d")) self.FYear = self.root_hist + "/" + self.yr self.monpath = self.FYear + "/" + self.mn self.dypath = self.monpath + "/" + self.dy self.createdir(self.FYear) self.createdir(self.monpath) self.createdir(self.dypath) self.start = datetime.now().strftime("%Y%m%d%H%M%S") self.end = datetime.strptime(self.start, "%Y%m%d%H%M%S") + self.delta self.filename = self.dypath + "/" +self.start + ".avi" print ("creating file") print(self.filename) self.out.write(frame) self.out.release() self.out = cv2.VideoWriter(self.filename, self.fourcc, 26.0, (320, 240)) #0x00000021 else: self.out.write(frame) #Save Backup ends here key = cv2.waitKey(1) & 0xFF if key == ord("q"): break self.fps.stop() except ThreadError: print(ThreadError) self.thread_cancelled = True print("exiting")
def searchvideo(): dbs = dbops() accountid = session.get('userid') userpath = "static/videos/" + str(accountid) fileDir = os.path.dirname(os.path.realpath(__file__)) newpath = os.path.join(fileDir, userpath) if os.path.exists(newpath): shutil.rmtree(newpath) #Get Details from screen settingdatails = dbs.get_settingsdetails() sdate = request.form['sdate'] stime = request.form['stime'] etime = request.form['etime'] viewname = request.form['viewname'] sdate = datetime.datetime.strptime(sdate, "%Y-%m-%d") year = str(sdate.strftime("%Y")) month = str(sdate.strftime("%m")) day = str(sdate.strftime("%d")) stime = stime.replace(":", "") etime = etime.replace(":", "") #Generate Paths for video startrange = int(year + month + day + stime + "00") endrange = int(year + month + day + etime + "00") rootpathprimary = settingdatails[0][2] rootpathsecondary = settingdatails[0][3] rootpathtertiary = settingdatails[0][4] camviewlist = dbs.get_camViews(accountid) listview = [] if len(camviewlist) != 0: for camview in camviewlist: listview.append(camview[1]) # Get List of cameras for Views view = dbs.get_camViews_byname(viewname) print(view) camids = view[0][2].split(":") camname_forview = [] video_forview = [] for camid in camids: try: camdetails = dbs.get_Camera_details(int(camid)) camname = camdetails[0].upper() camname_forview.append(camname) videoroot_primary = rootpathprimary + "/videos/" + camname + "/hist/" + str( year) + "/" + str(month) + "/" + str(day) videoroot_sec = rootpathsecondary + "/videos/" + camname + "/hist/" + str( year) + "/" + str(month) + "/" + str(day) videoroot_ter = rootpathtertiary + "/videos/" + camname + "/hist/" + str( year) + "/" + str(month) + "/" + str(day) if os.path.exists(videoroot_primary): videoroot = videoroot_primary elif os.path.exists(videoroot_sec): videoroot = videoroot_sec elif os.path.exists(videoroot_ter): videoroot = videoroot_ter generatevideos(camname, videoroot, startrange, endrange) finalvideo = "/static/videos/" + str(accountid) + "/" + str( startrange) + "/" + camname + "/" + "show.mp4" video_forview.append(finalvideo) except Exception as e: print(e) print("Error in Querying Camera details") #Create tempvideo for display return render_template('playcam.html', cameras=camname, camviews=listview, camlistforviews=camname_forview, videolist=video_forview, NameView=viewname)
def __init__(self, camid,camname,camlocation,cam_type,threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter # Getting camera details self.camname = camname self.camid = camid self.camlocation = camlocation cam_type = cam_type self.face_cascade = cv2.CascadeClassifier('./models/haarcascades/haarcascade_frontalface_default.xml') self.font= cv2.FONT_HERSHEY_SIMPLEX self.fileDir = os.path.dirname(os.path.realpath(__file__)) self.unknownusers_dir = os.path.join(self.fileDir, "img/unknownusers") self.classifierModel = os.path.join(self.fileDir, 'ginilib/openface/generated-embeddings/classifier.pkl') if os.path.exists(self.classifierModel): with open(self.classifierModel, 'rb') as f: if sys.version_info[0] < 3: (self.le, self.clf) = pickle.load(f) else: (self.le, self.clf) = pickle.load(f, encoding='latin1') dbs=dbops() # create a directory for camera settingdetails = dbs.get_settingsdetails() rootpathprimary = settingdetails[0][2] rootpathsecondary = settingdetails[0][3] rootpathtertiary = settingdetails[0][4] if os.path.exists(rootpathprimary): pvideoroot = rootpathprimary else: self.createdir(rootpathprimary) pvideoroot = rootpathprimary if os.path.exists(rootpathsecondary): svideoroot = rootpathsecondary else: self.createdir(rootpathsecondary) svideoroot = rootpathsecondary if os.path.exists(rootpathtertiary): tvideoroot = rootpathtertiary else: self.createdir(rootpathtertiary) tvideoroot = rootpathtertiary camdir = pvideoroot+"/videos/" + camname self.base = pvideoroot+"/videos/" self.root = self.base + camname + "/live" self.root_hist = self.base + camname + "/hist" self.createdir(camdir) self.createdir(self.base) self.createdir(self.root) self.createdir(self.root_hist) framerate = 18.0 self.fps = FPS().start() self.Camtype=cam_type if self.Camtype=="webcam": try: ur =int(self.camid) self.video = WebcamVideoStream(src=ur).start() except Exception as e: print(e) print("Unable to open",camname) elif self.Camtype == "rtsp": try: ur = self.camid self.video = VideoStream(ur).start() except Exception as e: # print(e) print("Unable to open", camname) elif self.Camtype=="http": try: self.ur = camid self.imgResp = urllib.request(self.ur) # self.imgResp= requests.get(self.ur,stream=True,verify=True) except Exception as e: #print(e) print("Unable to open",camname) elif self.Camtype=="pi": try: # camera = PiCamera() # rawCapture = PiRGBArray(camera) # allow the camera to warmup time.sleep(0.1) except Exception as e: #print(e) print("Unable to open",camname)
def __init__(self,name): self.name=name.upper() dbs = dbops()
def run(self): connectport=self.url print (connectport) dbs = dbops() ids = 11 # this is camera id # Getting camera details camdetails = dbs.get_Camera_details(ids) camname = camdetails[0].upper() camid = camdetails[1] camlocation = camdetails[2].upper() cam_type = camdetails[3] Camtype = cam_type # Load Model fileDir = os.path.dirname(os.path.realpath(__file__)) unknownusers_dir = os.path.join(fileDir, "img/unknownusers/tmp") if not os.path.exists(unknownusers_dir): try: os.makedirs(unknownusers_dir) except: print ("unable to create directory") root = "./videos/" + camname + "/live" counter = 0 samplenum = 0 files = [] readframe=False #Left to Right while counter<=20: try: if self.type == "webcam": success, img = self.video.read() elif self.type == "rtsp": success, img = self.video.read() elif self.type == "http": imgResp = urllib.urlopen(connectport) imgNp = np.array(bytearray(imgResp.read()), dtype=np.uint8) img = cv2.imdecode(imgNp, -1) else: # camera.capture(rawCapture, format="bgr") # img = rawCapture.array time.sleep(0.1) # put the image on screene time.sleep(0.4) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Show faces faces = self.face_cascade.detectMultiScale(gray, 1.3, 5, minSize=(30, 30)) if len(faces)>1: for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w + 10, y + h + 10), (0, 0, 255), 2) cv2.putText(img, "Multiple Faces --Invalid Recording", (x + w + 12, y - 10), self.font, 0.6, 255) else: for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w + 10, y + h + 10), (0, 255, 255), 2) cv2.putText(img, "Recording", (x + w + 12, y - 10), self.font, 0.4, 255) userid = "U" + str(counter) + ".jpg" saveunknownto = os.path.join(unknownusers_dir, userid) cv2.imwrite(saveunknownto, img[y:y + h + 10, x:x + w + 10]) files.append(saveunknownto) counter += 1 rgbImage = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) convertToQtFormat = QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0], QImage.Format_RGB888) convertToQtFormat = QPixmap.fromImage(convertToQtFormat) p = convertToQtFormat.scaled(self.length, self.height, Qt.KeepAspectRatio) self.changePixmap.emit(p) except: print("unable to get feeds") cv2.destroyAllWindows() self.video.release() return
from ginilib.db import dbops import mysql.connector df = dbops() #################### # for Account table #insert #df.create_Account("manju","Raamanedi","*****@*****.**","manju123","skjdfddhf","manju","8/3/2019","8/3/2019") #delete #df.delete_Account(4) #update #val = "prithviraj" #id = 1 #df.update_Account(id,"firstname",val) # read #a= df.get_Account_details_byname("manjku") #print(a) #print(df.getid()) ############################ # for clients_camera table #insert df.Add_Camera(121, "webcam", 0, "4", "webcam", 5)