def __init__(self, jhs_type, thread_num=10, a_val=None): # parent construct MyThread.__init__(self, thread_num) # thread lock self.mutex = threading.Lock() # db self.mysqlAccess = MysqlAccess() # mysql access self.mongofsAccess = MongofsAccess() # mongodb fs access # jhs queue type self.jhs_type = jhs_type # h:每小时, i:商品信息详情 # appendix val self.a_val = a_val # activity items self.items = [] # dial client self.dial_client = DialClient() # local ip self._ip = Common.local_ip() # router tag self._tag = 'ikuai' #self._tag = 'tpent' # give up item, retry too many times self.giveup_items = []
def run(self): MyThread.run(self) Object_Label=self.bridgeutil.GetParameters(self.label) print("Metto in ascolto l'interaccia %s su %s: %s \n" %(self.label,Object_Label.IP,Object_Label.Port)) thread=TCPSimulatorThread(self.label,Object_Label.IP,Object_Label.Port) thread.start()
def main(): logger = logging.getLogger('main()') logger.info('server start!') worker_threads = 4 #定义需要启动的线程数量 timeline = 2 #线程检查时间间隔,秒 thread_pool = {} for i in range(0, worker_threads ): param = 'some param' job = MyJobs( param ) thread = MyThread( job, i ) thread.setDaemon = True thread.start() logger.info('start thread %s' %( thread.getName() )) thread_pool[i] = thread #干完就结束模式 #for eachKey in thread_pool.keys(): # thread_pool[eachKey].join() #保持线程数量模式 while 1: time.sleep(timeline) # 检查每一个线程 for eachKey in thread_pool.keys(): if thread_pool[eachKey].isAlive(): print ('thread alive:' + str(i)) else: print ('thread down:' + str(i)) thread_pool[eachKey].run() logger.info('main exist!') return
def __init__(self, jhs_type, thread_num = 15, a_val=None): # parent construct MyThread.__init__(self, thread_num) # thread lock self.mutex = threading.Lock() # db self.mysqlAccess = MysqlAccess() # mysql access self.mongofsAccess = MongofsAccess() # mongodb fs access # appendix val self.a_val = a_val # jhs queue type self.jhs_type = jhs_type # 1:即将上线品牌团频道页, 2:检查每天还没结束的活动, 3:新增活动 # activity items self.items = [] # dial client self.dial_client = DialClient() # local ip self._ip = Common.local_ip() # router tag self._tag = 'ikuai'
def run(self): MyThread.run(self) #creo la socket per la comunicazione #PARTE SERVER #print("CONFIGURAZIONE SERVER") server = TheServer(self.m_ip, int(self.m_port)) try: server.main_loop() except KeyboardInterrupt: print "Ctrl C - Stopping server" sys.exit(1)
def __init__(self, jhs_type, thread_num=10, a_val=None): # parent construct MyThread.__init__(self, thread_num) # thread lock self.mutex = threading.Lock() # db self.mysqlAccess = MysqlAccess() # mysql access self.mongofsAccess = MongofsAccess() # mongodb access # jhs queue type self.jhs_type = jhs_type # m:解析json数据 # appendix val self.a_val = a_val # activity items self.items = [] # give up item, retry too many times self.giveup_items = []
def __init__(self, _q_type, thread_num=10, a_val=None): # parent construct MyThread.__init__(self, thread_num) # thread lock self.mutex = threading.Lock() self.worker_type = Config.JHS_Brand # message self.message = Message() # db self.mysqlAccess = MysqlAccess() # mysql access self.redisAccess = RedisAccess() # redis db self.mongofsAccess = MongofsAccess() # mongodb fs access # jhs queue type self._q_type = _q_type # main:新增商品, day:每天一次的商品, hour:每小时一次的商品, update:更新 # appendix val self.a_val = a_val # activity items self.items = [] # dial client self.dial_client = DialClient() # local ip self._ip = Common.local_ip() # router tag self._tag = 'ikuai' #self._tag = 'tpent' # give up item, retry too many times self.giveup_items = []
def __init__(self, _q_type, thread_num=10, a_val=None): # parent construct MyThread.__init__(self, thread_num) # thread lock self.mutex = threading.Lock() self.worker_type = Config.TC_Spot # message self.message = Message() # db self.mysqlAccess = MysqlAccess() # mysql access self.mongofsAccess = MongofsAccess() # mongodb fs access # tc queue type self._q_type = _q_type # new:新增商品 # appendix val self.a_val = a_val # activity items self.items = [] # dial client self.dial_client = DialClient() # local ip self._ip = Common.local_ip() # router tag self._tag = 'ikuai' #self._tag = 'tpent' # give up item, retry too many times self.giveup_items = []
def __init__(self, key, q_type, thread_num=10, a_val=None): # parent construct MyThread.__init__(self, thread_num) # thread lock self.mutex = threading.Lock() self.tc_type = Config.TC_TYPE # tc type #self.item_type = q_type # item queue type # db self.mysqlAccess = MysqlAccess() # mysql access self.redisQueue = RedisQueue() # redis queue self.mongofsAccess = MongofsAccess() # mongodb fs access # tc queue type self.tc_queue_type = q_type # new... self._key = key # redis queue key # appendix val self.a_val = a_val # return items self.items = [] # dial client self.dial_client = DialClient() # local ip self._ip = Common.local_ip() # router tag self._tag = 'ikuai' #self._tag = 'tpent' # give up item, retry too many times self.giveup_items = []
def __init__(self, itemtype, q_type, thread_num=10, a_val=None): # parent construct MyThread.__init__(self, thread_num) # thread lock self.mutex = threading.Lock() self.jhs_type = Config.JHS_TYPE # jhs type self.item_type = itemtype # item type # db self.mysqlAccess = MysqlAccess() # mysql access self.redisQueue = RedisQueue() # redis queue self.mongofsAccess = MongofsAccess() # mongodb fs access # jhs queue type self.jhs_queue_type = q_type # h:每小时 self._key = '%s_%s_%s' % (self.jhs_type,self.item_type,self.jhs_queue_type) # appendix val self.a_val = a_val # activity items self.items = [] # dial client self.dial_client = DialClient() # local ip self._ip = Common.local_ip() # router tag self._tag = 'ikuai' #self._tag = 'tpent' # give up item, retry too many times self.giveup_items = []
def main(): nfuncs = len(funcs) print('single thread start at:', ctime()) for i in range(nfuncs): print('starting', funcs[i].__name__, 'at', ctime()) print(funcs[i](n)) print(funcs[i].__name__, 'finished at:', ctime()) print('single thread end at:', ctime()) threads = [] print('multiple threads starting at:', ctime()) for i in range(nfuncs): t = MyThread(funcs[i], args=(n, ), name=funcs[i].__name__) threads.append(t) for i in range(nfuncs): threads[i].start() pass for i in range(nfuncs): threads[i].join() print(threads[i].getresult()) print('multiple threads end at:', ctime())
def main(): ''' a=2 print("a=%d" %a) area_test(a) print("a now is a= %d" %a) q=Queue(10); print("main q size %d" %q.qsize()) queue_test(q) print("after function q size %d" %q.qsize()) ''' threads = [] q = Queue(10) loop = 10 for i in range(nfuncs): t = MyThread(funcs[i], (q, loop)) threads.append(t) for i in range(nfuncs): threads[i].start() '''
def main(): print 'single thread...' for func in funcs: print func.__name__, 'start@', ctime() print func(n) print func.__name__, 'end@', ctime() threads = [] for i in range(len(funcs)): mythread = MyThread(funcs[i], (n, ), funcs[i].__name__) threads.append(mythread) print 'multi-threads...' for th in threads: th.start() for th in threads: th.join() print th.getResult() print 'main--done'
def pro_run(path): baidu_handle(path) data = pre_run(path) img = data["image"] # data["binarize_image"].show() width, height = img.size cuty = data["cuty"] print("start") # loop = asyncio.get_event_loop() tasks = [] for i in range(1, len(cuty)): temp = img.crop((0, cuty[i - 1], width, cuty[i])) t = MyThread(tesseract_ocr, args=(temp,)) tasks.append(t) # coroutine = asyncio.ensure_future(tesseract_ocr(temp)) # task = asyncio.ensure_future(coroutine) # tasks.append(coroutine) result = runthread(tasks, 6) for i in result: print(i)
def main(): nloops = randint(2, 5) q = Queue(32) threads = [] for i in range(nfuncs): t = MyThread(funcs[i], (q, nloops), funcs[i].__name__) threads.append(t) for i in range(nfuncs): threads[i].start() for i in range(nfuncs): threads[i].join() print('all Done')
def main(): nfuncs = range(len(funcs)) print('*** SINGLE THREAD') for i in nfuncs: print('starting %s at: %s' % (funcs[i].__name__, ctime())) print(funcs[i](n)) print('%s finished at: %s' % (funcs[i].__name__, ctime())) print('\n*** MULTIPLE THREAD') threads = [] for i in nfuncs: t = MyThread(funcs[i], (n, ), funcs[i].__name__) threads.append(t) for i in nfuncs: threads[i].start() for i in nfuncs: threads[i].join() print(threads[i].getResult()) print('all DONE')
def main(): nfuncs = range(len(funcs)) print('*** single thread -------------') for i in nfuncs: print('starting ', funcs[i].__name__, 'at: ', ctime()) print(funcs[i](n)) print(funcs[i].__name__, ' finished at: ', ctime()) print('*** multiple thread -------------') threads = [] for i in nfuncs: t = MyThread(funcs[i], (n, ), funcs[i].__name__) threads.append(t) for i in nfuncs: threads[i].start() for i in nfuncs: threads[i].join() print(threads[i].getResult()) print('all done')
# coding:utf-8 import time from MyThread import MyThread __author__ = 'uv2sun' t1 = MyThread(1, "t1") t2 = MyThread(2, "t2") print time.ctime() t1.start() t2.start() t1.join() t2.join() print time.ctime()
class MyVideoRecorder(object): def __init__(self, cam=1): self.ap = argparse.ArgumentParser() self.ap.add_argument("-v", "--video", default='./videos', help="path to the video file") self.ap.add_argument("-f", "--fps", type=int, default=10, help="fps") self.ap.add_argument("-p", "--path", type=str, default='./videos', help="path to which to save videos") file_name = 'test' + str(np.random.randint(100)) self.ap.add_argument("-n", "--name", type=str, default=file_name, help="filename") self.ap.add_argument("-r", "--resize", type=bool, default=True, help="filename") self.ap.add_argument("-c", "--cam", type=int, default=1, help="csamera number") self.args = vars(self.ap.parse_args()) self.output = self.args['path'] + '/' + self.args['name'] self.fps = self.args['fps'] self.cam = self.args['cam'] self.resize = self.args['resize'] print(self.output) self.fourcc = cv2.VideoWriter_fourcc(*'XVID') self.imH = int(360 / 2) self.imW = int(640 / 2) self.recording = False self.initialiseCap() self.initialiseWriter() self.recordingThread = MyThread(self.record) self.recordingThread.start() self.Timer = MyTimer() self.Timer.restart() def convert2gif(self): self.gif = MyGif(self.output, array, fps=self.fps, scale=1.0) def start(self): self.recording = True def pause(self): self.recording = False def initialiseCap(self): self.cap = cv2.VideoCapture(self.cam) def initialiseWriter(self): self.writer = cv2.VideoWriter(self.output,fourcc = self.fourcc,\ fps = self.fps, \ frameSize = (self.imW,self.imH)) time.sleep(1.0) def record(self): while self.recording: self.grabFrame() self.writer.write(self.frame) cv2.imshow("Frame", self.frame) self.key = cv2.waitKey(1) & 0xFF if self.key == ord("q"): self.recording = False self.stop() def grabFrame(self): ret, self.frame = self.cap.read() if ret: self.frame = self.frame.swapaxes(0, 1)[:, :, ::-1] if self.resize: self.frame = cv2.resize(self.frame, (self.imH, self.imW)).astype('uint8') def releaseCap(self): self.cap.release() def stop(self): self.recording = False self.releaseCap() self.writer.release() print('file saved at:\n{0}'.format(self.output)) cv2.destroyAllWindows() self.recordingThread.stop()
a.append(int(n)) except Exception as e: print(e) _max = max(a) for i in range(1, _max): u = str(l+"/"+str(i)) url_list.append(u) return url_list if __name__ == '__main__': url = "https://avmoo.asia/cn/genre" print("开始解析:" + url) html = get_html(url, 'https://avmoo.asia/cn') soup = get_soup(html) img_dirs = get_img_dirs(soup) threads = [] if None == img_dirs: print("无法获取该网页下的相册内容...") else: for d in img_dirs: # print(img_dirs.get(d)) # download_imgs((d, img_dirs.get(d), 'https://avmoo.asia/cn')) my_thread = MyThread(download_imgs, (d, img_dirs.get(d), 'https://avmoo.asia/cn')) my_thread.start() my_thread.join() # threads.append(my_thread) # for my in threads: # my.join()
def __init__(self, opt=1): #################### #### args #################### self.ap = argparse.ArgumentParser() self.default_path = '/Users/virginiarutten/Documents/deep_fish/videos' self.ap.add_argument("-v", "--video", \ default = self.default_path, help="path to the video file") self.ap.add_argument("-f", "--fps", type=str, default=str(10), help="fps") self.ap.add_argument("-p", "--path", type = str, \ default=self.default_path, help="path to which to save videos") file_name = 'test_delete' self.ap.add_argument("-n", "--name", type=str, default=file_name, help="filename") self.ap.add_argument("-r", "--resize", type=bool, default=True, help="filename") self.ap.add_argument("-c", "--cam", type=int, default=1, help="camera number") self.ap.add_argument("-t", "--max_time", type=int, default=10, help="camera number") self.ap.add_argument("-w", "--wait_time", type=int, default=100, help="camera number") if opt == 1: self.args = vars(self.ap.parse_args()) else: self.args = vars(self.ap.parse_known_args()[0]) self.wait_time = self.args['wait_time'] / 1000 self.dt = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")[2:] self.output = self.args['path'] + '/' + self.args[ 'name'] + self.dt + '.avi' #self.fps = int(self.args['fps']) self.fps = np.ceil(1 / self.wait_time) self.cam = self.args['cam'] self.resize = self.args['resize'] self.max_time = self.args['max_time'] print('output file:{0}'.format(self.output)) ################# ### settings ############### self.fourcc = cv2.VideoWriter_fourcc(*'XVID') self.imH = int(360 / 2) self.imW = int(640 / 2) self.recording = False self.initialiseCap() self.initialiseWriter() time.sleep(.2) self.grabFrame() self.initialise_window() self.show_frame() self.recording = True self.recordingThread = MyThread(self.start_recording, self.wait_time) self.recordingThread.start() self.count = 0 self.Timer = MyTimer() self.Timer.restart()
# print(info) print(datetime.datetime.now()) time.sleep(5) except: pass os.system('say "end"') if __name__ == "__main__": print('Strat Tickets') headers = { 'Host': 'kyfw.12306.cn', 'If-Modified-Since': '0', 'Pragma': 'no-cache', 'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'X-Requested-With': 'XMLHttpRequest' } index_url = 'https://www.12306.cn/index/' html_index = requests.get(index_url, headers=headers, verify=False) print(html_index.status_code) queray = LeftqueryUtil(requests) from_station = '宿州东' to_station = '上海' date = '2019-10-07' thread1 = MyThread().createThread(querayThread, args={"queray": queray}) thread1.start() thread1.join()
class myApp(QtGui.QWidget): def __init__(self): super(myApp, self).__init__() # initialise gui self.initUI() # initialise bools self.measuring = False #reading from arduino self.trialOn = False #trial loo ## trial thread self.trial_thread = MyThread(self.trial_loop) self.trial_thread.start() self.ard_thread = MyThread(self.read_ard) self.ard_thread.start() # try to connect to arduino try: self.get_serial() except: pass try: self.load_picture() except: pass def initUI(self): self.maxLen = 300 # data buffer self.yvals = deque([0.0]*self.maxLen) ##################################### ## standard buttons ##################################### ## start flow button self.start_btn = QtGui.QPushButton('start',self) self.start_btn.clicked.connect(self.on_start) ## stop flow button self.stop_btn = QtGui.QPushButton('stop',self) self.stop_btn.clicked.connect(self.on_stop) ## quit app button self.qbtn = QtGui.QPushButton('exit',self) # quit threads if running ************** self.qbtn.clicked.connect(self.on_quit) # quit app self.qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit) ##################################### ## set flow rate button ##################################### self.slider = QtGui.QSlider(Qt.Horizontal) self.slider.setMinimum(0) self.slider.setMaximum(100) self.slider.setValue(50) self.slider.setTickPosition(QSlider.TicksBelow) self.slider.setTickInterval(10) # change value self.slider.valueChanged.connect(self.slidervaluechange) ##################################### ## labels to show current flow rate ##################################### ## text - data sent from Arduino self.text_ard = QtGui.QLineEdit('arduino sent:') self.label_ard = QLabel() self.label_ard.setText('arduino sent:') # communication signal to write to gui self.comm_ard = Communicate() self.comm_ard.signal.connect(self.text_ard.setText) # ## text - data written to Arduino self.text_rate= QtGui.QLineEdit('PC sent:') self.label_rate = QLabel() self.label_rate.setText('PC sent:') # communication signal to write to gui self.comm_rate = Communicate() self.comm_rate.signal.connect(self.text_rate.setText) self.plot = pg.PlotWidget() ##################################### ## stimulus display ##################################### ## start trial self.trial_btn= QtGui.QPushButton('start trial',self) self.trial_btn.clicked.connect(self.on_startTrial) self.trialOff_btn= QtGui.QPushButton('stop trial',self) self.trialOff_btn.clicked.connect(self.on_stopTrial) # communication signal to write to gui self.comm_trial = Communicate() self.comm_trial.signal.connect(self.text_rate.setText) self.figure = pl.Figure() self.canvas = FigureCanvas(self.figure) self.stim_btn = QtGui.QPushButton('show stimulus',self) self.stim_btn.clicked.connect(self.plot_picture) self.stimOff_btn = QtGui.QPushButton('hide stimulus',self) self.stimOff_btn.clicked.connect(self.clear_picture) ##################################### ## layout #####################################v layout = QtGui.QGridLayout() layout.setColumnStretch(0, 0) layout.setColumnStretch(1, 0) layout.addWidget(self.start_btn, 0, 0, 1, 1) # button goes in upper-left layout.addWidget(self.stop_btn, 1, 0, 1, 1) # button goes in upper-left layout.addWidget(self.qbtn, 2, 0, 1, 1) # button goes in upper-left layout.addWidget(self.label_ard, 0, 1, 1, 1) # button goes in upper-left layout.addWidget(self.text_ard, 0, 2, 1, 1) # button goes in upper-left layout.addWidget(self.label_rate, 1, 1, 1, 1) # button goes in upper-left layout.addWidget(self.text_rate, 1, 2, 1, 1) # button goes in upper-left layout.addWidget(self.slider, 3, 0, 1, 1) # button goes in upper-left layout.addWidget(self.stim_btn, 2, 2, 1, 1) # button goes in upper-left layout.addWidget(self.stimOff_btn, 2, 3, 1, 1) # button goes in upper-left layout.addWidget(self.trial_btn, 3, 2, 1, 1) # button goes in upper-left layout.addWidget(self.trialOff_btn, 3, 3, 1, 1) # button goes in upper-left layout.addWidget(self.plot, 4, 0, 3, 5) # plot goes on right side, spanning 3 rows layout.addWidget(self.canvas, 4, 5, 3, 5) self.setLayout(layout) self.setWindowTitle('DeepFish') self.show() def load_picture(self): file_path = '../assets/pp.png' self.im = np.asarray(Image.open(file_path)) def clear_picture(self): try: ax ax.set_axis_off() except: ax = self.figure.add_subplot(111) ax.set_axis_off() ax.clear() ax.set_axis_off() ax.set_frame_on(False) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) self.canvas.draw() def plot_picture(self): try: ax except: ax = self.figure.add_subplot(111) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) ax.set_axis_off() ax.clear() ax.imshow(self.im) ax.set_frame_on(False) self.canvas.draw() def test_plot(self): tmp_data = np.arange(20) ax = self.figure.add_subplot(111) ax.set_axis_off() ax.clear() ax.imshow(self.im) ax.set_axis_off() ax.set_frame_on(False) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) #ax.plot(tmp_data, 'o-') self.canvas.draw() def slidervaluechange(self): rate = self.slider.value() self.send_ard(rate) def send_ard(self, var): self.ser.write(bytes(var)) def go_cue(self): self.plot_picture() def trial_loop(self): self.trial_time = 10 t = Timer(self.trial_time, self.go_cue) while self.trialOn: pass #t.start() #self.test_plot() def read_ard(self): while self.measuring: self.incoming_data = self.ser.readline().decode("utf-8") sleep(0.1) if self.incoming_data.find('ard')>-1: numbers = ''.join(re.findall('[0-9]',self.incoming_data)) self.comm_ard.signal.emit(self.incoming_data) # add data point to plot self.addToBuf( self.yvals,numbers) sys.stdout.write(numbers+ '\n') #sys.stdout.write("ard found") elif self.incoming_data.find('PC')>-1: numbers = ''.join(re.findall('[0-9]',self.incoming_data)) self.comm_rate.signal.emit(self.incoming_data) sys.stdout.write(numbers + '\n') def get_serial(self): self.ser = serial.Serial('/dev/cu.usbmodem14311', 9600,timeout=.05) def startTrial(self): if not self.trialOn: self.trialOn=True def stopTrial(self): if self.trialOn: self.trialOn=False ################## ### measure rate ################ def startMeasuring(self): if not self.measuring: self.measuring=True def stopMeasuring(self): if self.measuring: self.measuring=False def print_to_screen(self): while self.measuring: sleep(0.1) data = self.ser.readline().decode("utf-8") self.comm.signal.emit(data) # add to buffer def addToBuf(self, buf, val): if len(buf) < self.maxLen: buf.append(val) else: buf.pop() buf.appendleft(val) ################### #### slots ################### @pyqtSlot() def on_startTrial(self): print('starting trial') self.startTrial() @pyqtSlot() def on_stopTrial(self): print('stop trial') self.stopTrial() @pyqtSlot() def on_start(self): print('start to measuring') self.startMeasuring() @pyqtSlot() def on_stop(self): print('stop measuring') self.stopMeasuring() @pyqtSlot() def on_quit(self): print('kill all threads') self.ard_thread.stop() self.trial_thread.stop()
def __init__(self, general_): MyThread.__init__(self, -1, "main") self.general = general_
application.listen(port) tornado.ioloop.IOLoop.instance().start() def add_new_pic(face_recognization): while True: # 直接请求本地的服务,加入LSH Forest face_recognization.add_all_new_pic() time.sleep(10) if __name__ == "__main__": sub_process_id = '' try: face_recognition = FaceRecognition() face_recognition.load_all_data() application = tornado.web.Application([(r"/", MainHandler),]) add_new_pic_args = (face_recognition, ) add_new_pic_thread = MyThread(func=add_new_pic, args=add_new_pic_args, name='add_new_pic') add_new_pic_thread.start() application.listen(port) tornado.ioloop.IOLoop.instance().start() add_new_pic_thread.join() except: traceback.print_exc()
def get_html_data(url,url_id): get_url = MyThread (get_response, (url,)) get_url2 = MyThread (get_route, (url_id,)) get_url.start (), get_url2.start () get_url.join (), get_url2.join () response = get_url.get_result () route = get_url2.get_result () return response,route
def __init__(self,opt=1): ########################## ##### default saving directory ########################## self.default_path = '/Users/virginiarutten/Documents/deep_fish/videos' self.filename = 'test' self.ext = '.avi' self.dt = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")[2:] self.foldername = self.default_path +'/' + self.dt[:6] self.path = self.get_path() self.check_dir() self.save = False self.cameraPort = 1 self.width = 950 self.height = 700 self.recording = False self.trialOn = False self.flowOn = False self.ARD = False self.trialTime = 10 self.trialSleepTime = 10 ########################## ##### Arduino settings ########################## self.flowOffDelay = 1 self.flowOnDelay = 1 self.imW = int(640/2) self.imH = int(360/2) self.imfps = 25 self.trialTimer = MyTimer() self.trialTimer.restart() self.frameTimer = MyTimer() self.frameTimer.restart() self.ite = 0 self.args = self.initialise_tracking_variables() self.win = self.initialise_window() self.recorder = self.initialise_videorecorder() self.Tracker = self.initialise_tracker() ########################## ##### Arduino ########################## self.ARDPort = self.ArdPortComboBox.currentData() self.Ard = self.initialise_Ard() ########################## ##### Threads ########################## self.recordingThread = MyThread(self.start_recording, wait_time = 0.02) self.recordingThread.start() self.trialThread = MyThread(self.start_trial, wait_time = 0.001) self.trialThread.start() self.recording = True
def server_main(PLAYERS_COUNT, SERVER_ADDRESS, SERVER_PORT, LEVEL_H, LEVEL_W): # инициализация pygame pygame.init() # создаем уровень level_height = LEVEL_H level_width = LEVEL_W blocks, total_level_width, total_level_height = gen_level(level_height,level_width, BLOCK_DEMAGE) # группы объектов players_yellow = pygame.sprite.Group() players_yellow_bullets = pygame.sprite.Group() players_green = pygame.sprite.Group() players_green_bullets = pygame.sprite.Group() # серверный сокет game_server = Game_Server_UDP(SERVER_ADDRESS, SERVER_PORT, BLOCK_SIZE, LEVEL_W, LEVEL_H, players_green, players_yellow, total_level_width, total_level_height, level_width, level_height, BLOCK_DEMAGE, FRAME_RATE, blocks) print("Server started on %s:%d" % (SERVER_ADDRESS, SERVER_PORT)) print("Waiting for %d players..." % PLAYERS_COUNT) #запускаем цикл опроса сокетов socket_loop_thread = MyThread(asyncore.loop, [0.01]) socket_loop_thread.start() # таймер timer = pygame.time.Clock() # id пули bullet_id = 0 # ждем первого клиента while game_server.player_count == 0: time.sleep(1) # Основной цикл программы while 1: timer.tick(FRAME_RATE) # таймер на 30 кадров print('\rserver FPS: %.2f ' % timer.get_fps(), end='') # вывод fps # отключившиеся игроки disconnected = [] # цикл по всем игрокам for player in game_server.players: if player.ready: if player.socket._closed: disconnected.append(player.id) print('\nDisconnected client %s:%d, team: %s, id: %d' % (player.addr[0], player.addr[1], player.team, player.id)) player.sprite.kill() game_server.players.remove(player) game_server.player_count -= 1 #if game_server.player_count <= 0: #pygame.quit() #game_server.close() #print("All players disconnected") #return # очередной пакет данных текущего игрока # формат: # input_message = {'id': my_id, 'name': player_name, 'events': event_queue} # event_queue = [ {'type': e.type, 'key': e.key}, ... ] # получаем очередной пакет данных l = len(player.imes) if l > 0: input_message = player.imes.pop() player.imes = [] player.name = input_message['name'] else: input_message = {'id': 0, 'name': "", 'events': []} # очередь событий текущего игрока event_queue = input_message['events'] # цикл по всем событиям в очереди for e in event_queue: type = e['type'] # тип события key = e['key'] # нажатая клавиша # нажатие клавиши на клавиатуре if type == pygame.KEYDOWN: # движение if key == pygame.K_LEFT: player.sprite.course = 'left' elif key == pygame.K_RIGHT: player.sprite.course = 'right' elif key == pygame.K_UP: player.sprite.course = 'up' elif key == pygame.K_DOWN: player.sprite.course = 'down' # выстрел if key == pygame.K_SPACE and not player.sprite.isBullet: player_bullet = Bullet(bullet_id,player.sprite.rect.left,player.sprite.rect.top,player.sprite.shutdirection) bullet_id += 1 player_bullet.shooter = player.sprite if player.team == 'green': players_green_bullets.add(player_bullet) elif player.team == 'yellow': players_yellow_bullets.add(player_bullet) player.sprite.isBullet = True # отпускание клавиши if type == pygame.KEYUP: if (key == pygame.K_RIGHT) and (player.sprite.course == 'right'): player.sprite.course = '' elif (key == pygame.K_LEFT) and (player.sprite.course == 'left'): player.sprite.course = '' elif (key == pygame.K_UP) and (player.sprite.course == 'up'): player.sprite.course = '' elif (key == pygame.K_DOWN) and (player.sprite.course == 'down'): player.sprite.course = '' # обновление всех объектов (симуляция мира) players_yellow.update( blocks.sprites() + players_green.sprites() + players_yellow.sprites() ) players_green.update( blocks.sprites() + players_yellow.sprites() + players_green.sprites() ) players_yellow_bullets.update( blocks.sprites() + players_green.sprites() + players_green_bullets.sprites() ) players_green_bullets.update( blocks.sprites() + players_yellow.sprites() + players_yellow_bullets.sprites() ) # отправить очередные изменения мира dataframe = {} #блоки dataframe['blocks'] = [] for b in blocks.sprites(): if b.shooted: data = {'id' : b.id, 'shootdirection' : b.shootdirection} dataframe['blocks'].append(data) b.shooted = False b.shootdirection = '' if b.dead: b.kill() #игроки dataframe['disconnected'] = disconnected dataframe['players'] = [] for player in game_server.players: current = {'id': player.id, 'name': player.name, 'x': player.sprite.rect.x, 'y': player.sprite.rect.y, 'course': player.sprite.course, 'shutdirection': player.sprite.shutdirection, 'dead': player.sprite.dead, 'team' : player.team, 'dead_count': player.sprite.config.dead_count, 'frag': player.sprite.frag} if player.last != current : dataframe['players'].append(current) player.last = current #пули dataframe['bullets'] = [] for b in players_yellow_bullets.sprites() + players_green_bullets.sprites(): data = {'id': b.id, 'x': b.rect.x, 'y': b.rect.y, 'shutdirection' : b.shutdirection, 'bum': b.bum} dataframe['bullets'].append(data) # упаковываем данные message = pack_data(dataframe) # отправляем for player in game_server.players: player.obuffer += message
conn.execute('''CREATE TABLE IF NOT EXISTS GALLERY (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, URL TEXT NOT NULL);''') print "GALLERY Table created successfully" conn.execute('''CREATE TABLE IF NOT EXISTS PHOTO (ID INTEGER PRIMARY KEY AUTOINCREMENT, GALLERY INTEGER NOT NULL, URL TEXT NOT NULL);''') print "PHOTO Table created successfully" parser = argparse.ArgumentParser() parser.add_argument("echo") # parser.add_argument("url") # url = int(args.url) args = parser.parse_args() url = str(args.echo) print("开始解析:" + url) html = get_html(url) soup = get_soup(html) img_dirs = get_img_dirs(soup) if None == img_dirs: print("无法获取该网页下的相册内容...") else: for d in img_dirs: my_thread = MyThread(fetch_imgs, (d, img_dirs.get(d))) my_thread.start() my_thread.join()
class MyLiveTracker(object): def __init__(self, opt=1): ########################## ##### default saving directory ########################## self.default_path = '/Users/virginiarutten/Documents/deep_fish/videos' self.filename = 'test' self.ext = '.avi' self.dt = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")[2:] self.foldername = self.default_path + '/' + self.dt[:6] self.path = self.get_path() self.check_dir() self.save = False self.cameraPort = 1 self.recording = False self.trialOn = False self.flowOn = False self.ARD = False self.trialTime = 10 self.trialSleepTime = 10 ########################## ##### Arduino settings ########################## self.flowOffDelay = 1 self.flowOnDelay = 1 self.imW = int(640 / 2) self.imH = int(360 / 2) self.imfps = 25 self.trialTimer = MyTimer() self.trialTimer.restart() self.ite = 0 self.args = self.initialise_tracking_variables() self.win = self.initialise_window() self.recorder = self.initialise_videorecorder() self.Tracker = self.initialise_tracker() ########################## ##### Arduino ########################## self.ARDPort = self.ArdPortComboBox.currentData() self.Ard = self.initialise_Ard() ########################## ##### Threads ########################## self.recordingThread = MyThread(self.start_recording) self.recordingThread.start() self.trialThread = MyThread(self.start_trial) self.trialThread.start() self.recording = True def check_dir(self): ''' check that directory of the day exisits and that filename is unique''' if not os.path.isdir(self.foldername): print('creating directory...') os.mkdir(self.foldername) file_num = 1 while os.path.exists(self.path): print('file already exisits...\nrenaming') print(self.path) self.filename = self.filename + str(file_num) file_num += 1 self.path = self.get_path() def initialise_tracker(self): self.Tracker = MyRealTimeTracker(self.args) return self.Tracker def initialise_tracking_variables(self): ''' default values ''' self.keypoints = {} self.mvAvgFrame = None self.fishNum = 4 self.area_mn = 35 ## threshold mask value self.pVal = 180 self.pVal_mx = 255 self.text = None self.pre_frames = 5 self.args = {} self.args['pVal'] = self.pVal self.args['pVal_mx'] = self.pVal_mx self.args['fishNum'] = self.fishNum self.args['area_mn'] = self.area_mn self.args['keypoints'] = self.keypoints self.args['pre_frames'] = self.pre_frames return self.args def get_path(self): return self.foldername + '/' + self.dt + self.filename + self.ext def initialise_videorecorder(self): ''' initialises recorder''' self.num_saved_frame = 0 self.cameraPort = self.cameraComboBox.currentIndex() self.check_dir() if self.path[-3:] != 'avi': print('please check extension') print('initialising recording...\noutput file:{0}'.\ format(self.path)) self.recorder = MyVideoRecorder(cameraport = self.cameraPort,\ path = self.path,\ imH = self.imH,\ imW = self.imW,\ fps = self.imfps) wasrecording = False if self.recording: wasrecording = True self.recording = False self.recorder.initialise_camera() ### reinitialise camera self.camera = self.recorder.camera ### test camera works if self.camera.grab() == False: if self.cameraPort == 1: self.cameraPort = 0 self.cameraComboBox.setCurrentIndex(self.cameraPort) print('no camera detected... camera changed') if wasrecording: self.recording = True else: self.recording = False wasrecording = False return self.recorder def initialise_Ard(self): try: self.Ard = MyArduino() self.ARDport = self.Ard.port self.ARD = True except: print('no valid port found \nplease check') self.ARD = False return self.Ard def load_picture(self): file_path = '/Users/virginiarutten/Documents/deep_fish/assets/pavlov_dog.jpg' self.bkImage = np.array(Image.open(file_path)).T def initialise_window(self): self.load_picture() self.app = QApplication([]) self.win = MyQtWidget() ##################################### ## Layout ##################################### self.layout = QGridLayout() self.win.setLayout(self.layout) self.createRecordGroupBox() self.createDefaultGroupBox() self.createImageGroupBox() self.createSwitchFormGroupBox() self.createCalibrationFormGroupBox() self.createParamGroupBox() self.createPumpGroupBox() self.createTextGroupBox() self.resetPath() self.layout.addWidget(self.imageForm, 0, 0, 1, 3) self.layout.addWidget(self.textForm, 0, 4, 1, 3) self.layout.addWidget(self.paramForm, 2, 0, 1, 1) self.layout.addWidget(self.calibrationForm, 2, 1, 1, 1) self.layout.addWidget(self.pumpForm, 2, 2, 1, 1) self.layout.addWidget(self.switchForm, 3, 1, 1, 1) self.layout.addWidget(self.defaultForm, 3, 2, 1, 1) self.layout.addWidget(self.recordForm, 3, 0, 1, 1) self.win.show() return self.win def createImageGroupBox(self): self.imageForm = QGroupBox('Imaging') self.imageLayout = QGridLayout() ##raw image self.imv1 = RawImageWidget(scaled=True) ## tracking self.imv2 = RawImageWidget(scaled=True) ## mask self.imv3 = RawImageWidget(scaled=True) ## avergae self.imv4 = RawImageWidget(scaled=True) ## set background image self.imv1.setImage(self.bkImage) self.imageLayout.addWidget(QLabel("Raw:"), 0, 0, 1, 1) self.imageLayout.addWidget(QLabel("Detection:"), 0, 1, 1, 1) self.imageLayout.addWidget(self.imv1, 1, 0, 1, 1) self.imageLayout.addWidget(self.imv2, 1, 1, 1, 1) self.imageLayout.addWidget(QLabel("Mask:"), 2, 0, 1, 1) self.imageLayout.addWidget(QLabel("Moving average:"), 2, 1, 1, 1) self.imageLayout.addWidget(self.imv3, 3, 0, 1, 1) self.imageLayout.addWidget(self.imv4, 3, 1, 1, 1) self.imageForm.setLayout(self.imageLayout) def createTextGroupBox(self): self.textForm = QGroupBox('Imaging') self.textLayout = QFormLayout() ## parameters self.maxArea_box = QtGui.QLineEdit() self.num_detected_box = QtGui.QLineEdit() self.maxArea_box.setText('0') self.num_detected_box.setText('0') hbox = QtGui.QHBoxLayout() hbox.addWidget(QLabel("max area:")) hbox.addWidget(self.maxArea_box) hboxD = QtGui.QHBoxLayout() hboxD.addWidget(QLabel("fish #:")) hboxD.addWidget(self.num_detected_box) self.textLayout.addRow(hbox) self.textLayout.addRow(hboxD) self.textForm.setLayout(self.textLayout) def createSwitchFormGroupBox(self): self.switchForm = QGroupBox("Controller") self.switchLayout = QFormLayout() ###################### #### Trial/Lights ##################### self.lightOn_btn = QtGui.QPushButton('Light On', self.win) self.lightOn_btn.clicked.connect(self.on_lightOn) self.lightOff_btn = QtGui.QPushButton('Light Off', self.win) self.lightOff_btn.clicked.connect(self.on_lightOff) self.trialOn_btn = QtGui.QPushButton('Start Trial', self.win) self.trialOn_btn.clicked.connect(self.on_trialOn) self.trialOff_btn = QtGui.QPushButton('Stop Trial', self.win) self.trialOff_btn.clicked.connect(self.on_trialOff) self.switchLayout.addRow(self.lightOn_btn, self.lightOff_btn) self.switchLayout.addRow(self.trialOn_btn, self.trialOff_btn) self.switchForm.setLayout(self.switchLayout) def createCalibrationFormGroupBox(self): self.calibrationForm = QGroupBox("Image Calibration") self.calibrationLayout = QFormLayout() self.slider = QSlider(Qt.Horizontal) self.slider.setMinimum(0) self.slider.setMaximum(255) self.slider.setValue(self.pVal) self.slider.setTickPosition(QSlider.TicksBelow) self.slider.setTickInterval(10) self.slider.valueChanged.connect(self.on_slidervaluechange) self.textSlider = QtGui.QLineEdit(str(self.pVal)) hbox_mn = QtGui.QHBoxLayout() hbox_mn.addWidget(self.slider) hbox_mn.addWidget(self.textSlider) self.slider2 = QSlider(Qt.Horizontal) self.slider2.setMinimum(0) self.slider2.setMaximum(255) self.slider2.setValue(self.pVal_mx) self.slider2.setTickPosition(QSlider.TicksBelow) self.slider2.setTickInterval(10) self.slider2.valueChanged.connect(self.on_slider2valuechange) self.textSlider2 = QtGui.QLineEdit(str(self.pVal_mx), self.win) hbox_mx = QtGui.QHBoxLayout() hbox_mx.addWidget(self.slider2) hbox_mx.addWidget(self.textSlider2) self.ROIslider = QSlider(Qt.Horizontal) self.ROIslider.setMinimum(0) self.ROIslider.setMaximum(1000) self.ROIslider.setValue(self.area_mn) self.ROIslider.setTickPosition(QSlider.TicksBelow) self.ROIslider.setTickInterval(100) self.ROIslider.valueChanged.connect(self.on_ROIslidervaluechange) self.ROItextSlider = QLineEdit(str(self.area_mn)) hbox = QtGui.QHBoxLayout() hbox.addWidget(self.ROIslider) hbox.addWidget(self.ROItextSlider) self.calibrationLayout.addRow(QLabel("ROI max area:"), hbox) self.calibrationLayout.addRow(QLabel("px min:"), hbox_mn) self.calibrationLayout.addRow(QLabel("px max:"), hbox_mx) self.calibrationForm.setLayout(self.calibrationLayout) def createPumpGroupBox(self): self.pumpForm = QGroupBox("Pump settings") self.pumpFormLayout = QFormLayout() self.flowOff1_btn = QtGui.QPushButton('Increase') self.flowOff0_btn = QtGui.QPushButton('Decrease') self.flowOn1_btn = QtGui.QPushButton('Increase') self.flowOn0_btn = QtGui.QPushButton('Decrease') self.flowOn1_btn.clicked.connect(self.on_flowOn1) self.flowOn0_btn.clicked.connect(self.on_flowOn0) self.flowOff1_btn.clicked.connect(self.on_flowOff1) self.flowOff0_btn.clicked.connect(self.on_flowOff0) self.ardReset_btn = QtGui.QPushButton('reset flow') self.ardReset_btn.clicked.connect(self.on_ARDreset) hbox = QtGui.QHBoxLayout() hbox.addWidget(self.flowOn0_btn) hbox.addWidget(self.flowOn1_btn) hboxOff = QtGui.QHBoxLayout() hboxOff.addWidget(self.flowOff0_btn) hboxOff.addWidget(self.flowOff1_btn) self.pumpFormLayout.addRow(QLabel("On time:"), hbox) self.pumpFormLayout.addRow(QLabel("Off time:"), hboxOff) self.pumpFormLayout.addRow(self.ardReset_btn) self.pumpForm.setLayout(self.pumpFormLayout) def createParamGroupBox(self): self.paramForm = QGroupBox("Trial parameters") self.paramFormLayout = QFormLayout() self.Timer_tbox = QtGui.QLineEdit() self.trialTime_tbox = QtGui.QLineEdit() self.trialTime_tbox.textChanged.connect(self.on_trialTime_changed) self.trialSleepTime_tbox = QtGui.QLineEdit() self.trialSleepTime_tbox.textChanged.connect( self.on_trialSleepTime_changed) self.trialTime_tbox.setText(str(self.trialTime)) self.trialSleepTime_tbox.setText(str(self.trialSleepTime)) self.Timer_tbox.setText(str(0)) self.paramFormLayout.addRow(QLabel("Trial time:"), self.trialTime_tbox) self.paramFormLayout.addRow(QLabel("Stimulus time:"), self.trialSleepTime_tbox) self.paramFormLayout.addRow(QLabel("Time left:"), self.Timer_tbox) self.paramFormLayout.addRow(QLabel("Time:"), QSpinBox()) self.paramForm.setLayout(self.paramFormLayout) def createDefaultGroupBox(self): self.defaultForm = QtGui.QGroupBox("Video capture") self.defaultFormLayout = QFormLayout() self.ArdPortComboBox = QComboBox() self.ArdPortComboBox.addItem("Port 14511", '/dev/cu.usbmodem14511') self.ArdPortComboBox.addItem("Port 14311", '/dev/cu.usbmodem14311') self.ArdPortComboBox.addItem("Port 1461", '/dev/cu.usbmodem1461') self.ArdPortComboBox.currentIndexChanged.connect(self.on_setARDport) self.cameraComboBox = QComboBox() self.cameraComboBox.addItem("0", '0') self.cameraComboBox.addItem("1", '1') self.cameraComboBox.currentIndexChanged.connect(self.on_setcameraport) self.start_btn = QtGui.QPushButton('start') self.start_btn.clicked.connect(self.on_start) ## stop flow button self.stop_btn = QtGui.QPushButton('stop') self.stop_btn.clicked.connect(self.on_stop) ## quit app button self.qbtn = QtGui.QPushButton('exit') self.qbtn.clicked.connect(self.on_quit) self.qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit) hbox = QtGui.QHBoxLayout() hbox.addWidget(self.start_btn) hbox.addWidget(self.stop_btn) hbox.addWidget(self.qbtn) self.defaultFormLayout.addRow(hbox) self.defaultFormLayout.addRow(QLabel("Arduino Port:"),\ self.ArdPortComboBox) self.defaultFormLayout.addRow(QLabel("camera:"),\ self.cameraComboBox) self.defaultForm.setLayout(self.defaultFormLayout) def createRecordGroupBox(self): self.recordForm = QtGui.QGroupBox("Video capture") self.recordFormLayout = QFormLayout() self.path_bx = QtGui.QLineEdit() self.resetPath() self.file_btn = QtGui.QPushButton("save to") self.file_btn.clicked.connect(self.on_getfile) self.file_bx = QtGui.QLineEdit() self.file_bx.textChanged.connect(self.on_fileChange) self.file_bx.setText(self.filename) self.save_btn = QtGui.QCheckBox() self.save_btn.setChecked(self.save) self.save_btn.stateChanged.connect(self.on_saveClick) hbox = QtGui.QHBoxLayout() self.recordFormLayout.addRow(self.file_btn, self.file_bx) self.recordFormLayout.addRow(QLabel("path:"), self.path_bx) self.recordFormLayout.addRow(QLabel("save:"), self.save_btn) self.recordForm.setLayout(self.recordFormLayout) ################# ### slots ################ @pyqtSlot() def on_getfile(self): self.foldername = QtGui.QFileDialog.getExistingDirectory() self.resetPath() @pyqtSlot() def on_fileChange(self): self.filename = self.file_bx.text() self.resetPath() @pyqtSlot() def on_setcameraport(self): self.initialise_videorecorder() @pyqtSlot() def on_trialTime_changed(self): try: self.trialTime = int(self.trialTime_tbox.text()) except: self.trialTime_tbox.setText(str(1)) print('only integrs valid') @pyqtSlot() def on_trialSleepTime_changed(self): try: self.trialSleepTime = int(self.trialSleepTime_tbox.text()) except: self.trialSleepTime_tbox.setText(str(1)) print('only integrs valid') @pyqtSlot() def on_setARDport(self): pass # if self.ARD: # self.ARDPort = self.ArdPortComboBox.currentData() # print('ARD port set to ={0}'.format(self.ARDPort)) # else: # print('no ARD detected') @pyqtSlot() def on_trialOn(self): print('trial starting') self.flowOn = False self.resetARD() self.trialTimer.restart() self.trialOn = True @pyqtSlot() def on_trialOff(self): print('trial ended') self.trialTimer.restart() self.trialOn = False self.flowOn = False self.resetARD() @pyqtSlot() def on_ARDreset(self): print('resetting ARD') self.resetFlowRate() @pyqtSlot() def on_flowOn1(self): print('changing flow rate') try: self.Ard.sendChar('u') self.resetARD() except: pass @pyqtSlot() def on_flowOn0(self): print('changing flow rate') try: self.Ard.sendChar('d') self.resetARD() except: pass @pyqtSlot() def on_flowOff1(self): print('changing flow rate') try: self.Ard.sendChar('k') self.resetARD() except: pass @pyqtSlot() def on_flowOff0(self): print('changing flow rate') try: self.Ard.sendChar('j') self.resetARD() except: pass @pyqtSlot() def on_lightOn(self): self.flowOn = True self.resetARD() @pyqtSlot() def on_lightOff(self): self.flowOn = False self.resetARD() @pyqtSlot() def on_slidervaluechange(self): self.pVal = int(self.slider.value()) self.Tracker.pVal = self.pVal self.textSlider.setText(str(self.pVal)) @pyqtSlot() def on_slider2valuechange(self): self.pVal_mx = int(self.slider2.value()) self.Tracker.pVal_mx = self.pVal_mx self.textSlider2.setText(str(self.pVal_mx)) @pyqtSlot() def on_ROIslidervaluechange(self): self.area_mn = int(self.ROIslider.value()) self.Tracker.area_mn = self.area_mn self.ROItextSlider.setText(str(self.area_mn)) @pyqtSlot() def on_start(self): if self.recording: print('current recording being stopping...') print('number of previously saved frames:\n{0}'.\ format(self.num_saved_frame)) self.recording = False sleep(0.02) try: self.recorder.release_writer() except: pass sleep(0.02) print('new recording starting...') self.initialise_videorecorder() self.recording = True @pyqtSlot() def on_saveClick(self): self.on_start() if self.save_btn.isChecked(): try: self.recorder.initialise_writer() print('writer initialised') sleep(0.02) self.save = self.save_btn.isChecked() except: print('couldn\'t initialise writer') else: try: self.recorder.release_writer() except: print('couldn\'t release writer') pass @pyqtSlot() def on_stop(self): print('current recording being stopping...') print('number of previously saved frames:\n{0}'.\ format(self.num_saved_frame)) self.recording = False self.save = False self.save_btn.setChecked(self.save) try: self.recorder.release_writer() self.num_saved_frame = 0 except: pass @pyqtSlot() def on_ROIinit(self): print('initiliase ROI') self.initialise_ROI() @pyqtSlot() def on_quit(self): print('stopping threads...') self.flowOn = False self.resetARD() self.recording = False self.trialOn = False sleep(0.5) print('number saved frames:\n{0}'.\ format(self.num_saved_frame)) try: self.recorder.release_writer() except: pass try: self.recorder.release_camera() except: pass self.recordingThread.stop() self.trialThread.stop() def resetARD(self): if self.flowOn == False: if self.ARD: print('0') self.Ard.sendChar('0') if self.flowOn == True: if self.ARD: self.Ard.sendChar('1') def resetFlowRate(self): if self.ARD: self.Ard.sendChar('r') self.resetARD() def resetPath(self): self.dt = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")[2:] self.path = self.get_path() self.path_bx.setText(self.path) def kill_threads(self): self.recording = False self.trialOn = False def start_recording(self): while self.recording: self.frame_loop() def start_trial(self): while self.trialOn: self.trial_loop() ########################## ##### Thread functions ########################## def trial_loop(self): time_ = self.trialTimer.get_time() self.time_left = self.trialTime - int(time_) self.Timer_tbox.setText(str(self.time_left)) if time_ > self.trialTime: print('new trial') self.flowOn = True self.resetARD() sleep(int(self.trialSleepTime)) self.flowOn = False self.resetARD() self.trialTimer.restart() def frame_loop(self): self.gray = self.grab_frame() self.blur = self.Tracker.blur_frame(self.gray) self.mvAvgFrame = self.update_avg() self.fD = self.Tracker.delta_frame(self.mvAvgFrame, self.blur) self.mask, self.masked = self.Tracker.mask_frame(self.fD, pVal=self.pVal, pVal_mx=self.pVal_mx) self.fD_, self.keypoints, self.num_fish_detected, self.max_a\ = self.Tracker.get_frame_contours(self.masked, self.fD) self.maxArea_box.setText(str(self.max_a)) self.num_detected_box.setText(str(self.num_fish_detected)) if self.save: self.num_saved_frame += 1 try: self.recorder.save_frame(self.gray) except: print('couldn\'t save file') self.show_frame() ########################## ##### detection functions ########################## def grab_frame(self): try: (grabbed, frame) = self.camera.read() self.frame = cv2.resize(frame, (self.imW, self.imH)) self.gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY) #self.frame = cv2.cvtColor(self.frame , cv2.COLOR_BGR2HSV)[:,:,1] # saturation except: print('couldn\'t grab frame') pass return self.gray def update_avg(self): if self.mvAvgFrame is None: self.mvAvgFrame = self.blur else: self.ite += 1 fr = self.ite if fr > 10000: print('reset') self.ite = 1 self.mvAvgFrame = self.mvAvgFrame else: self.mvAvgFrame = self.mvAvgFrame * ( fr / (fr + 1)) + self.blur / (fr + 1) return self.mvAvgFrame def show_frame(self): if self.ite % 4 == 0: self.imv1.setImage(self.gray.T) elif self.ite % 4 == 1: self.imv4.setImage(self.mvAvgFrame.T.astype('uint8')) elif self.ite % 4 == 2: self.imv2.setImage(self.fD_.swapaxes(0, 1)) elif self.ite % 4 == 3: self.imv3.setImage(self.mask.T)
def __init__(self, label): MyThread.__init__(self) self.label=label self.bridgeutil=BridgeUtils()
class MyVideoRecorder(object): def __init__(self, opt=1): #################### #### args #################### self.ap = argparse.ArgumentParser() self.default_path = '/Users/virginiarutten/Documents/deep_fish/videos' self.ap.add_argument("-v", "--video", \ default = self.default_path, help="path to the video file") self.ap.add_argument("-f", "--fps", type=str, default=str(10), help="fps") self.ap.add_argument("-p", "--path", type = str, \ default=self.default_path, help="path to which to save videos") file_name = 'test_delete' self.ap.add_argument("-n", "--name", type=str, default=file_name, help="filename") self.ap.add_argument("-r", "--resize", type=bool, default=True, help="filename") self.ap.add_argument("-c", "--cam", type=int, default=1, help="camera number") self.ap.add_argument("-t", "--max_time", type=int, default=10, help="camera number") self.ap.add_argument("-w", "--wait_time", type=int, default=100, help="camera number") if opt == 1: self.args = vars(self.ap.parse_args()) else: self.args = vars(self.ap.parse_known_args()[0]) self.wait_time = self.args['wait_time'] / 1000 self.dt = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")[2:] self.output = self.args['path'] + '/' + self.args[ 'name'] + self.dt + '.avi' #self.fps = int(self.args['fps']) self.fps = np.ceil(1 / self.wait_time) self.cam = self.args['cam'] self.resize = self.args['resize'] self.max_time = self.args['max_time'] print('output file:{0}'.format(self.output)) ################# ### settings ############### self.fourcc = cv2.VideoWriter_fourcc(*'XVID') self.imH = int(360 / 2) self.imW = int(640 / 2) self.recording = False self.initialiseCap() self.initialiseWriter() time.sleep(.2) self.grabFrame() self.initialise_window() self.show_frame() self.recording = True self.recordingThread = MyThread(self.start_recording, self.wait_time) self.recordingThread.start() self.count = 0 self.Timer = MyTimer() self.Timer.restart() def initialise_window(self): self.app = QtGui.QApplication([]) self.win = MyQtWidget() self.win.load_picture() title = 'deep fish detection' self.win.setWindowTitle(title) self.imv1 = RawImageWidget(scaled=True) self.imv1.setImage(self.win.bkImage) self.layout = QtGui.QGridLayout() self.win.setLayout(self.layout) self.layout.addWidget(self.imv1) self.win.show() def show_frame(self): tmp = self.frame.swapaxes(0, 1)[:, :, ::-1] self.imv1.setImage(tmp) def convert2gif(self): self.gif = MyGif(self.output, array, fps=self.fps, scale=1.0) def start_recording(self): while self.recording: self.record_loop() def pause(self): self.recording = False def initialiseCap(self): self.cap = cv2.VideoCapture(self.cam) def initialiseWriter(self): self.writer = cv2.VideoWriter(self.output,fourcc = self.fourcc,\ fps = self.fps, \ frameSize = (self.imW,self.imH)) def record_loop(self): tmp = self.Timer.get_time() if tmp > self.max_time: print('time limit reached') print(self.Timer.get_time()) self.recording = False self.stop() else: self.grabFrame() if self.ret: self.count += 1 if self.count % 100 == 0: print(self.count) print(self.Timer.get_time()) self.writer.write(self.frame) self.show_frame() def grabFrame(self): self.ret, self.frame = self.cap.read() if self.ret: self.frame = cv2.resize(self.frame, (self.imW, self.imH)).astype('uint8') else: print('no frame captured') pass def releaseCap(self): self.cap.release() def stop(self): print('stop function has been called') print('total time = {0}'.format(self.Timer.get_time())) print('total frames = {0}'.format(self.count)) print('approx fps = {0}'.format(int(self.count / self.Timer.get_time()))) self.recording = False self.writer.release() self.releaseCap() print('\nfile saved at:\n{0}'.format(self.output))
h = str(link['href']) n = h.replace(l + "/", "") try: a.append(int(n)) except Exception as e: print(e) _max = max(a) for i in range(1, _max): u = str(l + "/" + str(i)) url_list.append(u) return url_list if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("echo") args = parser.parse_args() url = str(args.echo) print("开始解析:" + url) html = get_html(url) soup = get_soup(html) img_dirs = get_img_dirs(soup) if None == img_dirs: print("无法获取该网页下的相册内容...") else: for d in img_dirs: my_thread = MyThread(download_imgs, (d, img_dirs.get(d))) my_thread.start() my_thread.join()
def startThread(self): #thread.Thread(target=self.recvData).start() thread1 = MyThread().createThread(self.startTCP) thread1.start() # thread2 = return thread1
#/cn/actresses/page/2 if __name__ == '__main__': i = 7 while i < 10000: url = "https://avmoo.asia/cn/actresses/page/" + str(i) print("开始解析:" + url) if 1 == i: refer = 'https://avmoo.asia/cn/actresses/2' else: refer = 'https://avmoo.asia/cn/actresses/' + str(i - 1) i = i + 1 # 女星姓名 + 跳转链接的map表 img_dirs = get_current_thumbs_list(url, refer) if None == img_dirs: print("无法获取该网页下的相册内容...") break else: for d in img_dirs: if consume_last(d): continue # print(img_dirs.get(d)) url_parser = img_dirs.get(d) # 爬取女星的资料 # download_imgs((d, url_parser, refer, [1, url_parser])) my_thread = MyThread(download_imgs, (d, url_parser, refer, [1, url_parser])) my_thread.start() my_thread.join() print("[Main], " + str(i))
def test_model(sess, minibatch): # test and validate model if conf.test_mode: run_batch(sess, mtest, test_data, tf.no_op(), minibatch) t_train = MyThread(run_batch, (sess, m, train_data, tf.no_op(), minibatch)) t_test = MyThread(run_batch, (sess, mtest, test_data, tf.no_op(), minibatch)) t_val = MyThread(run_batch, (sess, mval, val_data, tf.no_op(), minibatch)) t_train.start() t_test.start() t_val.start() t_train.join() result_train = t_train.get_result() t_test.join() result_test = t_test.get_result() t_val.join() result_val = t_val.get_result() result = result_train + result_test + result_val monitor.new(result, minibatch) return result
def Principal_function(messagerow,soup,route,subtitle,response,movie_type,Complete): medium = messagerow[0] code = messagerow[1] resolving_power = messagerow[2] Audio_coding = messagerow[3] region = messagerow[4] Production_team = messagerow[5] info = vidioparme(soup) judge_info='' if info[0] ==False: info=str(info[1]) judge_info = '===info错误,没用quote括起来' else: info=str(info) x_info = re.findall('data-cfemail="(.*)" href="/cdn-cgi/l/email-protection', info) if x_info: email_ = email_jimi(x_info[0]) info = re.sub('<a class="__cf_email__".*>', email_, info) title = title_get(soup) title_check_ans = title_check(title) # 创建9个线程 task = MyThread(medium_check_All, (route, medium, info, title, soup)) task2 = MyThread(check_code_All, (code, info, medium, route, title)) task3 = MyThread(check_Audio_coding_All, (Audio_coding, info, Production_team, title)) task4 = MyThread(check_resolving_power_All, (resolving_power, info, medium, route, title,movie_type)) task5 = MyThread(check_region_all, (soup, region)) task6 = MyThread(team_processing, (route, medium, title,info)) task7 = MyThread(tag_check, (title, response, medium, subtitle, info, Production_team,Complete,region)) task8 = MyThread(link_check, (soup, response)) task9=MyThread(movie_type_check_All,(movie_type, medium, resolving_power, title)) #task10=MyThread(img_check,(soup,imgheaders)) task.start(),task2.start(),task3.start(),task4.start(),task5.start(),task6.start() task7.start(),task8.start(),task9.start(), task.join() task2.join() task3.join() task4.join() task5.join() task6.join() task7.join() task8.join() task9.join() if title_check_ans: title = title + title_check_ans return title, subtitle, task9.get_result(), messagerow, task.get_result(),task2.get_result(),task3.get_result(),\ task4.get_result(),task5.get_result(),task6.get_result(),task7.get_result(),task8.get_result()+judge_info
URL TEXT NOT NULL);''') print "GALLERY Table created successfully"; conn.execute('''CREATE TABLE IF NOT EXISTS PHOTO (ID INTEGER PRIMARY KEY AUTOINCREMENT, GALLERY INTEGER NOT NULL, URL TEXT NOT NULL);''') print "PHOTO Table created successfully"; parser = argparse.ArgumentParser() parser.add_argument("echo") # parser.add_argument("url") # url = int(args.url) args = parser.parse_args() url = str(args.echo) print("开始解析:" + url) html = get_html(url) soup = get_soup(html) img_dirs = get_img_dirs(soup) if None == img_dirs: print("无法获取该网页下的相册内容...") else: for d in img_dirs: my_thread = MyThread(fetch_imgs, (d, img_dirs.get(d))) my_thread.start() my_thread.join()
def test_model(sess, minibatch): # test and validate model if conf.test_mode: run_batch(sess, mtest, test_data, tf.no_op(), minibatch) t_train = MyThread(run_batch, (sess, m, train_data, tf.no_op(), minibatch)) t_test = MyThread(run_batch, (sess, mtest, test_data, tf.no_op(), minibatch)) t_val = MyThread(run_batch, (sess, mval, val_data, tf.no_op(), minibatch)) t_train.start() t_test.start() t_val.start() t_train.join() result_train = t_train.get_result() t_test.join() result_test = t_test.get_result() t_val.join() result_val = t_val.get_result() print("Train cost {0:0.3f}, Acc {1:0.3f}".format(result_train[0], result_train[1])) print("Valid cost {0:0.3f}, Acc {1:0.3f}".format(result_val[0], result_val[1])) print("Test cost {0:0.3f}, Acc {1:0.3f}".format(result_test[0], result_test[1])) return result_train + result_test + result_val
def add_new_pic(face_recognization): while True: # 直接请求本地的服务,加入LSH Forest face_recognization.add_all_new_pic() time.sleep(10) if __name__ == "__main__": sub_process_id = '' try: face_recognition = FaceRecognition() face_recognition.load_all_data() application = tornado.web.Application([ (r"/", MainHandler), ]) add_new_pic_args = (face_recognition, ) add_new_pic_thread = MyThread(func=add_new_pic, args=add_new_pic_args, name='add_new_pic') add_new_pic_thread.start() application.listen(port) tornado.ioloop.IOLoop.instance().start() add_new_pic_thread.join() except: traceback.print_exc()
class MyApp: def __init__(self): ## 변수 self.key = "" self.apiGetter = LolApiGetter() self.popupMaker = PopupMaker() self.nickname = "" ## 쓰레드 self.t = MyThread() self.t.daemon = True # 부모 종료 시 같이 종료 self.t.setApiGetter(self.apiGetter) self.t.setPopupMaker(self.popupMaker) ## UI self.root = Tk() self.main_frame = Frame(self.root) self.main_frame.pack() self.label = Label(self.main_frame, text="API KEY") self.label.pack() self.txt_key = Entry(self.main_frame) self.txt_key.pack() self.label2 = Label(self.main_frame, text="소환사 이름") self.label2.pack() self.txt = Entry(self.main_frame) self.txt.pack() self.btn_ok = Button(self.main_frame, text="OK", command=self.setNicknameByBtn) self.btn_ok.pack() self.txt.focus_force() self.root.mainloop() def setNicknameByBtn(self): self.nickname = self.txt.get() self.apiGetter.setApiKey(self.txt_key.get()) if self.nickname == "": messagebox.showinfo("알림", "닉네임을 입력해주세요") else: messagebox.showinfo("이름", self.nickname) self.main_frame.destroy() self.main_frame = Frame(self.root) self.main_frame.pack() new_label = Label(self.main_frame, text="실행중") new_label.pack() self.t.setNickname(self.nickname) self.t.start() def tt(self): toplevel = Toplevel() frame = Frame(toplevel, background="white") frame.pack(side=LEFT) name_label = Label(frame, text="name", background="white") name_label.pack() tier_label = Label(frame, text="tier", background="white") tier_label.pack() toplevel.attributes('-topmost', 'true') toplevel.after(3000, lambda: toplevel.destroy())
def client_main(bg, screen, WINDOW_W, WINDOW_H, SERVER_ADDR, SERVER_PORT_DISP, player_name): # Инициация PyGame, обязательная строчка #pygame.init() #pygame.event.set_allowed([pygame.QUIT, pygame.KEYDOWN, pygame.KEYUP]) # инициализация окна #bg, screen = window_init(WINDOW_W, WINDOW_H, "#000000", "PyTanks") label_bg = Surface((WINDOW_W,WINDOW_H)) label_bg.fill((54,64,74)) # группы объектов players = pygame.sprite.Group() players_bullets = pygame.sprite.Group() # создаем асинхронный клиент game_client = Client((SERVER_ADDR, SERVER_PORT_DISP)) # запускаем цикл опроса сокетов socket_loop_thread = MyThread(asyncore.loop, [0.01]) socket_loop_thread.start() # отправляем серверу свое имя #message = pack_data(player_name) #game_client.obuffer = message # получаем собственный идентификатор #while len(game_client.imes) <= 0: #time.sleep(1) #my_id = player_name my_id = game_client.addr[1] # получаем первоначальную инфу flag = True while flag: if len(game_client.imes) > 0: data = game_client.imes.pop(0) if 'params' in data.keys(): init_data = data flag = False #print(game_client.imes) #init_data = game_client.imes.pop(0) FRAME_RATE = init_data['params']['frame_rate'] #['params'] = {'total_width': total_level_width, 'total_height': total_level_height, 'width': level_width, # 'height': level_height, 'block_demage': BLOCK_DEMAGE} # генерируем уровень total_level_width = init_data['params']['total_width'] total_level_height = init_data['params']['total_height'] blocks = gen_client_level(init_data['blocks'], init_data['params']['block_demage']) # создаем героев # {'id' : player.addr[0], 'x' : player.sprite.rect.x, 'y' : player.sprite.rect.y, # 'team' : player.team, 'dead_count': player.config.dead_count} players_list = init_data['players'] for player_item in players_list: x = player_item['x'] y = player_item['y'] id = player_item['id'] team = player_item['team'] dead_count = player_item['dead_count'] tank_config = Tank_config(x, y, dead_count) player = Tank(tank_config, id, team, 0) players.add(player) if id == my_id: i_am = player #создаем камеру camera = Camera(camera_configure, total_level_width, total_level_height, WINDOW_W, WINDOW_H) # таймер timer = pygame.time.Clock() # надпись font = pygame.font.Font('freesansbold.ttf', 12) dropped_frames = 0 empty_queue = 0 # Основной цикл программы while 1: if game_client.socket._closed: #pygame.quit() return timer.tick(FRAME_RATE) # таймер на 30 кадров # отправляем произошедшие события на сервер event_queue = [] for e in pygame.event.get(): # выход if e.type == pygame.QUIT or (e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE): #pygame.quit() # упаковываем данные message = pack_data("exit") game_client.obuffer = message game_client.close() return # нажатие клавиши на клавиатуре if (e.type == pygame.KEYDOWN) or (e.type == pygame.KEYUP): event_item = {'type': e.type, 'key': e.key} event_queue.append(event_item) # упаковываем данные out_data = {'id': my_id, 'name': player_name, 'events': event_queue} message = pack_data(out_data) game_client.obuffer = message # получаем очередной пакет данных l = len(game_client.imes) if l > 0: if l > MAX_LEN_QUEUE: game_client.imes = game_client.imes[-MAX_LEN_QUEUE:] dropped_frames += (l - 3) dataframe = game_client.imes.pop(0) else: dataframe = {'blocks': [], 'players': [], 'bullets': [], 'disconnected': []} empty_queue += 1 #блоки dataframe["blocks"] = {"id" : b.id, "shootdirection" : b.shootdirection} blocks_list = dataframe['blocks'] for block_data in blocks_list: for block in blocks.sprites(): if block.id == block_data['id']: block.die(block_data['shootdirection']) break # dataframe['disconnected'] - отключившиеся игроки disconnected = dataframe['disconnected'] for player in players.sprites(): if player.id in disconnected: player.kill() # игроки dataframe["players"] = {'id': player.id, 'name': player.name, 'x': player.sprite.rect.x, 'y': player.sprite.rect.y, # 'course': player.sprite.course, 'shutdirection': player.sprite.shutdirection, # 'dead': player.sprite.dead, 'team' : player.team, 'dead_count': player.sprite.config.dead_count, # 'frag': player.sprite.frag} players_list = dataframe['players'] for player_item in players_list: found = False for player in players.sprites(): if player.id == player_item['id']: player.name = player_item['name'] player.update(player_item['x'], player_item['y'], player_item['course'], player_item['shutdirection'], player_item['dead'], player_item['frag']) found = True break if not found: x = player_item['x'] y = player_item['y'] id = player_item['id'] team = player_item['team'] dead_count = player_item['dead_count'] frag = player_item['frag'] tank_config = Tank_config(x, y, dead_count) new_player = Tank(tank_config, id, team, frag) players.add(new_player) # пули #{'id': b.id, 'x': b.rect.x, 'y': b.rect.y, 'shutdirection' : b.shutdirection, 'bum': b.bum} bullets_list = dataframe['bullets'] for bullet_item in bullets_list: id = bullet_item['id'] x = bullet_item['x'] y = bullet_item['y'] shutdirection = bullet_item['shutdirection'] bum = bullet_item['bum'] found = False for b in players_bullets.sprites(): if b.id == id: found = True b.update(x, y, bum) break if not found: b = Bullet(id, x, y, shutdirection) players_bullets.add(b) camera.update(i_am, WINDOW_W, WINDOW_H) # центризируем камеру относительно персонажа # Каждую итерацию необходимо всё перерисовывать screen.blit(bg, (0,0)) # рисование блоков entities = blocks.sprites() for e in entities: screen.blit(e.image, camera.apply(e)) # рисование танков entities = players.sprites() for e in entities: topleft = camera.apply(e) screen.blit(e.image, topleft) if e.team == "green": label = font.render(e.name, True, Color("green")) else: label = font.render(e.name, True, Color("yellow")) screen.blit(label, (topleft[0], topleft[1]+28)) # рисование пуль entities = players_bullets.sprites() for e in entities: screen.blit(e.image, camera.apply(e)) # выводим списки игроков screen.blit(label_bg, (WINDOW_W,0)) i = 30 team_count = 0 for player in players: if player.team == "yellow": team_count += player.frag label = font.render(" " + player.name + " ["+str(player.frag)+"]", True, Color("yellow")) screen.blit(label, (WINDOW_W, i)) i+=20 i += 20 label = font.render(' YELLOW team: '+ str(team_count), True, Color("yellow")) screen.blit(label, (WINDOW_W, 10)) team_count = 0 l_x = i i += 20 for player in players: if player.team == "green": team_count += player.frag label = font.render(" " + player.name + " ["+str(player.frag)+"]", True, Color("green")) screen.blit(label, (WINDOW_W, i)) i+=20 label = font.render(' GREEN team: '+ str(team_count), True, Color("green")) screen.blit(label, (WINDOW_W, l_x)) # выводим строчки со служебной инфой label = font.render(' fps=%.2f ' % timer.get_fps(), True, (255,255,255)) screen.blit(label, (WINDOW_W, WINDOW_H - 60)) label = font.render(' len_queue=%d ' % len(game_client.imes), True, (255,255,255)) screen.blit(label, (WINDOW_W, WINDOW_H - 45)) label = font.render(' dropped_frames=%d ' % dropped_frames, True, (255,255,255)) screen.blit(label, (WINDOW_W, WINDOW_H - 30)) label = font.render(' empty_queue=%d ' % empty_queue, True, (255,255,255)) screen.blit(label, (WINDOW_W, WINDOW_H - 15)) # обновление и вывод всех изменений на экран pygame.display.update()
def __init__(self, label,ip,port): MyThread.__init__(self) self.m_label=label self.m_ip=ip self.m_port=port