def getView(self, dis): # 管理员数据字典 with QMutexLocker(self._Mlock): self.accoutDatabase = { self.face_thread.database.account_num[i]: self.face_thread.database.password[i] for i in range(len(self.face_thread.database.account_num)) } account, ok = QInputDialog.getText(self, 'Account Input', 'Please enter the account number:') secret, bingo = QInputDialog.getText( self, 'secret Input', 'Please enter the secret number:') if ok and bingo: if account in self.accoutDatabase.keys(): if secret == self.accoutDatabase.get(account): if dis: if self.pushButton_2.isEnabled( ) and self.Register_Button.isEnabled(): self.logicalDisplaySignal.emit( self.signal_OpenEvent) else: pass return True else: return "账号或者密码不正确" else: return "账号或者密码不正确" pass else: return False
def __loadQtHelpPage(self, url): """ Private method to load the requested QtHelp page. @param url URL of the requested page @type QUrl """ if self.__engine.findFile(url).isValid(): data = self.__engine.fileData(url) else: data = QByteArray( self.tr("""<html>""" """<head><title>Error 404...</title></head>""" """<body><div align="center"><br><br>""" """<h1>The page could not be found</h1><br>""" """<h3>'{0}'</h3></div></body>""" """</html>""").format(url.toString()).encode("utf-8")) lock = QMutexLocker(self.__mutex) self.__buffer.setData(data) self.__buffer.open(QIODevice.ReadOnly) self.open(QIODevice.ReadOnly) lock.unlock() self.readyRead.emit()
def readData(self): """SLOT: readData Reads data from the serial port when it's available Expects: none Connects to: QSerialPort.readyRead Emits: newDataAvailable """ with QMutexLocker(self.lock): bytesIn = self.serialPort.readAll() for b in bytesIn: if b == b'\n': # This translates to the \n character which means the message is complete msg = self.buffer.decode().strip() self.displayRXMessage.emit(msg) if msg == "ready": self.ready.emit() else: self.newDataAvailable.emit(float(msg)) self.printStatus.emit("Serial read complete") self.buffer = bytearray() # Clear buffer elif b != b'\r': # Ignore '\r' character too self.buffer = self.buffer + b
def add(self, deviceUrl, imageBuffer, sync=False): # Device stream is to be synchronized if sync: with QMutexLocker(self.mutex): self.syncSet.add(deviceUrl) # Add image buffer to map self.imageBufferDict[deviceUrl] = imageBuffer
def receiveSignalHandle(self, state): if state == self.Register_FINISHSINGAL: if len(self.registerlist) > 0: with QMutexLocker(self._Mlock): self.face_thread.database.insertRow( self.registerlist, self.ACCOUNT_INFO) # 删除默认密码 self.face_thread.database.loadDataBase(self.ACCOUNT_INFO) if len(self.face_thread.database.keyid) == 0: self.face_thread.database.insertRow( ['123', '1234', '-1'], self.ACCOUNT_INFO) elif (len(self.face_thread.database.keyid) > 1 and '123' in self.face_thread.database.account_num): self.face_thread.database.deleteRow( '123', self.ACCOUNT_INFO) self.face_thread.database.loadDataBase(self.ACCOUNT_INFO) self.faceCapSignal.emit(False) self.Register_Button.setEnabled(True) self.videoLabel.setPixmap(QPixmap.fromImage(self.videoPicture)) if state == self.Register_FAILED: QMessageBox.critical(self, '注册失败', '人脸已经存在或没有识别到人脸,请靠近摄像头') self.faceCapSignal.emit(False) self.Register_Button.setEnabled(True) self.videoLabel.setPixmap(QPixmap.fromImage(self.videoPicture)) pass
def start(self, fn): """ Public slot to start the svn blame command. @param fn filename to show the blame for (string) """ self.blameList.clear() self.errorGroup.hide() self.activateWindow() dname, fname = self.vcs.splitPath(fn) locker = QMutexLocker(self.vcs.vcsExecutionMutex) cwd = os.getcwd() os.chdir(dname) try: annotations = self.client.annotate(fname) locker.unlock() for annotation in annotations: author = annotation["author"] line = annotation["line"] if sys.version_info[0] == 2: author = author.decode('utf-8') line = line.decode('utf-8') self.__generateItem( annotation["revision"].number, author, annotation["number"] + 1, line) except pysvn.ClientError as e: locker.unlock() self.__showError(e.args[0] + '\n') self.__finish() os.chdir(cwd)
def startNewRecording(self, countchannel, triggerchannel, binwidth, roistart, roistop, filename=None): logger = logging.getLogger(__name__) with QMutexLocker(self.Mutex): command = struct.pack('>BB', 0x12, 0) self.Connection.write(command) self.channel = countchannel self.triggerchannel = triggerchannel self.binwidth = binwidth self.roistart = roistart self.roistop = roistop self.numberOfBins = (roistop - roistart) / binwidth + 1 self.histogram = numpy.zeros(self.numberOfBins) logger.info("command {0:x}".format(0xff & (1 << self.channel | 1 << self.triggerchannel))) self.clearStatus() command = struct.pack( '>BB', 0x12, 0xff & (1 << self.channel | 1 << self.triggerchannel)) self.Connection.write(command) if self.filename != filename: if self.binfile is not None: self.binfile.close() if filename is not None: self.binfile = open(filename, 'wb') else: self.binfile = None self.filename = filename
def updateImage(self): locker = QMutexLocker(self.mutex) if not self.isRunning(): self.start(QThread.LowPriority) else: self.restart = True self.condition.wakeOne()
def setLogsText(self, textJACK, textA2J, textLASH, textLADISH): QMutexLocker(self.fTextLock) self.fTextJACK = textJACK self.fTextA2J = textA2J self.fTextLASH = textLASH self.fTextLADISH = textLADISH
def slot_updateLogs(self): QMutexLocker(self.fTextLock) if self.fFirstRun: self.ui.pte_jack.clear() self.ui.pte_a2j.clear() self.ui.pte_lash.clear() self.ui.pte_ladish.clear() if self.LOG_FILE_JACK and self.fTextJACK: self.ui.pte_jack.appendPlainText(self.fTextJACK) if self.LOG_FILE_A2J and self.fTextA2J: self.ui.pte_a2j.appendPlainText(self.fTextA2J) if self.LOG_FILE_LASH and self.fTextLASH: self.ui.pte_lash.appendPlainText(self.fTextLASH) if self.LOG_FILE_LADISH and self.fTextLADISH: self.ui.pte_ladish.appendPlainText(self.fTextLADISH) if self.fFirstRun: self.ui.pte_jack.horizontalScrollBar().setValue(0) self.ui.pte_jack.verticalScrollBar().setValue(self.ui.pte_jack.verticalScrollBar().maximum()) self.ui.pte_a2j.horizontalScrollBar().setValue(0) self.ui.pte_a2j.verticalScrollBar().setValue(self.ui.pte_a2j.verticalScrollBar().maximum()) self.ui.pte_lash.horizontalScrollBar().setValue(0) self.ui.pte_lash.verticalScrollBar().setValue(self.ui.pte_lash.verticalScrollBar().maximum()) self.ui.pte_ladish.horizontalScrollBar().setValue(0) self.ui.pte_ladish.verticalScrollBar().setValue(self.ui.pte_ladish.verticalScrollBar().maximum()) self.fFirstRun = False
def stopRecording(self): with QMutexLocker(self.Mutex): command = struct.pack('>BB', 0x12, 0) self.Connection.write(command) if self.binfile is not None: self.binfile.close() self.binfile = None
def __loadPage(self): """ Private method to load the requested page. """ if self.__loaded: return lock = QMutexLocker(self.__mutex) if self.__pageName == "adblock": contents = self.__adBlockPage() elif self.__pageName in ["home", "start", "startpage"]: contents = self.__startPage() elif self.__pageName == "speeddial": contents = self.__speedDialPage() else: contents = "" self.__buffer.setData(contents.encode("utf-8")) self.__buffer.open(QIODevice.ReadOnly) self.open(QIODevice.ReadOnly) lock.unlock() self.readyRead.emit() self.__loaded = True
def on_ignore_clicked(self, file_name): """ Stop watching a single file until next save """ #print(f'on_ignore_clicked {file_name} in', QThread.currentThread().objectName()) with QMutexLocker(self._mutex): self.blacklist.add(file_name)
def interceptRequest(self, info): """ Public method handling an URL request. @param info URL request information @type QWebEngineUrlRequestInfo """ locker = QMutexLocker(self.__mutex) # __IGNORE_WARNING__ # Do Not Track feature if self.__doNotTrack: info.setHttpHeader(b"DNT", b"1") info.setHttpHeader(b"X-Do-Not-Track", b"1") # Send referrer header? if info.requestUrl().host() not in Preferences.getWebBrowser( "SendRefererWhitelist"): self.__setRefererHeader(info) # User Agents header userAgent = WebBrowserPage.userAgentForUrl(info.requestUrl()) info.setHttpHeader(b"User-Agent", userAgent.encode()) for interceptor in self.__interceptors: interceptor.interceptRequest(info)
def run(self): self._abort = False self._camera.start_video_capture() while True: with QMutexLocker(self._mutex): if self._abort: self._camera.stop_video_capture() break data = self._camera.get_video_data() whbi = self._camera.get_roi_format() shape = [whbi[1], whbi[0]] if whbi[3] == zwoasi.ASI_IMG_RAW8 or whbi[3] == zwoasi.ASI_IMG_Y8: img = np.frombuffer(data, dtype=np.uint8) elif whbi[3] == zwoasi.ASI_IMG_RAW16: img = np.frombuffer(data, dtype=np.uint16) elif whbi[3] == zwoasi.ASI_IMG_RGB24: img = np.frombuffer(data, dtype=np.uint8) shape.append(3) else: raise ValueError('Unsupported image type') img = img.reshape(shape) img = np.rot90(img, 2) self.ndarray_available.emit(img)
def is_stopped(self): """ 线程状态是否是停止 :return: """ with QMutexLocker(self.mutex): return self.stopped
def start(self, path): """ Public slot to populate the data. @param path directory name to show change lists for (string) """ self.changeListsDict = {} self.cancelled = False self.filesLabel.setText( self.tr("Files (relative to {0}):").format(path)) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() locker = QMutexLocker(self.vcs.vcsExecutionMutex) try: entries = self.client.get_changelist(path, depth=pysvn.depth.infinity) for entry in entries: file = entry[0] changelist = entry[1] if sys.version_info[0] == 2: file = file.decode('utf-8') changelist = changelist.decode('utf-8') if changelist not in self.changeListsDict: self.changeListsDict[changelist] = [] filename = file.replace(path + os.sep, "") if filename not in self.changeListsDict[changelist]: self.changeListsDict[changelist].append(filename) except pysvn.ClientError as e: locker.unlock() self.__showError(e.args[0]) self.__finish()
def run(self): self._abort = False while True: with QMutexLocker(self._mutex): if self._abort: break frame = self.frame self.frame = None pixel_format = frame.pixelFormat() image_format = QVideoFrame.imageFormatFromPixelFormat(pixel_format) if image_format == QImage.Format_Invalid: qDebug("WARNING: Could not convert video frame to image!") return if not frame.map(QAbstractVideoBuffer.ReadOnly): qDebug("WARNING: Could not map video frame!") return width = frame.width() height = frame.height() bytes_per_line = frame.bytesPerLine() image = QImage(frame.bits(), width, height, bytes_per_line, image_format) image = image.convertToFormat(QImage.Format_RGB32) frame.unmap() # fix upside-down data for windows if platform.system() == "Windows": image = image.mirrored(vertical=True) # now convert QImage to ndarray pointer = image.constBits() pointer.setsize(image.byteCount()) array = np.array(pointer).reshape(image.height(), image.width(), 4) # get rid of the transparency channel and organize the colors as rgb # NB: it would be safer to figure out the image format first, and where the transparency channel is # stored... array = array[:, :, 0:3:][:, :, ::-1] self.ndarray_available.emit(array) # see if new data is available, go to sleep if not with QMutexLocker(self._mutex): if self.frame is None: self._condition.wait(self._mutex)
def process_frame(self, frame: QVideoFrame): with QMutexLocker(self._mutex): self.frame = frame if not self.isRunning(): self.start() else: self._condition.wakeOne()
def requestNewFortune(self, hostname, port): locker = QMutexLocker(self.mutex) self.hostName = hostname self.port = port if not self.isRunning(): self.start() else: self.cond.wakeOne()
def updateImageProcessingFlags(self, imgProcFlags): with QMutexLocker(self.processingMutex): self.imgProcFlags.grayscaleOn = imgProcFlags.grayscaleOn self.imgProcFlags.smoothOn = imgProcFlags.smoothOn self.imgProcFlags.dilateOn = imgProcFlags.dilateOn self.imgProcFlags.erodeOn = imgProcFlags.erodeOn self.imgProcFlags.flipOn = imgProcFlags.flipOn self.imgProcFlags.cannyOn = imgProcFlags.cannyOn
def stop(self): """ 线程停止 :return: """ # 互斥锁 with QMutexLocker(self.mutex): self.stopped = True
def run(self): with QMutexLocker(self.mutex): self.stopped = False while True: if self.stopped: return self.timeSignal.signal.emit("1") time.sleep(1 / self.frequent)
def bind_thread(self, thread): with QMutexLocker(self.mutex): self.sync_devices.add(thread.device_id) shape = project_shapes[thread.camera_model.camera_name] self.current_frames[thread.device_id] = np.zeros( shape[::-1] + (3, ), np.uint8) thread.proc_buffer_manager = self
def execute(self, function, *args, **kwargs): locker = QMutexLocker(self.mutex) self.function = function self.args = args self.kwargs = kwargs self.done = False self.start()
def bytesAvailable(self): """ Public method to get the number of available bytes. @return number of available bytes @rtype int """ lock = QMutexLocker(self.__mutex) # __IGNORE_WARNING__ return self.__buffer.bytesAvailable()
def readData(self, maxlen): """ Public method to retrieve data from the reply object. @param maxlen maximum number of bytes to read (integer) @return string containing the data (bytes) """ lock = QMutexLocker(self.__mutex) # __IGNORE_WARNING__ return self.__buffer.read(maxlen)
def on_file_saved(self, file_name): """ Remove file from blacklist, update mtime """ #print(f'on_file_saved {file_name} in', QThread.currentThread().objectName()) with QMutexLocker(self._mutex): self.blacklist = set([f for f in self.blacklist if f != file_name]) self.on_file_open(file_name)
def onFinishRegister(self): if self.flag_registed == True: dir = self.PATH_FACE + self.name for file in os.listdir(dir): os.remove(dir + "/" + file) print("已删除已录入人脸的图片", dir + "/" + file) os.rmdir(self.PATH_FACE + self.name) print("已删除已录入人脸的姓名文件夹", dir) self.initData() return if self.pic_num > 0: pics = os.listdir(self.PATH_FACE + self.name) feature_list = [] feature_average = [] for i in range(len(pics)): pic_path = self.PATH_FACE + self.name + "/" + pics[i] print("正在读的人脸图像:", pic_path) img = iio.imread(pic_path) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) dets = self.detector(img_gray, 1) if len(dets) != 0: shape = self.predictor(img_gray, dets[0]) face_descriptor = self.facerec.compute_face_descriptor( img_gray, shape) feature_list.append(face_descriptor) else: face_dssaescriptor = 0 print("未在照片中识别到人脸") if len(feature_list) > 0: for j in range(128): # 防止越界 feature_average.append(0) for i in range(len(feature_list)): feature_average[j] += feature_list[i][j] feature_average[j] = ( feature_average[j]) / len(feature_list) # 数据库写入 with QMutexLocker(self._mutex): self.database.insertRow( [self.id, self.name, feature_average], self.WORKER_INFO) print("写入数据库成功") # 删除处理图片的缓存 if True: dir = self.PATH_FACE + self.name for file in os.listdir(dir): os.remove(dir + "/" + file) print("已删除已录入人脸的图片", dir + "/" + file) os.rmdir(self.PATH_FACE + self.name) print("已删除已录入人脸的姓名文件夹", dir) self.initData() return pass else: os.rmdir(self.PATH_FACE + self.name) print("已删除空文件夹", self.PATH_FACE + self.name) self.initData()
def consume(self): # when this goes out of scope the lock is opened locker = QMutexLocker(QdImageLoader._mutex) if self._index == len(self._paths): return None path = self._paths[self._index] self._index += 1 return path