def __init__(self,ori_dataset): self.col = [] self.ld = ori_dataset self.dataset = ori_dataset.dataset self.ins = Inspection(self.dataset) self.head = ori_dataset.head self.label = self.ld.get_value(self.dataset,-1)
def __init__(self): threading.Thread.__init__(self) self.setting_json = gParam.Setting_Json self.videosplit_path = gParam.VideoSplit_Path self.face_path = gParam.Face_Path self.face_db = gParam.FaceDB_Path self.faceclipxml_path = gParam.FaceClipXml_Path # 以下这3个数据在一次StartIdentify事件或Sync之后要全部更新 # face_datas中保存数据库中所有员工的信息列表,包括人脸特征 # self.face_datas = features_abstract() # face_datas_flags是用来看有没有多次识别 # self.face_datas_flags = [0]*len(self.face_datas) # person_num保存识别出员工的工号 self.person_num = [] # 本次识别的各种设定 self.time_limit = 5 self.period = 1 self.TaskID = 'TaskID' self.PersonCount = 1 self.rq = redis.Redis(host='127.0.0.1', port=6379) # 下面的是之前写的,应该不起作用 with open(gParam.Client_Server_Cfg, 'r') as f: configuration = json.loads(f.read()) # print('客户端与服务端TCP连接配置如下', configuration) self.ins = Inspection(configuration['REDIS_HOST'])
def __init__(self, ori_dataset, max_depth): self.col = [] self.max_depth = max_depth self.dataset = ori_dataset self.ld = LoadData() self.ins = Inspection(ori_dataset)
def __init__(self,col_index_used,col_index_touse, dataset, head, left = None, right = None, depth=0): self.left = left self.right = right self.message = '' self.col_index_touse = col_index_touse self.col_index_used = col_index_used self.attribute = head[col_index_used] # the attribute to divide self.dataset = dataset # the dataset divided by attribute self.depth = depth # current depth of the node self.ld = LoadData() self.ins = Inspection(self.dataset) self.result = self.ins.majority_vote(dataset) # majority_vote for each node
def get_inspections(): inspections = [] with open("data.csv") as file: reader = csv.reader(file, delimiter=",") # Skip header. next(reader) for index, line in enumerate(reader): inspections.append( Inspection( restaurant_id=line[0], restaurant_name=line[1], borough=line[2], zipcode=line[5], cusine=line[7], inspection_date=line[8], violation_code=line[10], violation_description=line[11], score=line[13], grade=line[14], grade_date=line[15], ), ) return inspections
def register_option(function): if Inspection.find_calling_module() == '__main__': added_option = self._get_option_from_args(args, kwargs) if not hasattr(function, Application.OPTIONS_ATTR): new_group = options.new_group('For command %s' % function.__name__) setattr(function, Application.OPTIONS_ATTR, new_group) getattr(function, Application.OPTIONS_ATTR).prepend_option(added_option) return function
def main(self): """ If called from __main__ module, run script's main() method with arguments passed and global options parsed. """ main_module = Inspection.find_calling_module() if main_module != '__main__': # only support if __name__ == '__main__' return # Pull in modules in twitter.common.app.modules if not self._import_module('twitter.common.app.modules'): print >> sys.stderr, 'Unable to import twitter app modules!' sys.exit(1) # defer init as long as possible. self.init() self._commands[None] = Inspection.find_main_from_caller() main_method = self._commands[self._command] if main_method is None: commands = sorted(self.get_commands()) if commands: print >> sys.stderr, 'Must supply one of the following commands:', ', '.join(commands) else: print >> sys.stderr, 'No main() or command defined! Application must define one of these.' sys.exit(1) try: argspec = inspect.getargspec(main_method) except TypeError as e: print >> sys.stderr, 'Malformed main(): %s' % e sys.exit(1) if len(argspec.args) == 1: args = [self._argv] elif len(argspec.args) == 2: args = [self._argv, self._option_values] else: if len(self._argv) != 0: print >> sys.stderr, 'main() takes no arguments but got leftover arguments: %s!' % ( ' '.join(self._argv)) sys.exit(1) args = [] rc = self._run_main(main_method, *args) self.quit(rc)
def _main(): """ If called from __main__ module, run script's main() method. """ main_method, main_module = Inspection._find_main_from_caller(), Inspection._find_main_module() if main_module != '__main__': # only support if __name__ == '__main__' return if main_method is None: print >> sys.stderr, 'No main() defined! Application must define main function.' sys.exit(1) Methods._run_registry() try: argspec = inspect.getargspec(main_method) except TypeError, e: print >> sys.stderr, 'Malformed main(): %s' % e sys.exit(1)
def command(self, function): """ Decorator to turn a function into an application command. """ if Inspection.find_calling_module() == '__main__': func_name = function.__name__ if func_name in self._commands: raise Application.Error('Found two definitions for command %s' % func_name) self._commands[func_name] = function return function
def name(self): """ Return the name of the application. If set_name was never explicitly called, the application framework will attempt to autodetect the name of the application based upon the location of __main__. """ if self._name is not None: return self._name else: return Inspection.find_application_name()
def _main(): """ If called from __main__ module, run script's main() method. """ main_method, main_module = Inspection._find_main_from_caller( ), Inspection._find_main_module() if main_module != '__main__': # only support if __name__ == '__main__' return if main_method is None: print >> sys.stderr, 'No main() defined! Application must define main function.' sys.exit(1) Methods._run_registry() try: argspec = inspect.getargspec(main_method) except TypeError, e: print >> sys.stderr, 'Malformed main(): %s' % e sys.exit(1)
def default_command(self, function): """ Decorator to make a command default. """ if Inspection.find_calling_module() == '__main__': if None in self._commands: defaults = (self._commands[None].__name__, function.__name__) raise Application.Error('Found two default commands: %s and %s' % defaults) self._commands[None] = function return function
def add_option(self, *args, **kwargs): """ Add an option to the application. You may pass either an Option object from the optparse/options module, or pass the *args/**kwargs necessary to construct an Option. """ self._raise_if_initialized("Cannot call add_option() after main()!") calling_module = Inspection.find_calling_module() added_option = self._get_option_from_args(args, kwargs) self._add_option(calling_module, added_option)
def __init__(self): super(WorkspaceView, self).__init__() self._main_layout = QtGui.QVBoxLayout(self) self._main_layout.setSpacing(10) self._grid_layout = QtGui.QGridLayout() # Init widgets self.project_lb = QtGui.QLabel() self._main_layout.addWidget(self.project_lb) self.listbox = ListBox( self._main_layout, Inspection.get_inspection_types() ) self.listbox.setSelectionMode(QtGui.QAbstractItemView.SingleSelection) self.meas_btn = QtGui.QPushButton('Measure') self.doc_btn = QtGui.QPushButton('Document') self.compare_btn = QtGui.QPushButton('Compare') self._meas_stat_lb = QtGui.QLabel() self._doc_stat_lb = QtGui.QLabel() self._compare_stat_lb = QtGui.QLabel() self._meas_stat_lb.setAlignment(QtCore.Qt.AlignCenter) self._doc_stat_lb.setAlignment(QtCore.Qt.AlignCenter) self._compare_stat_lb.setAlignment(QtCore.Qt.AlignCenter) # Add widgets to layout self._grid_layout.addWidget(self.meas_btn, 0, 0) self._grid_layout.addWidget(self._meas_stat_lb, 1, 0) self._grid_layout.addWidget(self.doc_btn, 0, 1) self._grid_layout.addWidget(self._doc_stat_lb, 1, 1) self._grid_layout.addWidget(self.compare_btn, 0, 2) self._grid_layout.addWidget(self._compare_stat_lb, 1, 2) self._main_layout.addLayout(self._grid_layout) self._main_layout.addItem(Spacer()) self.btns = QtGui.QDialogButtonBox() self.btns.addButton('OK', QtGui.QDialogButtonBox.AcceptRole) self.btns.addButton('Back', QtGui.QDialogButtonBox.HelpRole) self._main_layout.addWidget(self.btns) # Map processes to status labels self._status_map = { 'Measure': self._meas_stat_lb, 'Document': self._doc_stat_lb, 'Compare': self._compare_stat_lb }
v_cap.video = '1.mp4' t_helmet.start() v_cap.start() f_dectect.start() setdefaulttimeout(10) pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_respomses=True) r = redis.Redis(connection_pool=pool) ADDR = ('23.88.228.11', 43967) tctimeClient = socket(AF_INET, SOCK_STREAM) tctimeClient.connect(ADDR) BUFFSIZE = 20480000 ins = Inspection('127.0.0.1') def main(): event = Event(e_smoking=True) event.TaskID = '4396' event.start() t_send = NewThread('Event', '4396', 4, tctimeClient) v_cap.video_path = gParam.Video_Path v_cap.video = 'smoking.mp4' setting(status='run', writing=True) setting(address=gParam.Event_Setting_Json, status='run', writing=True) t_send.start()
print('客户端与服务端TCP连接配置如下', configuration) # redis 连接池 pool = redis.ConnectionPool(host=configuration['REDIS_HOST'], port=6379, decode_responses=True) r = redis.Redis(connection_pool=pool) # 与服务端连接的配置 ADDR = (configuration['IP'], configuration['PORT']) tctimeClient = socket(AF_INET, SOCK_STREAM) tctimeClient.bind((configuration['LOCAL_IP'], 5678)) tctimeClient.connect(ADDR) BUFFSIZE = configuration['BUFFSIZE'] ins = Inspection(configuration['REDIS_HOST']) def heartbeat(): """心跳检测函数,根据configuration.txt中设置的间隔时间固定发出心跳检测,确认连接情况 """ while True: try: print('===============heartbeat start============') print('heart jinru 1') heartbeat = ins.register() tctimeClient.send(heartbeat.encode()) print('done') ret_data = tctimeClient.recv(BUFFSIZE).decode() print('rt_register', ret_data) # tctimeClient.close()
class DecisionTree(): def __init__(self, ori_dataset, max_depth): self.col = [] self.max_depth = max_depth self.dataset = ori_dataset self.ld = LoadData() self.ins = Inspection(ori_dataset) # divide the dataset with certain attribute def divide_dataset(self, dataset, col_index): label = self.ld.get_value(dataset, col_index) dataset0 = [] dataset1 = [] for row in dataset: if row[col_index] == label[0]: dataset0.append(row) else: dataset1.append(row) dataset0 = np.array(dataset0) dataset1 = np.array(dataset1) return dataset0, dataset1 # calculate the gini impurity given attribute def gini_impurity(self, dataset, col_index=-1): if col_index == -1: gi = self.ins.gini_impurity(dataset) else: # print('dataset:\n', dataset) # print('col index:',col_index) ds = self.divide_dataset(dataset, col_index) # print('ds0:\n',ds[0]) # print('ds1:\n', ds[1]) gi_left = self.ins.gini_impurity(ds[0]) gi_right = self.ins.gini_impurity(ds[1]) gi = (len(ds[0]) / len(dataset)) * gi_left + ( len(ds[1]) / len(dataset)) * gi_right return gi # calculate the gini gain given attribute def gini_gain(self, dataset, col_index): ori_gi = self.gini_impurity(dataset) new_gi = self.gini_impurity(dataset, col_index) gg = ori_gi - new_gi return gg def get_attribute(self, dataset, used_col): gg_arr = {} col_arr = [i for i in range(len(dataset[0]) - 1)] for item in list(set(col_arr).difference(set(used_col))): gg_arr[item] = self.gini_gain(dataset, item) col_index = max(gg_arr, key=gg_arr.get) return col_index # 记录下路径,再进行搞 def construct(self, dataset, col_index=-1, depth=0): # print('\nlen:',len(dataset)) # print(dataset) # print('used_col:',self.col) # print('depth:', depth) # reach the max depth if depth > self.max_depth: print('depth reach max depth') # self.col.pop(col_index) return None # after divide the dataset is empty elif len(dataset) == 0: print('dataset is empty.') # self.col.pop(col_index) return None # No more attribute to divide elif len(dataset[0]) == len(self.col) + 1: # print(self.col) print('all the attributes have been used.') # self.col.pop(col_index) # print(depth) return None # after divide the gini-impurity of dataset is 0 elif self.gini_impurity(dataset) == 0: print('no need to do more division!') # self.col.pop(col_index) return None # recursively construct the left and right node else: col_index = self.get_attribute(dataset, self.col) # construct the current node node = Node(col_index, dataset, depth=depth) self.col.append(col_index) # divide the dataset according to max gini-gain new_dataset = self.divide_dataset(dataset, col_index) depth += 1 #recurse the left branch left_branch = self.construct(new_dataset[0], col_index, depth) node.left = left_branch # self.col.pop(col_index) #recurse the right branch right_branch = self.construct(new_dataset[1], col_index, depth) node.right = right_branch # print('col_index:',col_index) self.col.remove(col_index) return node def traverse(self, node): if node: # print(node.dataset,'\n') print(node.depth, '\t', node.attribute) self.traverse(node.left) self.traverse(node.right)
def name(): if _APP_NAME is not None: return _APP_NAME else: return Inspection._find_main_module()
class DecisionTree(): def __init__(self,ori_dataset): self.col = [] self.ld = ori_dataset self.dataset = ori_dataset.dataset self.ins = Inspection(self.dataset) self.head = ori_dataset.head self.label = self.ld.get_value(self.dataset,-1) # divide the dataset with certain attribute def divide_dataset(self,dataset,col_index): label = self.ld.get_value(dataset,col_index) dataset0 = [] dataset1 = [] for row in dataset: if row[col_index] == label[0]: dataset0.append(row) else: dataset1.append(row) dataset0 = np.array(dataset0) dataset1 = np.array(dataset1) return dataset0,dataset1 # calculate the gini impurity given attribute def gini_impurity(self,dataset,col_index=-1): if col_index==-1: gi = self.ins.gini_impurity(dataset) else: ds = self.divide_dataset(dataset,col_index) gi_left = self.ins.gini_impurity(ds[0]) gi_right = self.ins.gini_impurity(ds[1]) gi = (len(ds[0])/len(dataset))*gi_left+(len(ds[1])/len(dataset))*gi_right return gi # calculate the gini gain given attribute def gini_gain(self,dataset,col_index): ori_gi = self.gini_impurity(dataset) new_gi = self.gini_impurity(dataset,col_index) gg = ori_gi-new_gi return gg def get_attribute(self,dataset,used_col): gg_arr = {} col_arr = [i for i in range(len(dataset[0])-1)] for item in list(set(col_arr).difference(set(used_col))): gg_arr[item] = self.gini_gain(dataset,item) gg_arr = sorted(gg_arr.items(),key=lambda d:d[0], reverse=True) gg_lst = [] gg_index = [] for item in gg_arr: gg_index.append(item[0]) gg_lst.append(item[1]) col_index = gg_index[gg_lst.index(max(gg_lst))] return col_index # construct the decision tree def construct(self,dataset,max_depth, depth=0, col_index=-1): # print('used col: {}'.format(self.col)) # reach the max depth if depth>max_depth-1: # print('depth reach max depth') node = Node(col_index, -1, dataset, self.head, depth=depth) node.message = 'Gini Impurity: {}'.format(self.gini_impurity(dataset)) return node # after divide the dataset is empty elif len(dataset)==0: # print('dataset is empty.') node = Node(col_index, -1, dataset, self.head, depth=depth) node.message = 'Gini Impurity: {}'.format(self.gini_impurity(dataset)) return node # No more attribute to divide elif len(dataset[0])==len(self.col)+1: # print('all the attributes have been used.') node = Node(col_index, -1, dataset, self.head, depth=depth) node.message = 'Gini Impurity: {}'.format(self.gini_impurity(dataset)) return node # after divide the gini-impurity of dataset is 0 elif self.gini_impurity(dataset)==0: # print('no need to do more division!-gini impurity') node = Node(col_index, -1, dataset, self.head, depth=depth) node.message = 'Gini Impurity: {}'.format(self.gini_impurity(dataset)) return node # no more gini-gain for further division elif self.gini_gain(dataset,self.get_attribute(dataset,self.col))==0: # print('no need to do more division!-gini-gain') node = Node(col_index, -1, dataset, self.head, depth=depth) node.message = 'Gini Impurity: {}'.format(self.gini_impurity(dataset)) return node # recursively construct the left and right node else: # construct the current node node = Node(col_index, self.get_attribute(dataset, self.col), dataset, self.head, depth=depth) node.message = 'Gini Impurity: {}'.format(self.gini_impurity(dataset)) col_index = self.get_attribute(dataset, self.col) self.col.append(col_index) # divide the dataset according to max gini-gain new_dataset = self.divide_dataset(dataset,col_index) depth += 1 #recurse the left branch # print('left') left_branch = self.construct(new_dataset[0], max_depth, depth,col_index) node.left = left_branch #recurse the right branch # print('right') right_branch = self.construct(new_dataset[1], max_depth, depth,col_index) node.right = right_branch self.col.remove(col_index) return node # traverse the constructed tree and print the tree def traverse(self,node): if node: result = node.dataset[:,-1] count={self.label[0]:0,self.label[1]:0} for item in result: count[item] += 1 for i in range(node.depth): print('| ',end='') if node.col_index_used != -1: print(node.attribute,'=',node.dataset[0][node.col_index_used],': ',end='') print(count) self.traverse(node.left) self.traverse(node.right) def classify_row(self,row,node,outfile_stream): if node.left==None and node.right==None: outfile_stream.write('{}\n'.format(node.result)) return node.result else: if row[node.col_index_touse] == node.left.dataset[0][node.col_index_touse]: self.classify_row(row, node.left,outfile_stream) elif row[node.col_index_touse] == node.right.dataset[0][node.col_index_touse]: self.classify_row(row, node.right,outfile_stream) def classify(self,dataset,root,outfile): with open(outfile,'w') as f: for row in dataset: self.classify_row(row,root,f) return
class FaceDetect(threading.Thread): """ 从图片中捕捉到人脸,并进行识别 整体的逻辑: 每张截图与数据库中所有人脸比较,得到3个变量 finding,repeating,MatchInfo 根据finding与repeating判断出 找到员工,重复找到员工,无匹配者三种情况并分别处理 当超过规定时间时则发送相应报文,结束识别 attr setting: self.time_limit: 设定时间限制 self.period: 设定多长时间识别一张视频帧 self.TaskID: 设定存入redis缓存的key self.PersonCount: 设定检测现场的人数 """ def __init__(self): threading.Thread.__init__(self) self.setting_json = gParam.Setting_Json self.videosplit_path = gParam.VideoSplit_Path self.face_path = gParam.Face_Path self.face_db = gParam.FaceDB_Path self.faceclipxml_path = gParam.FaceClipXml_Path # 以下这3个数据在一次StartIdentify事件或Sync之后要全部更新 # face_datas中保存数据库中所有员工的信息列表,包括人脸特征 # self.face_datas = features_abstract() # face_datas_flags是用来看有没有多次识别 # self.face_datas_flags = [0]*len(self.face_datas) # person_num保存识别出员工的工号 self.person_num = [] # 本次识别的各种设定 self.time_limit = 5 self.period = 1 self.TaskID = 'TaskID' self.PersonCount = 1 self.rq = redis.Redis(host='127.0.0.1', port=6379) # 下面的是之前写的,应该不起作用 with open(gParam.Client_Server_Cfg, 'r') as f: configuration = json.loads(f.read()) # print('客户端与服务端TCP连接配置如下', configuration) self.ins = Inspection(configuration['REDIS_HOST']) def opencv_clip(self, frame, frame_name, xml): """ args: frame: ndarray, 视频截图 frame_name: 视频截图的绝对地址 xml: str, 存放截取用配置文件 returns: facename_list: list, 存放脸的地址,没有脸则为[] """ face_cascade = cv2.CascadeClassifier(xml) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) facename_list = [] name_time = time.time() if (len(faces) > 0): for ind, (x, y, w, h) in enumerate(faces): img_part = frame[y:y + h, x:x + w] face_name = os.path.join(self.face_path, str(name_time) + str(ind) + '.jpg') cv2.imwrite(face_name, img_part) facename_list.append(face_name) #图片两张人脸的话face长度 一张人脸就长度为1吗? return facename_list def clip_face(self, frame_name): """从一张图片中截取下人脸部分 args: frame_name: str, 视频流截图的绝对地址 returns: facename_list: list, 存放截取的人脸图像的地址列表 """ xml = os.path.join(self.faceclipxml_path, 'haarcascade_frontalface_default.xml') facename_list = [] frame = cv2.imread(frame_name) facename_list = self.opencv_clip(frame, frame_name, xml) return facename_list def feature_compare(self, f1, f2): """ args: f1: list, 存放截取图片的feature f2: list, 存放数据库人脸的feature returns: sum: float, f1与f2的相似度 """ sum = 0 for ind, ele1 in enumerate(f1): ele2 = float(f2[ind]) sum += float(ele1) * ele2 return sum def face_identify(self, facename): """从face_db库中识别人脸 args: facename: string, 存放截取出的人脸的地址 returns: finding: bool, 有没有找到对应者 repeating: bool, 找到的是不是重复者 err_img_path: string, 存放未找到对应员工的图片的位置 MatchInfo: dict, {pic: base64, 识别时的截图 matches:{ matchPic: base64, 照片库中的匹配照片 matchCode: string, matchType: string, matchPercent: int, 相似度 }} """ matches = [] finding = False repeating = False err_img_path = facename # f1, self.face_datas, img_pic三花聚顶 fr = faceRecognize() f1 = fr.get_feature(facename) img_pic = base64_pic(facename) # f1本来是二维的list try: f1 = f1[0] except: # 利用一种不可能出现的逻辑情况做debug return False, True, err_img_path, b'wtx' n = 0 for face_data in self.face_datas: f2 = face_data['feature'] # f2本来是string f2 = eval(f2) matchType = face_data['type'] similar = self.feature_compare(f1, f2) # print(".....................") # print("similarity...........") # print(similar) # 一般来讲一个图片就只会匹配到一个员工,但是也可能出现识别出多个相似度高的情况, # 此时就显示出matches的重要性了 # 由于这里的逻辑完全无法走通,比如我可能匹配到很多人,但是我还要判断识别了多少人,这就是不可能的事情,所以说当有一张脸匹配到多张照片的时候,匹配到的多个身份全部认为到场,添加到person_num中!!!!!!!!!!!!!!!!!!!!!!!!!! if int(similar * 100) >= 60 and self.face_datas_flags[n] == 0: finding = True self.person_num.append(face_data['code']) matchPic = base64_pic(face_data['pic']) match = { 'matchPic': matchPic, 'matchCode': face_data['code'], 'matchType': matchType, 'matchPercent': similar, } matches.append(match) self.face_datas_flags[n] = 1 elif int(similar * 100) >= 60 and self.face_datas_flags[n] != 0: finding = True repeating = True else: pass n += 1 MatchInfo = {'pic': img_pic, 'matches': matches} return finding, repeating, err_img_path, MatchInfo def update(self): """每次识别任务结束后都更新一下 """ self.face_datas = features_abstract() self.face_datas_flags = [0] * len(self.face_datas) self.person_num = [] def detect_face(self): while True: status = {} with open(self.setting_json) as f: status = json.load(f) if status['status'] == 'run' and status[ 'command'] == 'StartIdentify': start_time = time.time() person_count = 0 while True: # print("facedetect-----已经开启") try: """ 取出视频流的最新截图,从中截取人脸,保存人脸文件到gParam.Face_Path """ lists = [] lists = os.listdir(self.videosplit_path) try: lists.sort(key=lambda fn: os.path.getmtime( os.path.join(self.videosplit_path, fn))) # frame_name = os.path.join(self.videosplit_path, lists[-1]) frame_name = os.path.join(self.videosplit_path, "1581607991.216811.jpg") except: frame_name = None print('frame_name = None') facename_list = self.clip_face(frame_name) # time.sleep(0.3) # print('frame_name:', frame_name) # print('facename_list', facename_list) except: print("有错误") for facename in facename_list: finding, repeating, err_img_path, MatchInfo = self.face_identify( facename) # 根据返回信息决定如何发送报文 # 正常找到照片对应员工 if finding == True and repeating == False: rt_data = { 'Command': 'rt_StartIdentify', 'TaskID': self.TaskID, 'Retval': 'OK', 'MatchInfo': json.dumps(MatchInfo) } rt_data = json.dumps(rt_data) if type(rt_data) == str: rt_data = rt_data.encode() self.rq.lpush(self.TaskID, rt_data) time.sleep(1) # 没有找到与图片对应的数据库照片 elif finding == False and repeating == False: reason = { 'ErrorCode': '0002', 'ErrorMessage': 'find unmatched person' } rt_data = { 'Command': 'rt_StartIdentify', 'TaskID': self.TaskID, 'Retval': 'Error', 'Reason': json.dumps(reason), 'DismatchPic': MatchInfo['pic'] } rt_data = json.dumps(rt_data) if type(rt_data) == str: rt_data = rt_data.encode() self.rq.lpush(self.TaskID, rt_data) time.sleep(1) elif finding == False and repeating == True: print('facedetect-----err_img_path---------', err_img_path) else: pass # 判断有没有超时 cur_time = time.time() # print('time-----------------', cur_time-start_time) if cur_time - start_time > self.time_limit: # 发送retval为error的报文,并主动停止 if self.person_num == []: rt_data = self.ins.rt_startidentify( self.TaskID, Retval='Error', Reason='TimeOut') if type(rt_data) == str: rt_data = rt_data.encode() self.rq.lpush(self.TaskID, rt_data) else: errormessage = 'just match ' + str( len(self.person_num)) reason = { 'ErrorCode': '0003', 'ErrorMessage': errormessage } rt_data = { 'Command': 'rt_StartIdentify', 'TaskID': self.TaskID, 'Retval': 'Error', 'Reason': json.dumps(reason) } rt_data = json.dumps(rt_data) if type(rt_data) == str: rt_data = rt_data.encode() self.rq.lpush(self.TaskID, rt_data) print("facedetect-----time out! Stop!") setting(status='stop', command='none', writing=True) with open(self.setting_json) as f: data = json.load(f) if not (data['status'] == 'run' and data['command'] == 'StartIdentify'): print("facedetect-----停止人脸识别") # 将本地文件中的截取的视频流图片删除,节省空间 lists = os.listdir(self.videosplit_path) lists.sort(reverse=True, key=lambda fn: os.path.getmtime( self.videosplit_path + "/" + fn)) try: for i in lists[3:]: os.remove(os.path.join(self.videosplit_path, i)) print("facedetect-----清理冗余文件") except: print("facedetect-----无冗余文件") while self.rq.llen(self.TaskID) > 0: self.rq.rpop(self.TaskID) print('facedetect-----清理redis缓存成功') self.update() break # 现在是根据这里的设定来决定多长时间截取一次人脸 time.sleep(self.period) else: print("facedetect-----未开启人脸识别") time.sleep(3) # break def run(self): self.detect_face()