def list_son(id): if not session.get('log_in'): return redirect(url_for('login')) sql = 'select ip1,type from xpp_list where id = %s'%id conn = F.db_get_conn() cursor = conn.cursor() cursor.execute(sql) rez = cursor.fetchone() if rez[1] == 0: sql = 'select ip,status,create_time from xpp_log where ip = "%s" order by create_time desc limit 50'%rez[0] cursor.execute(sql) data = cursor.fetchall() data2 = [] for i in data: t = [] t.append(i[0]) t.append(i[1]) t.append(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(i[2]))) data2.append(t) return render_template('list_son.html',data=data2) elif rez[1] == 1: sql = 'select ip from xpp_list_son where fid = %s'%id n = cursor.execute(sql) if n: data = cursor.fetchall() data2 = [] for i in data: t = [] t.append(i[0]) t.append(F.ip_get_status(i[0])) t.append(u'now') data2.append(t) return render_template('list_son.html',data=data2)
def shtml(txt,file='',browser=True): import T,pprint,F if file=='' and type(txt) is not str: try:file=T.filename(T.max(txt.__str__(),txt.__repr__(),txt.__name__)[:19]) except:pass # if type(txt) in (dict,list): txt=pprint.pformat(txt) # if len(txt)==0:return # s=[] # for i in txt.keys(): # s.append(T.string(i)+' : '+T.string(txt[i])+'\n') # txt=T.listToStr(s) # if len(file)<1:file=T.filename(getObjName(txt)+stime())[:19] if not file.lower().endswith('.txt'):file+='.txt' F.write(file,txt) # f=open(file+'.txt','a') # rm(f.name) # txt=txt.replace(txthtml[1],txthtml[1][:1]+'!!!qgb-padding!!!'+txthtml[1][1:]) # f.write(txthtml[0]) # f.write(txt) # f.write(txthtml[1]) # f.close() if(browser==True):globals()['browser'](path.abspath(file))
def flax(UL, UR, zl, zr, hdt): dmas = np.zeros(2) dmen = dmas g = 9.8 ul = UL[1] / (UL[0] + 1e-8) * (UL[0] >= 1e-3) + 0.0 # La velocidad de la celda UL ur = UR[1] / (UR[0] + 1e-8) * (UR[0] >= 1e-3) + 0.0 # La velocidad de la celda UR alfa0 = hdt alfa1 = 0 # Hallamos entonces D+ y D- en i+1/2 difz = zr - zl vecdifz = [difz, 0] t = g * (UL[0] + UR[0]) * 0.5 * difz vect = [0, t] dmas = 0.5 * alfa0 * (UR - UL + vecdifz) + 0.5 * (1 + alfa1) * ( F.F(UR) - F.F(UL) + vect) dmen = -0.5 * alfa0 * (UR - UL + vecdifz) + 0.5 * (1 - alfa1) * ( F.F(UR) - F.F(UL) + vect) return dmas, dmen
def autof(head,ext=''): '''return str # TODO # ext=?ext* ''' if not py.type(ext)==py.type(head)==py.str or head=='': return '' if len(ext)>0 and not ext.startswith('.'):ext='.'+ext ap='.' if path.isabs(head): ap=F.dir(head) if not F.isExist(ap): if head.endswith(ext):return head else:return head+ext import F ls=F.ls(ap) if head+ext in ls:return head+ext for i in ls: if i.startswith(head) and i.endswith(ext):return i for i in ls: if head in i and ext in i:return i # if inMuti(ext,'*?'):ext=ext.replace('*') if not head.endswith(ext):head+=ext return head
def add(): if not session.get('log_in'): return redirect(url_for('login')) if request.method == 'GET': return render_template('add.html') way = request.form['way'] conn = F.db_get_conn() cursor = conn.cursor() if way == '0': ip = request.form['ip'] sql = 'insert into xpp_list (type,ip1) values (%s,"%s")'%(way,ip) n = cursor.execute(sql) if n: flash(u'添加成功!') conn.commit() cursor.close() conn.close() return render_template('add.html') elif way == '1': start = request.form['start'] end = request.form['end'] sql = 'insert into xpp_list (type,ip1,ip2) values (%s,"%s","%s")'%(way,start,end) n = cursor.execute(sql) fid = cursor.lastrowid if n: for ip in F.gen_ip(start,end): sql = 'insert into xpp_list_son (fid,ip) values (%s,"%s")'%(fid,ip) cursor.execute(sql) conn.commit() cursor.close() conn.close() flash(u'添加成功!') return render_template('add.html')
def detect_ip(data): conn = F.db_get_conn() cursor = conn.cursor() for ip in data: rez = F.ping_host(ip) if rez: sql = 'insert into xpp_log (ip,status,create_time) values ("%s",1,%s)'%(ip,str(time.time())[:10]) else: sql = 'insert into xpp_log (ip,status,create_time) values ("%s",0,%s)'%(ip,str(time.time())[:10]) cursor.execute(sql) conn.commit() cursor.close() conn.close()
def Range_chk_slic(self, T): #sys.path.append("../Multiobjective_Functions") #import F if T == 0: if F.check(self.X, T): return 1 else: return 0 if T == 1: Range = F.check(self.X, T, [Row, Col]) for i in range(len(self.X)): for j in range(len(self.X[0])): self.X[i][j] = max(self.X[i][j], Range[i][j][0]) self.X[i][j] = min(self.X[i][j], Range[i][j][1])
def New(self, T, sigma=1): #sys.path.append("../Multiobjective_Functions") #import F Temp = self.X #print(Temp,self.X) self.X = np.where(self.X > 0, 0.0, 0.0) Range = F.check(self.X, 1, [Row, Col]) for i in range(len(self.X)): for j in range(len(self.X[0])): while 1: if T == 1: self.X[i][j] = random.uniform(Range[i][j][0], Range[i][j][1]) if self.Range_chk_slic(0): break if T == 0: #print(Range,self.X[0]) #sigma1=(Range[i][j][1]-Range[i][j][0])*sigma #print (np.random.normal(0,sigma1)) #print(Range[i][j][1]-Range[i][j][0]) self.X[i][j] = np.random.normal( Temp[i][j], (Range[i][j][1] - Range[i][j][0]) * sigma) if self.Range_chk_slic(0): break #print self.X self.Range_chk_slic(1) '''
def backup(): import F if model.is_first_run(): return has_backup = F.has_backup(model_name, model_path) io.log_info("Backup....", end='\r') loss_src_mean, loss_dst_mean = np.mean([ np.array(loss_history[i]) for i in range(save_iter, iter) ], axis=0) loss_src, loss_dst = loss_history[-1] if has_backup and (iter > 20000 and loss_src_mean > 1 or loss_dst_mean > 1 or loss_src > 1 or loss_dst > 1): if model_name == "SAE" and model.options['archi'] == 'df': F.restore_model(model_name, model_path) weights_to_load = [ [model.encoder, 'encoder.h5'], [model.decoder_src, 'decoder_src.h5'], [model.decoder_dst, 'decoder_dst.h5'], [model.decoder_srcm, 'decoder_srcm.h5'], [model.decoder_dstm, 'decoder_dstm.h5'] ] model.load_weights_safe(weights_to_load) io.log_info("Crash And Try Restore....") if loss_src_mean <= 1 and loss_dst_mean <= 1 and loss_src <= 1 and loss_dst <= 1: F.backup_model_move(model_name, model_path) F.backup_model(model_name, model_path)
def list(): if not session.get('log_in'): return redirect(url_for('login')) conn = F.db_get_conn() cursor = conn.cursor() sql = 'select id,ip1,ip2,type from xpp_list' cursor.execute(sql) data = cursor.fetchall() return render_template('list.html',data=data)
def fast_non_dominated_sort(V1, V2): S = [[] for i in range(0, len(V1))] F = [[]] n = [0 for i in range(0, len(V1))] rank = [0 for i in range(0, len(V1))] for p in range(0, len(V1)): S[p] = [] n[p] = 0 for q in range(0, len(V1)): if (V1[p] > V1[q] and V2[p] > V2[q]) or ( V1[p] >= V1[q] and V2[p] > V2[q]) or (V1[p] > V1[q] and V2[p] >= V2[q]): if q not in S[p]: S[p].append(q) elif (V1[q] > V1[p] and V2[q] > V2[p]) or ( V1[q] >= V1[p] and V2[q] > V2[p]) or (V1[q] > V1[p] and V2[q] >= V2[p]): n[p] = n[p] + 1 if n[p] == 0: rank[p] = 0 if p not in F[0]: F[0].append(p) i = 0 while (F[i] != []): Q = [] for p in F[i]: for q in S[p]: n[q] = n[q] - 1 if (n[q] == 0): rank[q] = i + 1 if q not in Q: Q.append(q) i = i + 1 F.append(Q) del F[len(F) - 1] return F
def list_del(id): if not session.get('log_in'): return redirect(url_for('login')) sql = 'delete from xpp_list where id = %s'%id conn = F.db_get_conn() cursor = conn.cursor() n = cursor.execute(sql) if n: flash(u'删除成功!') else: flash(u'删除失败!') conn.commit() cursor.close() conn.close() return redirect(url_for('list'))
def HLL(UL,UR,zl,zr) : dmas = np.zeros(2) dmen = dmas g = 9.8 ul = UL[1]/(UL[0]+1e-8)*(UL[0]>=1e-3)+0.0 # La velocidad de la celda UL ur = UR[1]/(UR[0]+1e-8)*(UR[0]>=1e-3)+0.0 # La velocidad de la celda UR c_1 = ul-np.sqrt(9.8*UL[0]) c = ur-np.sqrt(9.8*UR[0]) if c < c_1 : c_1 = c c_2 = ul+np.sqrt(9.8*UL[0]) c = ur+np.sqrt(9.8*UR[0]) if c > c_2 : c_2 = c if (abs(c_2-c_1)>1.e-8): alfa0 = (c_2*abs(c_1)-c_1*abs(c_2))/(c_2-c_1) alfa1 = (abs(c_2)-abs(c_1))/(c_2-c_1) else: alfa0=0.0 alfa1=0.0 # Hallamos entonces D+ y D- en i+1/2 difz = zr - zl vecdifz = [difz,0] t = g*(UL[0]+UR[0])*0.5*difz vect = [0,t] dmas = 0.5*alfa0*(UR-UL+vecdifz) + 0.5*(1+alfa1)*(F.F(UR)-F.F(UL) + vect) dmen = -0.5*alfa0*(UR-UL+vecdifz) + 0.5*(1-alfa1)*(F.F(UR)-F.F(UL) + vect) return dmas,dmen
def get_all_ip(): host_list = [] sql = 'select ip1 from xpp_list where type = 0' conn = F.db_get_conn() cursor = conn.cursor() n = cursor.execute(sql) if n: host_list1 = cursor.fetchall() for i in host_list1: host_list.append(i[0]) sql = 'select ip from xpp_list_son' n = cursor.execute(sql) if n: host_list2 = cursor.fetchall() for i in host_list2: host_list.append(i[0]) cursor.close() conn.close() return host_list
def login(): if request.method == 'POST': user_name = request.form['username'] pass_word = request.form['password'] conn=F.db_get_conn() cursor=conn.cursor() sql = 'select password from xpp_user where username = "******"'%user_name n = cursor.execute(sql) if n: rows = cursor.fetchone() cursor.close() conn.close() if pass_word == rows[0]: session['log_in'] = True return redirect(url_for('index')) else: flash(u'密码错误!') else: flash(u'用户不存在!') cursor.close() conn.close() return render_template('login.html') else: return render_template('login.html')
def get_data(self, host_dict): if not self.manual: if len(self.input_data) > 0: return self.input_data.pop(0) else: need_remark_face = False redraw_needed = False while len(self.input_data) > 0: data = self.input_data[0] filename, data_rects, data_landmarks = data.filename, data.rects, data.landmarks is_frame_done = False if need_remark_face: # need remark image from input data that already has a marked face? need_remark_face = False if len( data_rects ) != 0: # If there was already a face then lock the rectangle to it until the mouse is clicked self.rect = data_rects.pop() self.landmarks = data_landmarks.pop() data_rects.clear() data_landmarks.clear() redraw_needed = True self.rect_locked = True self.rect_size = (self.rect[2] - self.rect[0]) / 2 self.x = (self.rect[0] + self.rect[2]) / 2 self.y = (self.rect[1] + self.rect[3]) / 2 if len(data_rects) == 0: if self.cache_original_image[0] == filename: self.original_image = self.cache_original_image[1] else: self.original_image = cv2_imread(filename) self.cache_original_image = (filename, self.original_image) (h, w, c) = self.original_image.shape self.view_scale = 1.0 if self.manual_window_size == 0 else self.manual_window_size / ( h * (16.0 / 9.0)) if self.cache_image[0] == (h, w, c) + (self.view_scale, filename): self.image = self.cache_image[1] else: self.image = cv2.resize(self.original_image, (int( w * self.view_scale), int(h * self.view_scale)), interpolation=cv2.INTER_LINEAR) self.cache_image = ((h, w, c) + (self.view_scale, filename), self.image) (h, w, c) = self.image.shape sh = (0, 0, w, min(100, h)) if self.cache_text_lines_img[0] == sh: self.text_lines_img = self.cache_text_lines_img[1] else: self.text_lines_img = (imagelib.get_draw_text_lines( self.image, sh, [ '[Mouse click] - lock/unlock selection', '[Mouse wheel] - change rect', '[Enter] / [Space] - confirm / skip frame', '[,] [.]- prev frame, next frame. [Q] - skip remaining frames', '[a] - accuracy on/off (more fps)', '[f] - select face by last rect', '[h] - hide this help' ], (1, 1, 1)) * 255).astype(np.uint8) self.cache_text_lines_img = (sh, self.text_lines_img) while True: io.process_messages(0.0001) new_x = self.x new_y = self.y new_rect_size = self.rect_size right_btn_down = False mouse_events = io.get_mouse_events(self.wnd_name) for ev in mouse_events: (x, y, ev, flags) = ev if ev == io.EVENT_MOUSEWHEEL and not self.rect_locked: mod = 1 if flags > 0 else -1 diff = 1 if new_rect_size <= 40 else np.clip( new_rect_size / 10, 1, 10) new_rect_size = max(5, new_rect_size + diff * mod) elif ev == io.EVENT_LBUTTONDOWN: self.rect_locked = not self.rect_locked self.extract_needed = True elif ev == io.EVENT_RBUTTONDOWN: right_btn_down = True elif not self.rect_locked: new_x = np.clip(x, 0, w - 1) / self.view_scale new_y = np.clip(y, 0, h - 1) / self.view_scale key_events = io.get_key_events(self.wnd_name) key, chr_key, ctrl_pressed, alt_pressed, shift_pressed = key_events[ -1] if len(key_events) > 0 else (0, 0, False, False, False) if (key == ord('f') or right_btn_down) and self.rect_locked: # confirm frame is_frame_done = True self.last_outer = self.temp_outer data_rects.append(self.rect) data_landmarks.append(self.landmarks) self.auto = True break elif (key == ord('f') or key == ord('s') or self.auto) and len(self.last_outer) != 0: last_mid = F.mid_point(self.last_outer) last_border = np.linalg.norm( np.array(self.last_outer[0]) - np.array(self.last_outer[1])) last_area = F.poly_area(self.last_outer) x, y = last_mid new_x = np.clip(x, 0, w - 1) / self.view_scale new_y = np.clip(y, 0, h - 1) / self.view_scale new_rect_size = last_border / 2 / self.view_scale * 0.8 # make sure rect and landmarks have been refreshed # if self.x == new_x and self.y == new_y and len(self.temp_outer) != 0: if len(self.temp_outer) != 0: # compare dist and area temp_mid = F.mid_point(self.temp_outer) dist = np.linalg.norm( np.array(temp_mid) - np.array(last_mid)) dist_r = dist / last_border temp_area = F.poly_area(self.temp_outer) area_r = temp_area / last_area v0 = np.array(last_mid) - np.array( self.last_outer[0]) v1 = np.array(temp_mid) - np.array( self.temp_outer[0]) angle = math.fabs(F.angle_between(v0, v1)) if dist_r < 0.5 and 0.5 < area_r < 1.5 and angle < 0.7: is_frame_done = True self.last_outer = self.temp_outer data_rects.append(self.rect) data_landmarks.append(self.landmarks) self.auto = True break elif key == ord('s'): is_frame_done = True break elif self.x != new_x or self.y != new_y: # 可以在等一轮更新后试一下 pass else: self.auto = False for i in range(3): time.sleep(0.1) print('\a') elif key == ord('\r') or key == ord('\n'): # confirm frame is_frame_done = True data_rects.append(self.rect) data_landmarks.append(self.landmarks) break elif key == ord(' '): #confirm skip frame is_frame_done = True break elif key == ord('z') and len(self.result) > 0: #go prev frame if self.rect_locked: self.rect_locked = False # Only save the face if the rect is still locked data_rects.append(self.rect) data_landmarks.append(self.landmarks) self.input_data.insert(0, self.result.pop()) io.progress_bar_inc(-1) need_remark_face = True break elif key == ord('.'): #go next frame if self.rect_locked: self.rect_locked = False # Only save the face if the rect is still locked data_rects.append(self.rect) data_landmarks.append(self.landmarks) need_remark_face = True is_frame_done = True break elif key == ord('q'): #skip remaining if self.rect_locked: self.rect_locked = False data_rects.append(self.rect) data_landmarks.append(self.landmarks) while len(self.input_data) > 0: self.result.append(self.input_data.pop(0)) io.progress_bar_inc(1) break elif key == ord('h'): self.hide_help = not self.hide_help break elif key == ord('a'): self.landmarks_accurate = not self.landmarks_accurate break if self.x != new_x or \ self.y != new_y or \ self.rect_size != new_rect_size or \ self.extract_needed or \ redraw_needed: self.x = new_x self.y = new_y self.rect_size = new_rect_size self.rect = (int(self.x - self.rect_size), int(self.y - self.rect_size), int(self.x + self.rect_size), int(self.y + self.rect_size)) if redraw_needed: redraw_needed = False return ExtractSubprocessor.Data( filename, landmarks_accurate=self.landmarks_accurate) else: return ExtractSubprocessor.Data( filename, rects=[self.rect], landmarks_accurate=self.landmarks_accurate) else: is_frame_done = True if is_frame_done: self.result.append(data) self.input_data.pop(0) io.progress_bar_inc(1) self.extract_needed = True self.rect_locked = False self.temp_outer = [] return None
def loop(self): self.sound_counter += 1 if self.sound_counter % 3000 == 0 and not self.auto: F.beep()
from D import * from Cit_par import * import F from math import * import matplotlib.pyplot as plt Cmde = F.ElevatorEffectiveness() Cma = F.LongitudinalStability(ede, ea, Cmde) cVt = F.EquivalentAirspeed(cIAS, cTAT, chp)[0] cVe = F.EquivalentAirspeed(cIAS, cTAT, chp)[1] crho = F.EquivalentAirspeed(cIAS, cTAT, chp)[2] cM = F.EquivalentAirspeed(cIAS, cTAT, chp)[3] cT = F.EquivalentAirspeed(cIAS, cTAT, chp)[4] CD0_fit = np.polyfit(F.C_D(cThrust, cVt, crho), F.C_L(cET, cVt, crho)**2, 1) #print C_D_0 p = np.poly1d(CD0_fit) CD0 = -CD0_fit[1] / CD0_fit[0] ## Oswald efficiency factor ## e = F.C_L(cET, cVt, crho)**2 / ((F.C_D(cThrust, cVe, crho) - CD0) * (pi * A)) #CL-alpha graph plt.plot(ca, F.C_L(cET, cVt, crho)) plt.title('$C_L-alpha$ curve, clean configuration') plt.ylabel('Lift coefficient') plt.xlabel('Angle of attack in degrees') plt.text(5.0, 0.7, 'Mach number range: $0.28-0.59$') plt.text(4.5, 0.6, 'Reynols number range: $1.04\cdot10^8-2.11\cdot10^8$') plt.show()
def isonline(ip): if not session.get('log_in'): return redirect(url_for('login')) if F.ping_host(ip): return 'online' return 'offline'
Entry.objects.all()[:5] #LIMIT5 Entry.objects.all()[5:10] Entry.objects.all()[:10:2] #Every second object of the first 10: Entry.objects.order_by('headline')[0] #The same as the next query Entry.objects.order_by('headline')[0:1].get() }}} *Delete Update {{{ publishers = Publisher.objects.all() publishers.delete() publishers.update(status='inactive') }}} *Filters can reference fields on the mode {{{ from django.db.models import F Entry.objects.filter(n_comments__gt=F('n_pingbacks')) Entry.objects.filter(n_comments__gt=F('n_pingbacks') * 2) Entry.objects.filter(rating__lt=F('n_comments') + F('n_pingbacks')) Entry.objects.filter(authors__name=F('blog__name')) # the author's name is the same as the blog name Proxy.objects.all().update(value= not F('value')) # invert the value }}} *Q Object {{{ Poll.objects.get( Q(question__startswith='Who'), Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)) ) Poll.objects.get( Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)), question__startswith='Who' )
def driverPath(a): for i in T.AZ: if F.exist(i+a):return i+a return ''
# 3. startswith(以开头),endswith(以结尾) # 4. 空查询 isnull # BooksInfo.objects.filter(btitle__isnull=True) # 5. 范围查询 in # BooksInfo.objects.filter(id_in=[1,3,5]) # 6. 比较查询 gt(大于), lt(less than), gte(大于等于), lte(小于等于) # 7.日期查询 year(年), month(月), day(日) # 大于某个日期, from datetime import date # BooksInfo.objects.filter(bpub_date_gt=date(2001)) # exclude: 不满足数据的 # order_by('id') 排序 # F对象: 用于比较 import django.db.models from F BookInfo.objects.filter(bread__gt=F('bcomment') * 2) # Q对象: 用于查询条件之间的逻辑关系not and or # 大于3或阅读大于30 BookInfo.objects.filter(Q(id__gt=3)|(bread__gt=30)) # id不等于3 BookInfo.objects.filter(~Q(id=3)) # 聚合函数 # sum,count, avg, max, min # aggregate调用来聚合 from django.db.models import Sum,Count,Max,Min,Avg BookInfo.objects.aggregate((Count('id'))) """ 查询集 """
def get_data(self, host_dict): if self.type == 'landmarks-manual': need_remark_face = False while len(self.input_data) > 0: data = self.input_data[0] filepath, data_rects, data_landmarks = data.filepath, data.rects, data.landmarks is_frame_done = False if self.image_filepath != filepath: self.image_filepath = filepath if self.cache_original_image[0] == filepath: self.original_image = self.cache_original_image[1] else: self.original_image = imagelib.normalize_channels( cv2_imread(filepath), 3) self.cache_original_image = (filepath, self.original_image) (h, w, c) = self.original_image.shape self.view_scale = 1.0 if self.manual_window_size == 0 else self.manual_window_size / ( h * (16.0 / 9.0)) if self.cache_image[0] == (h, w, c) + (self.view_scale, filepath): self.image = self.cache_image[1] else: self.image = cv2.resize(self.original_image, (int( w * self.view_scale), int(h * self.view_scale)), interpolation=cv2.INTER_LINEAR) self.cache_image = ((h, w, c) + (self.view_scale, filepath), self.image) (h, w, c) = self.image.shape sh = (0, 0, w, min(100, h)) if self.cache_text_lines_img[0] == sh: self.text_lines_img = self.cache_text_lines_img[1] else: self.text_lines_img = (imagelib.get_draw_text_lines( self.image, sh, [ '[L Mouse click] - lock/unlock selection. [Mouse wheel] - change rect', '[R Mouse Click] - manual face rectangle', '[Enter] / [Space] - confirm / skip frame', '[,] [.]- prev frame, next frame. [Q] - skip remaining frames', '[a] - accuracy on/off (more fps)', '[h] - hide this help' ], (1, 1, 1)) * 255).astype(np.uint8) self.cache_text_lines_img = (sh, self.text_lines_img) if need_remark_face: # need remark image from input data that already has a marked face? need_remark_face = False if len( data_rects ) != 0: # If there was already a face then lock the rectangle to it until the mouse is clicked self.rect = data_rects.pop() self.landmarks = data_landmarks.pop() data_rects.clear() data_landmarks.clear() self.rect_locked = True self.rect_size = (self.rect[2] - self.rect[0]) / 2 self.x = (self.rect[0] + self.rect[2]) / 2 self.y = (self.rect[1] + self.rect[3]) / 2 self.redraw() if len(data_rects) == 0: (h, w, c) = self.image.shape while True: io.process_messages(0.0001) self.ea.loop() if not self.force_landmarks: new_x = self.x new_y = self.y new_rect_size = self.rect_size mouse_events = io.get_mouse_events(self.wnd_name) for ev in mouse_events: (x, y, ev, flags) = ev if ev == io.EVENT_MOUSEWHEEL and not self.rect_locked: mod = 1 if flags > 0 else -1 diff = 1 if new_rect_size <= 40 else np.clip( new_rect_size / 10, 1, 10) new_rect_size = max(5, new_rect_size + diff * mod) elif ev == io.EVENT_LBUTTONDOWN: if self.force_landmarks: self.x = new_x self.y = new_y self.force_landmarks = False self.rect_locked = True self.redraw() else: self.rect_locked = not self.rect_locked self.extract_needed = True elif ev == io.EVENT_RBUTTONDOWN: self.ea.right_btn_down = True # self.force_landmarks = not self.force_landmarks # if self.force_landmarks: # self.rect_locked = False elif not self.rect_locked: new_x = np.clip(x, 0, w - 1) / self.view_scale new_y = np.clip(y, 0, h - 1) / self.view_scale key_events = io.get_key_events(self.wnd_name) key, chr_key, ctrl_pressed, alt_pressed, shift_pressed = key_events[ -1] if len(key_events) > 0 else (0, 0, False, False, False) if self.ea.right_btn_down and self.rect_locked: is_frame_done = True data_rects.append(self.rect) data_landmarks.append(self.landmarks) self.ea.last_outer = self.ea.cur_outer self.ea.last_landmarks = self.ea.cur_landmarks self.ea.auto = True break elif key == ord('s'): self.ea.auto = False break elif self.ea.auto and len( self.ea.last_outer) > 0 and len( self.ea.last_landmarks) > 0: # 根据上次的外框算出这次的x/y,以及外框大小 border_ratio = 0.6 last_mid = F.mid_point_by_range( self.ea.last_landmarks) last_border = np.linalg.norm( np.array(self.ea.last_outer[0]) - np.array(self.ea.last_outer[1])) last_area = F.poly_area(self.ea.last_outer) x, y = last_mid new_x = np.clip(x, 0, w - 1) / self.view_scale new_y = np.clip(y, 0, h - 1) / self.view_scale new_rect_size = last_border / 2 / self.view_scale * border_ratio # make sure rect and landmarks have been refreshed if len(self.ea.cur_outer) != 0: # 根据本次外框大小算是否valid,通过边长,面积,角度 # temp_mid = F.mid_point(self.temp_outer) cur_mid = F.mid_point_by_range( self.ea.cur_landmarks) dist = np.linalg.norm( np.array(cur_mid) - np.array(last_mid)) dist_r = dist / last_border temp_area = F.poly_area(self.ea.cur_outer) area_r = temp_area / last_area v0 = np.array(last_mid) - np.array( self.ea.last_outer[0]) v1 = np.array(cur_mid) - np.array( self.ea.cur_outer[0]) angle = math.fabs(F.angle_between(v0, v1)) if dist_r < 0.5 and 0.5 < area_r < 1.5 and angle < 0.7: is_frame_done = True self.ea.last_outer = self.ea.cur_outer self.ea.last_landmarks = self.ea.cur_landmarks data_rects.append(self.rect) data_landmarks.append(self.landmarks) self.ea.auto = True break elif self.x != new_x or self.y != new_y: # 可以在等一轮更新后试一下 pass else: self.ea.auto = False F.beep() elif key == ord('n') and len(self.result) > 0: # go prev frame without save and clear result self.rect_locked = False n = 10 if shift_pressed else 1 while n > 0 and len(self.result) > 0: self.input_data.insert(0, self.result.pop()) self.input_data[0].rects.clear() self.input_data[0].landmarks.clear() io.progress_bar_inc(-1) n -= 1 # 直接无视之前的结果,重新标注 self.extract_needed = True break elif key == ord('m') and len(self.input_data) > 0: # go next frame without save self.rect_locked = False n = 10 if shift_pressed else 1 while n > 0 and len(self.input_data) > 0: self.result.append(self.input_data.pop(0)) io.progress_bar_inc(1) n -= 1 # 直接无视之前的结果,重新标注 self.extract_needed = True break elif key == ord('\r') or key == ord('\n'): #confirm frame is_frame_done = True data_rects.append(self.rect) data_landmarks.append(self.landmarks) break elif key == ord(' '): #confirm skip frame is_frame_done = True break elif key == ord(',') and len(self.result) > 0: #go prev frame if self.rect_locked: self.rect_locked = False # Only save the face if the rect is still locked data_rects.append(self.rect) data_landmarks.append(self.landmarks) self.input_data.insert(0, self.result.pop()) io.progress_bar_inc(-1) need_remark_face = True break elif key == ord('.'): #go next frame if self.rect_locked: self.rect_locked = False # Only save the face if the rect is still locked data_rects.append(self.rect) data_landmarks.append(self.landmarks) need_remark_face = True is_frame_done = True break elif key == ord('q'): #skip remaining if self.rect_locked: self.rect_locked = False data_rects.append(self.rect) data_landmarks.append(self.landmarks) while len(self.input_data) > 0: self.result.append(self.input_data.pop(0)) io.progress_bar_inc(1) break elif key == ord('h'): self.hide_help = not self.hide_help break elif key == ord('a'): self.landmarks_accurate = not self.landmarks_accurate break if self.force_landmarks: pt2 = np.float32([new_x, new_y]) pt1 = np.float32([self.x, self.y]) pt_vec_len = npla.norm(pt2 - pt1) pt_vec = pt2 - pt1 if pt_vec_len != 0: pt_vec /= pt_vec_len self.rect_size = pt_vec_len self.rect = (int(self.x - self.rect_size), int(self.y - self.rect_size), int(self.x + self.rect_size), int(self.y + self.rect_size)) if pt_vec_len > 0: lmrks = np.concatenate( (np.zeros((17, 2), np.float32), LandmarksProcessor.landmarks_2D), axis=0) lmrks -= lmrks[30:31, :] mat = cv2.getRotationMatrix2D( (0, 0), -np.arctan2(pt_vec[1], pt_vec[0]) * 180 / math.pi, pt_vec_len) mat[:, 2] += (self.x, self.y) self.landmarks = LandmarksProcessor.transform_points( lmrks, mat) self.redraw() elif self.x != new_x or \ self.y != new_y or \ self.rect_size != new_rect_size or \ self.extract_needed: self.x = new_x self.y = new_y self.rect_size = new_rect_size self.rect = (int(self.x - self.rect_size), int(self.y - self.rect_size), int(self.x + self.rect_size), int(self.y + self.rect_size)) return ExtractSubprocessor.Data( filepath, rects=[self.rect], landmarks_accurate=self.landmarks_accurate) else: is_frame_done = True if is_frame_done: self.result.append(data) self.input_data.pop(0) io.progress_bar_inc(1) self.extract_needed = True self.rect_locked = False self.ea.cur_outer = [] else: if len(self.input_data) > 0: return self.input_data.pop(0) return None
def test_basic(self): s = F.solve(4, 5) self.assertEqual(s, -1) print "basicOK"
def Cost_run(self, Directory): #sys.path.append("../Multiobjective_Functions") #import F self.Cost = F.run(self.X[0])