def fill_flag(win): pix = QPixmap() p = QPainter() p.begin(win.image) #p.setPen(QPen(col_one)) fill_extrem(win) FindPoints(win) #Sorter() #print(scan_dots) for i in range(len(scan_dots)): for j in range(0, 560): if (j > scan_dots[i][0]): #p.drawLine(scan_dots[i][0], scan_dots[i][1], scan_dots[i + 1][0], scan_dots[i + 1][1]) col = QColor(win.image.pixel(j, scan_dots[i][1])) if col == col_zero: p.setPen(QPen(col_one)) else: p.setPen(QPen(col_zero)) #p.drawLine(scan_dots[i][0], scan_dots[i][1], 581, scan_dots[i][1]) p.drawPoint(j, scan_dots[i][1]) if win.delay.isChecked(): delay() pix.convertFromImage(win.image) win.scene.addPixmap(pix) if not win.delay.isChecked(): pix.convertFromImage(win.image) win.scene.addPixmap(pix) #pix.convertFromImage(win.image) #win.scene.addPixmap(pix) p.end()
def trace_edge(self, edge): if edge.l.y() == edge.r.y(): return if edge.l.y() > edge.r.y(): edge.l, edge.r = edge.r, edge.l step_x = (edge.r.x() - edge.l.x()) / (edge.r.y() - edge.l.y()) x = edge.l.x() y = edge.l.y() pix = QPixmap() painter = QPainter() painter.begin(self.image) painter.setPen(QColorConstants.Green) while y < edge.r.y(): if QColor(self.image.pixel(int(x) + 1, y)) != QColorConstants.Green: painter.drawPoint(int(x) + 1, y) else: painter.drawPoint(int(x), y) x += step_x y += 1 painter.end() pix.convertFromImage(self.image) self.scene.addPixmap(pix)
def draw_circle(win): count = win.CountBox.value() step = win.StepBox.value() x = win.RXspinBox.value() y = win.RYspinBox.value() r = win.RRspinBox.value() #win.image.fill(win.color_bground) start = time.clock() for i in range(count): if win.canonButton.isChecked(): al.circle_canon(win, x, y, r) if win.paramButton.isChecked(): al.circle_param(win, x, y, r) if win.brezButton.isChecked(): al.circle_brez(win, x, y, r) if win.middleButton.isChecked(): al.circle_middle(win, x, y, r) if win.libraryButton.isChecked(): win.scene.addEllipse(x - r, y - r, r * 2, r * 2, win.pen) r += step end = time.clock() print(end - start) if not win.libraryButton.isChecked(): pix = QPixmap(511, 511) pix.convertFromImage(win.image) win.scene.addPixmap(pix)
def cvToPix(self, img): img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) qImg = QImage(img.data, img.shape[1], img.shape[0], img.strides[0], QImage.Format_RGB888) qpix = QPixmap() qpix.convertFromImage(qImg) return qpix
def add_pages(self): # 请求文件 if not self.file: message_label = QLabel('没有文件.') self.page_container.layout().addWidget(message_label) return try: response = requests.get(self.file) doc = fitz.Document(filename='a', stream=response.content) except Exception as e: message_label = QLabel('获取文件内容失败.\n{}'.format(e)) self.page_container.layout().addWidget(message_label) return for page_index in range(doc.pageCount): page = doc.loadPage(page_index) page_label = QLabel() # page_label.setMinimumSize(self.width() - 20, self.height()) # 设置label大小 # show PDF content zoom_matrix = fitz.Matrix(1.5, 1.5) # 图像缩放比例 pagePixmap = page.getPixmap( matrix=zoom_matrix, alpha=False) imageFormat = QImage.Format_RGB888 # get image format pageQImage = QImage( pagePixmap.samples, pagePixmap.width, pagePixmap.height, pagePixmap.stride, imageFormat) # init QImage page_map = QPixmap() page_map.convertFromImage(pageQImage) page_label.setPixmap(page_map) page_label.setScaledContents(True) # pixmap resize with label self.page_container.layout().addWidget(page_label)
def draw(win): win.scene.clear() win.image.fill(black) tx = win.dial_x.value() ty = win.dial_y.value() tz = win.dial_z.value() if win.funcs.currentText() == "cos(x) * sin(z)": f = f1 if win.funcs.currentText() == "2 * cos(x * z)": f = f2 if win.funcs.currentText() == "exp(sin(sqrt(x^2 + z^2)))": f = f3 if win.funcs.currentText() == "x^2 / 20 + z^2 / 20": f = f4 if win.funcs.currentText() == "|sin(x) * sin(z)|": f = f5 win.image = float_horizon(win.scene.width(), win.scene.height(), win.x_min.value(), win.x_max.value(), win.dx.value(), win.z_min.value(), win.z_max.value(), win.dz.value(), tx, ty, tz, f, win.image) pix = QPixmap() pix.convertFromImage(win.image) win.scene.addPixmap(pix)
def draw_line(win): xn = int(win.xn.text()) yn = int(win.yn.text()) xk = int(win.xk.text()) yk = int(win.yk.text()) set_color_line(win) # set_color_bg(win) if win.cda.isChecked(): start = time.clock() dda(win, xn, yn, xk, yk) end = time.clock() if win.br_float.isChecked(): start = time.clock() brez_float(win, xn, yn, xk, yk) end = time.clock() if win.br_int.isChecked(): start = time.clock() brez_int(win, xn, yn, xk, yk) end = time.clock() if win.br_smooth.isChecked(): start = time.clock() brez_smooth(win, xn, yn, xk, yk) end = time.clock() pix = QPixmap(500, 500) pix.convertFromImage(win.image) win.scene.addPixmap(pix)
def on_image_captured(self, id, captured_image): # The image to be displayed on screen self.captured2pixmap = QPixmap() success = self.captured2pixmap.convertFromImage(captured_image) self.list_pic_stats() self.thumb_scaled = self.captured2pixmap.scaled( self.picframe_width, self.picframe_height, Qt.KeepAspectRatio) self.ui.ThumbnailView.setScaledContents(True) self.ui.ThumbnailView.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.ui.FilenameDisp.setText(self.capture_name) self.ui.ThumbnailView.setPixmap(self.thumb_scaled) # The image to be saved to file as TIF # First confirm that the destination folder exists, create if it doesn't. self.manage_daily_folder() self.capture_fullpath = self.outdirname + "/" + self.capture_name outimage = QPixmap() outimage.convertFromImage(captured_image) outfile = QFile(self.capture_fullpath) outfile.open(QIODevice.WriteOnly) outimage.save(outfile, "TIFF") outfile.close()
def draw(win): win.scene.clear() win.image.fill(black) tx = win.dial_x.value() ty = win.dial_y.value() tz = win.dial_z.value() if win.funcs.currentText() == "- sin(x**2 + y**2)": f = f1 if win.funcs.currentText( ) == "(sin(sqrt(x**2 + y**2)))/(sqrt(x**2 + y**2))": f = f2 if win.funcs.currentText() == "exp((- x**2 - y**2) * x)": f = f3 if win.funcs.currentText( ) == "sqrt(x**2 + y**2) + 3 * (cos(sqrt(x**2 + y**2))) + 5": f = f4 win.image = float_horizon(win.scene.width(), win.scene.height(), win.x_min.value(), win.x_max.value(), win.dx.value(), win.z_min.value(), win.z_max.value(), win.dz.value(), tx, ty, tz, f, win.image) pix = QPixmap() pix.convertFromImage(win.image) win.scene.addPixmap(pix)
def draw_line(win): bx = win.begin_x.value() by = win.begin_y.value() ex = win.end_x.value() ey = win.end_y.value() is_standart =False win.image.fill(win.color_bground) if win.cda.isChecked(): start = time.clock() line_DDA(win, [bx, by], [ex, ey]) end = time.clock() if win.br_float.isChecked(): start = time.clock() line_br_float(win, [bx, by], [ex, ey]) end = time.clock() if win.br_int.isChecked(): start = time.clock() line_br_int(win, [bx, by], [ex, ey]) end = time.clock() if win.br_smooth.isChecked(): start = time.clock() line_br_smooth(win, [bx, by], [ex, ey]) end = time.clock() if win.lib.isChecked(): is_standart = True start = time.clock() win.scene.addLine(bx, by, ex, ey, win.pen) end = time.clock() if not is_standart: pix = QPixmap(511, 511) pix.convertFromImage(win.image) win.scene.addPixmap(pix) win.label.setText("{0:.3f}msc".format((end - start)*1000))
def update_style_preview(self, layer): syms = layer.renderer().symbols(QgsRenderContext()) # only display the first symbol if len(syms) > 0: pix = QPixmap() pix.convertFromImage(syms[0].bigSymbolPreviewImage()) self.ui.stylePreview.setPixmap(pix)
def to_pixmap(data: numpy.ndarray): image = QImage(data.data, *data.shape[:-1], QImage.Format_ARGB32) pixmap = QPixmap() # noinspection PyArgumentList pixmap.convertFromImage(image) return pixmap
def angle_changed(self, win): self.scene.clear() self.image.fill(bg_color) self.floating_horizon() pix = QPixmap() pix.convertFromImage(self.image) self.scene.addPixmap(pix)
def load_card_images(): global CARDS for card_name in os.listdir(CARDS_DIRECTORY): card_pixmap = QPixmap() card_pixmap.convertFromImage( QImage(os.path.join(CARDS_DIRECTORY, card_name))) # load image data from file and load into # memory as pixmap CARDS[os.path.splitext(os.path.basename(card_name))[0]] = card_pixmap
def fill_xor(win): pix = QPixmap() p = QPainter() xm = int(find_mid_x(win.edges)) draw_edges(win.image, win.edges) for ed in win.edges: p.begin(win.image) # если горизонтальное ребро - дальше if ed[1] == ed[3]: continue # иначе определяем границы сканирования if ed[1] > ed[3]: ed[1], ed[3] = ed[3], ed[1] ed[0], ed[2] = ed[2], ed[0] y = ed[1] end_y = ed[3] dx = (ed[2] - ed[0]) / (ed[3] - ed[1]) start_x = ed[0] while y < end_y: # определяем пересечение x = round(start_x) if(x < xm): while x < xm: col = QColor(win.image.pixel(x, y)) if col == col_zero: p.setPen(QPen(col_one)) else: p.setPen(QPen(col_zero)) p.drawPoint(x, y) x += 1 else: while x >= xm: col = QColor(win.image.pixel(x, y)) if col == col_zero: p.setPen(QPen(col_one)) else: p.setPen(QPen(col_zero)) p.drawPoint(x, y) x -= 1 start_x += dx y += 1 if win.delay.isChecked(): delay() pix.convertFromImage(win.image) win.scene.addPixmap(pix) if not win.delay.isChecked(): pix.convertFromImage(win.image) win.scene.addPixmap(pix) p.end()
def findIconHelper(self, size = int, themeName = str, iconName = str): pixmap = QPixmap() if iconName == '' or self.themeName == '': return pixmap if themeName == '': themeName = self.themeName if themeName == self.themeName: index = self.themeIndex else: index = self.readThemeIndex(themeName) subDirs = filter(lambda x:x[0] == str(size), index.dirList) for iconDir in self.iconDirs: if path.exists(path.join(iconDir, themeName)): for theme in subDirs: fileName = path.join(iconDir, themeName, theme[1], '%s.png' % str(iconName)) fileName_svg = path.join(iconDir, themeName, theme[1], '%s.svg' % str(iconName)) logging.debug('Looking for : %s' % fileName) if path.exists(fileName): pixmap.load(fileName) logging.debug('Icon: %s found in theme %s' % \ (iconName, themeName)) return pixmap elif path.exists(fileName_svg): pixmap.load(fileName_svg) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) return pixmap for iconDir in self.extraIcons: fileName = path.join(iconDir, '%s.png' % str(iconName)) fileName_svg = path.join(iconDir, '{}.svg'.format(str(iconName))) if path.exists(fileName): pixmap.load(fileName) #print "pixmap ->{}".format(fileName) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) return pixmap elif path.exists(fileName_svg): image=QImage(size, size, QImage.Format_RGB32) reader=QImageReader(fileName) reader.read(image) pixmap.convertFromImage(image) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) #print "pixmap ->{}".format(fileName) return pixmap if len(self._themes) > 0: self._themes.pop(0) if not len(self._themes) == 0 and pixmap.isNull(): pixmap = self.findIconHelper(size, self._themes[0], iconName) return pixmap
def findIconHelper(self, size=int, themeName=str, iconName=str): pixmap = QPixmap() if iconName == '' or self.themeName == '': return pixmap if themeName == '': themeName = self.themeName if themeName == self.themeName: index = self.themeIndex else: index = self.readThemeIndex(themeName) subDirs = filter(lambda x: x[0] == str(size), index.dirList) for iconDir in self.iconDirs: if path.exists(path.join(iconDir, themeName)): for theme in subDirs: fileName = path.join(iconDir, themeName, theme[1], '%s.png' % str(iconName)) fileName_svg = path.join(iconDir, themeName, theme[1], '%s.svg' % str(iconName)) logging.debug('Looking for : %s' % fileName) if path.exists(fileName): pixmap.load(fileName) logging.debug('Icon: %s found in theme %s' % \ (iconName, themeName)) return pixmap elif path.exists(fileName_svg): pixmap.load(fileName_svg) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) return pixmap for iconDir in self.extraIcons: fileName = path.join(iconDir, '%s.png' % str(iconName)) fileName_svg = path.join(iconDir, '{}.svg'.format(str(iconName))) if path.exists(fileName): pixmap.load(fileName) #print "pixmap ->{}".format(fileName) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) return pixmap elif path.exists(fileName_svg): image = QImage(size, size, QImage.Format_RGB32) reader = QImageReader(fileName) reader.read(image) pixmap.convertFromImage(image) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) #print "pixmap ->{}".format(fileName) return pixmap if len(self._themes) > 0: self._themes.pop(0) if not len(self._themes) == 0 and pixmap.isNull(): pixmap = self.findIconHelper(size, self._themes[0], iconName) return pixmap
def fill_xor(win): if win.check_color == False: draw_edges(win.edges) if win.check_lock == True: pix = QPixmap() p = QPainter() delay_time = win.delay_time_ent.value() xm = int(find_max_y(win.edges)) xm += 20 for ed in win.edges: p.begin(win.image) if ed[1] == ed[3]: continue if ed[1] > ed[3]: ed[1], ed[3] = ed[3], ed[1] ed[0], ed[2] = ed[2], ed[0] y = ed[1] end_y = ed[3] dx = (ed[2] - ed[0]) / (ed[3] - ed[1]) start_x = ed[0] while y < end_y: x = start_x while x < xm: col = QColor(win.image.pixel(x, y)) if col == win.bg_color: p.setPen(QPen(win.fill_color)) elif col == win.line_color: x += 1 continue elif col == win.fill_color: p.setPen(QPen(win.bg_color)) p.drawPoint(x, y) x += 1 start_x += dx y += 1 if delay_time: delay(delay_time) pix.convertFromImage(win.image) win.scene.addPixmap(pix) if not delay_time: pix.convertFromImage(win.image) win.scene.addPixmap(pix) p.end() win.check_filled = False else: QtWidgets.QMessageBox.warning( win, "Error", "Область не замкнута\nМногоугольник не определен")
def sun_drawing(window): rad = window.spin_rad.text() spin = window.spin_angle.text() bx = 325 by = 325 # clear_all(window) # window.image.fill(window.color_bground) is_standart = False if rad != '' and spin != '' and spin != '0' and float(spin) > 0 and float( spin) <= 360: rad = float(rad) spin = float(spin) for i in np.arange(0, 360, spin): ex = cos(radians(i)) * rad + 325 ey = sin(radians(i)) * rad + 325 if window.CDA.isChecked(): start = time.clock() CDA(window, [bx, by], [ex, ey]) end = time.clock() if window.bresenham_int.isChecked(): start = time.clock() bresenham_int(window, [bx, by], [ex, ey]) end = time.clock() if window.bresenham_float.isChecked(): start = time.clock() bresenham_float(window, [bx, by], [ex, ey]) end = time.clock() if window.bresenham_smooth.isChecked(): start = time.clock() bresenham_smooth(window, [bx, by], [ex, ey]) end = time.clock() if window.algorithm_wu.isChecked(): start = time.clock() algorithm_wu(window, [bx, by], [ex, ey]) end = time.clock() if window.librarian.isChecked(): is_standart = True start = time.clock() window.scene.addLine(float(bx), float(by), float(ex), float(ey), window.pen) end = time.clock() if not is_standart: pix = QPixmap(650, 650) pix.convertFromImage(window.image) window.scene.addPixmap(pix) window.time_label.setText("{0:.4f} msc".format((end - start) * 1000)) else: msg = QMessageBox() msg.setGeometry(450, 450, 800, 600) msg.setIcon(QMessageBox.Warning) msg.setText("Некорректные данные для построения 'солнца'!") msg.setWindowTitle("Ошибка!") msg.exec_()
def draw_res(self): self.scene.clear() self.image.fill(QtCore.Qt.white) self.read_x_z_value() self.image = self.float_horizon() p = QPixmap() p.convertFromImage(self.image) self.scene.addPixmap(p)
def fill_xor(win): summ = 0 start_time = time.process_time() pix = QPixmap() p = QPainter() xm = int(find_max_y(win.edges)) for ed in win.edges: p.begin(win.image) # если горизонтальное ребро - дальше if ed[1] == ed[3]: continue # иначе определяем границы сканирования if ed[1] > ed[3]: ed[1], ed[3] = ed[3], ed[1] ed[0], ed[2] = ed[2], ed[0] y = ed[1] end_y = ed[3] dx = (ed[2] - ed[0]) / (ed[3] - ed[1]) start_x = ed[0] while y < end_y: # определяем пересечение x = start_x while x < xm: col = QColor(win.image.pixel(x, y)) if col == col_zero: p.setPen(QPen(col_one)) else: p.setPen(QPen(col_zero)) p.drawPoint(x, y) x += 1 start_x += dx y += 1 if win.delay.isChecked(): current = time.process_time() - start_time summ += current delay() pix.convertFromImage(win.image) win.scene.addPixmap(pix) start_time = time.process_time() if not win.delay.isChecked(): pix.convertFromImage(win.image) win.scene.addPixmap(pix) p.end() draw_edges(win.image, win.edges) final = (time.process_time() - start_time) + summ print("Время выполнения алгоритма без задержки {:g} s".format(final))
def draw_edges(image, edges): global w pix = QPixmap() p = QPainter() p.begin(image) p.setPen(QPen(fill_color)) for ed in edges: p.drawLine(edge[0][0], edge[0][1], edge[1][0], edge[1][1]) p.end() pix.convertFromImage(image) w.scene.addPixmap(pix)
def showimg(self, filename): self.debuglabel.setText(filename) image = QImage() if (not (image.load(filename))): QMessageBox.information(self, "error", "open file is erroe") return self.myfile = filename pixmap = QPixmap() pixmap.convertFromImage(image) self.labelpic.setPixmap(pixmap) self.labelpic.resize(800, 600) self.labelpic.show()
def draw_edges(edges): global w qp = QPainter() pix = QPixmap() qp.begin(w.image) qp.setPen(QPen(w.line_color)) for ed in edges: qp.drawLine(ed[0], ed[1], ed[2], ed[3]) pix.convertFromImage(w.image) w.scene.addPixmap(pix) qp.end()
def add_image_from_thread(self, item, image): if self.isEmpty: super().clear() self.setGridSize(QSize(item_size_x, item_size_y)) pixmap = QPixmap(item_size_x, item_size_y) pixmap.convertFromImage(image) icon = QIcon(pixmap) item.setIcon(icon) self.updateGeometry() super().addItem(item) self.updateGeometry() self.isEmpty = False
def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton and self.drawing == True: self.drawing = False self.path = None self.begin = self.scaleCoords(event.pos()) self.end = self.scaleCoords(event.pos()) self.update() p = QPixmap() p.convertFromImage(self.imageDraw) self.history.append(p)
def paintEvent(self, ev): pixmap = QPixmap() pixmap.convertFromImage(self.plot_background) self.painter.begin(pixmap) self.painter.setPen(self.ytick_pen) temp = self.scale_y( np.array( list(self.buf[self.buffer_current_index:]) + list(self.buf[:self.buffer_current_index]))) for yt in self.yticks: self.painter.drawLine( QLine(0, self.scale_y(yt), self.buffer_length * self.xscale, self.scale_y(yt))) self.painter.setPen(self.hline_pen) for hline in self.hlines: self.painter.drawLine( QLine(0, self.scale_y(hline), self.buffer_length * self.xscale, self.scale_y(hline))) self.painter.setPen(self.pen) for idx in range(self.buffer_length - 1): x1 = (idx) * self.xscale x2 = (idx + 1) * self.xscale y1 = temp[idx] y2 = temp[idx + 1] self.painter.drawLine(QLine(x1, y1, x2, y2)) interval = self.buffer_length // 10 interval = ccfg.plot_xtick_interval if idx % interval == 0: self.painter.setPen(self.xtick_pen) self.painter.drawLine( QLine((x1 - self.buffer_current_index * self.xscale) % (self.buffer_length * self.xscale), self.xtick0, (x1 - self.buffer_current_index * self.xscale) % (self.buffer_length * self.xscale), self.xtick1)) self.painter.setPen(self.pen) #if True:#20<self.buffer_current_index<80: # painter.drawEllipse(x1,y1,x2,y2) self.painter.end() self.plot.setPixmap(pixmap)
def start(self): if (self.x_seed == -1): QMessageBox.warning(self, "Ошибка!", "Затравочный пиксел не введён") else: if self.delay.isChecked(): self.algorithm_delayed() else: self.algorithm() self.draw_edges_end() pix = QPixmap() pix.convertFromImage(self.image) self.scene.addPixmap(pix)
def draw_on_click_button(self, win): if len(self.edges) < 2: return pix = QPixmap() p = QPainter() p.begin(win.image) #self.scene.clear() pipe = self.set_pipeline(self.edges) self.scene.addLine(pipe, 0, pipe, 520) for i in self.edges: lb, rb, sy, ey, tg = self.get_line_values(i) l = max(abs(lb - rb), abs(sy - ey)) x = lb y = sy dx = (rb - lb) / l dy = (ey - sy) / l prevY = None for i in range(int(l)): p.setPen(QPen(black)) if sy == ey or int(y) == prevY: prevY = int(y) x += dx y += dy continue self.fill(win, pix, p, x, y, pipe) prevY = int(y) x += dx y += dy """if self.lazy_draw.isChecked(): self.delay() pix.convertFromImage(win.image) win.scene.addPixmap(pix) col = QColor(win.image.pixel(k, y)) if col == white: p.setPen(QPen(black)) else: p.setPen(QPen(white)) p.drawPoint(k, y) """ if not self.lazy_draw.isChecked(): pix.convertFromImage(win.image) win.scene.addPixmap(pix) p.end()
def draw_centr(window): # window.image.fill(window.color_bground) is_standart = False x = int(window.centr_x.text()) y = int(window.centr_y.text()) d = int(window.dia.text()) c = int(window.count.text()) if window.circle.isChecked(): for i in range(d, d * c + d, d): if window.canon.isChecked(): circle_canon(window, x, y, i) if window.param.isChecked(): circle_param(window, x, y, i) if window.brez.isChecked(): circle_brez(window, x, y, i) if window.middle.isChecked(): circle_middle(window, x, y, i) if window.lib.isChecked(): is_standart = True window.scene.addEllipse(x - i, y - i, i * 2, i * 2, window.pen) if window.ellips.isChecked(): a = int(window.a.text()) b = int(window.b.text()) for i in range(d, d * c + d, d): if window.canon.isChecked(): ellips_canon(window, x, y, i * a / b, i * b / a) if window.param.isChecked(): ellips_param(window, x, y, i * a / b, i * b / a) if window.brez.isChecked(): ellips_brez(window, x, y, i * a / b, i * b / a) if window.middle.isChecked(): ellips_middle(window, x, y, i * a / b, i * b / a) if window.lib.isChecked(): is_standart = True if a < b: window.scene.addEllipse(x - (i * a / b), y - (i * b / a) / 2, i * 2 * a / b, i * b / a, window.pen) if a > b: window.scene.addEllipse(x - (i * a / b) / 2, y - (i * b / a), i * a / b, 2 * i * b / a, window.pen) if not is_standart: pix = QPixmap(651, 651) pix.convertFromImage(window.image) window.scene.addPixmap(pix)
def get_pixel(point): global w, point_zat, circle pix = QPixmap() if circle: r = w.rad.value() draw_circle(w.image, r, point) circle = False if point_zat: w.p_x.setValue(point.x()) w.p_y.setValue(point.y()) draw_edges(w.image, w.edges) point_zat = False pix.convertFromImage(w.image) w.scene.addPixmap(pix)
def add_image(self, image): if self.isEmpty: super().clear() self.setGridSize(QSize(item_size_x, item_size_y)) item = CustomListWidgetItem(image) image = image.reshape(self.img_size, -1) image = ImageHelpers.toQImage(image) pixmap = QPixmap(self.img_size, self.img_size) pixmap.convertFromImage(image) icon = QIcon(pixmap) item.setIcon(icon) super().addItem(item) self.isEmpty = False return item
async def refresh_map(widget): """ Refresh map when map widget refresh event is set. This is asyncio coroutine. :param widget: Map widget. """ event = widget.refresh_map map = widget.map # use redis to cache map tiles client = redis.Redis('localhost') downloader = redis_downloader(client) render_map = functools.partial( geotiler.render_map_async, downloader=downloader ) fetch_tiles = functools.partial( geotiler.fetch_tiles, downloader=downloader ) pixmap = QPixmap(*map.size) while True: await event.wait() event.clear() logger.debug('fetching map image...') img = await render_map(map) pixmap.convertFromImage(ImageQt(img)) # TODO: use `fetch_tiles` to update map as tiles arrive, but try to # avoid `setPixmap` within the loop. # tiles = fetch_tiles(map) # async for tile in tiles: # painter = QPainter(pixmap) # img = QImage() # img.loadFromData(tile.img) # painter.drawImage(*tile.offset, img) # painter.end() # widget.map_layer.setPixmap(pixmap) scroll_map(widget, map.center) widget.map_layer.setPixmap(pixmap) logger.debug('got map image')
def setSampleImage(self, pathToFile): self.graphicsView.hide() #clear scene self.graphicsScene.clear() #load file tmpImage = QImage(pathToFile) self.originalHeight = tmpImage.height() self.originalWidth = tmpImage.width() tmpPixmap = QPixmap(1) tmpPixmap.convertFromImage(tmpImage.scaledToWidth(300)) self.scaledHeight = tmpPixmap.height() self.scaledWidth = tmpPixmap.width() #add to scene and show self.graphicsScene.addPixmap(tmpPixmap) self.graphicsView.show()
class Window(QQuickView): def __init__(self, settings, windowInfo): QQuickView.__init__(self) self._settings = settings surface_format = QSurfaceFormat() surface_format.setAlphaBufferSize(8) self.set_cursor_shape("shape_start_cursor") self.setColor(QColor(0, 0, 0, 0)) self.setFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.setResizeMode(QQuickView.SizeRootObjectToView) self.setFormat(surface_format) self.setTitle(_("Deepin screenshot")) self.qimage = QImage(self._settings.tmpImageFile) self.qpixmap = QPixmap() self.qpixmap.convertFromImage(self.qimage) self.window_info = windowInfo self._grabPointerStatus = False self._grabKeyboardStatus = False self._grabFocusTimer = self._getGrabFocusTimer() self._osdShowed = False self._osdShowing = False self._quitOnOsdTimeout = False @pyqtSlot(int, int, result="QVariant") def get_color_at_point(self, x, y): if x >= 0 and y >= 0: rgb = self.qimage.pixel(x, y) return [qRed(rgb), qGreen(rgb), qBlue(rgb)] else: return [0, 0, 0] @pyqtSlot(result="QVariant") def get_window_info_at_pointer(self): wInfo = self.window_info.get_window_info_at_pointer() wInfo[0] -= self.x() wInfo[1] -= self.y() return wInfo @pyqtSlot(result="QVariant") def get_cursor_pos(self): ''' get the cursor position relative to the top-left corner of this window ''' pos = QCursor.pos() pos.setX(pos.x() - self.x()) pos.setY(pos.y() - self.y()) return pos @pyqtSlot(str) def set_cursor_shape(self, shape): ''' Set the shape of cursor, the param shape should be one of the keys of the global variable cursor_shape_dict. ''' if cursor_shape_dict.get(shape): pix = QPixmap(cursor_shape_dict[shape]) if shape == "shape_start_cursor": cur = QCursor(pix, hotX=8, hotY=8) elif shape.startswith(CURSOR_SHAPE_COLOR_PEN_PREFIX): cur = QCursor(pix, hotX=0, hotY=pix.height()) else: cur = QCursor(pix, hotX=5, hotY=5) else: cur = QCursor(Qt.ArrowCursor) self.setCursor(cur) @pyqtSlot(str,int,int,int,int) def save_overload(self, style, x, y, width, height): mosaic_radius = 10 blur_radius = 10 p = QPixmap.fromImage(self.grabWindow()) p = p.copy(x,y,width,height) if style == "mosaic": p = p.scaled(width / mosaic_radius, height / mosaic_radius, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) p = p.scaled(width, height) elif style == "blur": p = p.scaled(width / blur_radius, height / blur_radius, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) p = p.scaled(width, height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) image_dir = "/tmp/deepin-screenshot-%s.png" % style p.save(os.path.join(image_dir)) def _getGrabFocusTimer(self): timer = QTimer() timer.setSingleShot(True) timer.setInterval(100) timer.timeout.connect(self._grabFocusInternal) return timer def _grabFocusInternal(self): if not self._grabPointerStatus: self._grabPointerStatus = self.setMouseGrabEnabled(True) if not self._grabKeyboardStatus: self._grabKeyboardStatus = self.setKeyboardGrabEnabled(True) if not (self._grabPointerStatus and self._grabKeyboardStatus): self._grabFocusTimer.start() def grabFocus(self): self._grabFocusTimer.start() def ungrabFocus(self): self._grabPointerStatus = False self._grabKeyboardStatus = False self.setMouseGrabEnabled(False) self.setKeyboardGrabEnabled(False) @pyqtSlot(str,str,result="QVariant") def get_save_config(self, group_name,op_name): return self._settings.getOption(group_name, op_name) @pyqtSlot(str,str,str) def set_save_config(self,group_name,op_name,op_index): self._settings.setOption(group_name, op_name, op_index) @pyqtSlot(int,int,int,int) def save_screenshot(self, x, y, width, height): pixmap = QPixmap.fromImage(self.grabWindow()) pixmap = pixmap.copy(x, y, width, height) pixmap.save(SAVE_DEST_TEMP) self.hide() saveScreenshot(pixmap) if self._settings.showOSD: self.showHotKeyOSD() @pyqtSlot() def enable_zone(self): try: iface = QDBusInterface("com.deepin.daemon.Zone", "/com/deepin/daemon/Zone", '', QDBusConnection.sessionBus()) iface.asyncCall("EnableZoneDetected", True) except: pass @pyqtSlot() def disable_zone(self): try: iface = QDBusInterface("com.deepin.daemon.Zone", "/com/deepin/daemon/Zone", '', QDBusConnection.sessionBus()) iface.asyncCall("EnableZoneDetected", False) except: pass @pyqtSlot() def share(self): socialSharingInterface.share("", SAVE_DEST_TEMP) @pyqtSlot(int, int, str, result=bool) def checkKeySequenceEqual(self, modifier, key, targetKeySequence): keySequence = QKeySequence(modifier + key).toString() return keySequence == targetKeySequence @pyqtSlot(int, int, result=str) def keyEventToQKeySequenceString(self, modifier, key): keySequence = QKeySequence(modifier + key).toString() return keySequence def _handleOSDTimeout(self): self._osdShowing = False if self._quitOnOsdTimeout: qApp.quit() def showHotKeyOSD(self): self._osdShowing = True self._osdShowed = True self.rootObject().showHotKeyOSD() self.rootObject().osdTimeout.connect(self._handleOSDTimeout) def showWindow(self): self.showFullScreen() self.grabFocus() @pyqtSlot() def closeWindow(self): self.enable_zone() unregister_service() self.close() if self._settings.showOSD: if not self._osdShowed: self.showHotKeyOSD() elif self._osdShowing: self._quitOnOsdTimeout = True else: qApp.quit() else: qApp.quit()
class ImageDisplay(QWidget): def __init__(self,name,downsample=1,clim=None,colormap=None,mouse_event_handler=None,image_min=None,image_max=None,width=512,height=512,zoom_height=kcfg.zoom_height,zoom_width=kcfg.zoom_width,zoomable=False,draw_boxes=False,draw_lines=False): super(ImageDisplay,self).__init__() self.name = name self.autoscale = False self.sx = width self.sy = height self.draw_boxes = draw_boxes self.draw_lines = draw_lines self.zoomable = zoomable if clim is None: try: clim = np.loadtxt('.gui_settings/clim_%s.txt'%name) except Exception as e: self.autoscale = True self.clim = clim self.pixmap = QPixmap() self.label = QLabel() self.image_max = image_max self.image_min = image_min self.zoom_width = zoom_width self.zoom_height = zoom_height layout = QHBoxLayout() layout.addWidget(self.label) if image_min is not None and image_max is not None and not self.autoscale: self.n_steps = 100 self.cmin_slider = QSlider(Qt.Vertical) self.cmax_slider = QSlider(Qt.Vertical) self.cmin_slider.setMinimum(0) self.cmax_slider.setMinimum(0) self.cmin_slider.setSingleStep(1) self.cmax_slider.setSingleStep(1) self.cmin_slider.setPageStep(10) self.cmax_slider.setPageStep(10) self.cmin_slider.setMaximum(self.n_steps) self.cmax_slider.setMaximum(self.n_steps) self.cmin_slider.setValue(self.real2slider(self.clim[0])) self.cmax_slider.setValue(self.real2slider(self.clim[1])) self.cmin_slider.valueChanged.connect(self.set_cmin) self.cmax_slider.valueChanged.connect(self.set_cmax) layout.addWidget(self.cmin_slider) layout.addWidget(self.cmax_slider) self.setLayout(layout) self.zoomed = False self.colormap = colormap if self.colormap is not None: self.colortable = colortable(self.colormap) if mouse_event_handler is not None: self.mousePressEvent = mouse_event_handler else: self.mousePressEvent = self.zoom self.downsample = downsample data = np.random.rand(100,100) self.show(data) self.zoom_x1 = 0 self.zoom_x2 = self.sx-1 self.zoom_y1 = 0 self.zoom_y2 = self.sy-1 def real2slider(self,val): # convert a real value into a slider value return round(int((val-float(self.image_min))/float(self.image_max-self.image_min)*self.n_steps)) def slider2real(self,val): # convert a slider integer into a real value return float(val)/float(self.n_steps)*(self.image_max-self.image_min)+self.image_min def set_cmax(self,slider_value): self.clim = (self.clim[0],self.slider2real(slider_value)) np.savetxt('.gui_settings/clim_%s.txt'%self.name,self.clim) def set_cmin(self,slider_value): self.clim = (self.slider2real(slider_value),self.clim[1]) np.savetxt('.gui_settings/clim_%s.txt'%self.name,self.clim) def show(self,data,boxes=None,lines=None,mask=None): if mask is None: if boxes is not None: mask = np.ones(boxes[0].shape) elif lines is not None: mask = np.ones(lines[0].shape) else: assert (boxes is None) and (mask is None) # if self.name=='mirror': # print data[6,6] if self.autoscale: clim = (data.min(),data.max()) else: clim = self.clim cmin,cmax = clim downsample = self.downsample data = data[::downsample,::downsample] if self.zoomed: x_scale = float(data.shape[1])/float(self.sx) y_scale = float(data.shape[0])/float(self.sy) zy1 = int(round(self.zoom_y1*y_scale)) zy2 = int(round(self.zoom_y2*y_scale)) zx1 = int(round(self.zoom_x1*x_scale)) zx2 = int(round(self.zoom_x2*x_scale)) #data = data[self.zoom_y1:self.zoom_y2,self.zoom_x1:self.zoom_x2] data = data[zy1:zy2,zx1:zx2] bmp = np.round(np.clip((data.astype(np.float)-cmin)/(cmax-cmin),0,1)*255).astype(np.uint8) sy,sx = bmp.shape n_bytes = bmp.nbytes bytes_per_line = int(n_bytes/sy) image = QImage(bmp,sy,sx,bytes_per_line,QImage.Format_Indexed8) if self.colormap is not None: image.setColorTable(self.colortable) self.pixmap.convertFromImage(image) if boxes is not None and self.draw_boxes: x1vec,x2vec,y1vec,y2vec = boxes pen = QPen() pen.setColor(QColor(*kcfg.active_search_box_color)) pen.setWidth(kcfg.search_box_thickness) painter = QPainter() painter.begin(self.pixmap) painter.setPen(pen) for index,(x1,y1,x2,y2) in enumerate(zip(x1vec,y1vec,x2vec,y2vec)): if mask[index]: width = float(x2 - x1 + 1)/float(self.downsample) painter.drawRect(x1/float(self.downsample)-self.zoom_x1,y1/float(self.downsample)-self.zoom_y1,width,width) painter.end() if lines is not None and self.draw_lines: x1vec,x2vec,y1vec,y2vec = lines pen = QPen() pen.setColor(QColor(*kcfg.slope_line_color)) pen.setWidth(kcfg.slope_line_thickness) painter = QPainter() painter.begin(self.pixmap) painter.setPen(pen) for index,(x1,y1,x2,y2) in enumerate(zip(x1vec,y1vec,x2vec,y2vec)): if mask[index]: painter.drawLine(QLine(x1/float(self.downsample)- self.zoom_x1,y1/float(self.downsample)-self.zoom_y1,x2/float(self.downsample)- self.zoom_x1,y2/float(self.downsample)- self.zoom_y1)) painter.end() if sy==self.sy and sx==self.sx: self.label.setPixmap(self.pixmap) else: self.label.setPixmap(self.pixmap.scaled(self.sy,self.sx)) def set_clim(self,clim): self.clim = clim def zoom(self,event): if not self.zoomable: return if self.zoom_width>=self.sx or self.zoom_height>=self.sy: return x,y = event.x(),event.y() if self.zoomed: self.zoomed = False self.zoom_x1 = 0 self.zoom_x2 = self.sx-1 self.zoom_y1 = 0 self.zoom_y2 = self.sy-1 else: self.zoomed = True self.zoom_x1 = x-self.zoom_width//2 self.zoom_x2 = x+self.zoom_width//2 self.zoom_y1 = y-self.zoom_height//2 self.zoom_y2 = y+self.zoom_height//2 if self.zoom_x1<0: dx = -self.zoom_x1 self.zoom_x1+=dx self.zoom_x2+=dx if self.zoom_x2>self.sx-1: dx = self.zoom_x2-(self.sx-1) self.zoom_x1-=dx self.zoom_x2-=dx if self.zoom_y1<0: dy = -self.zoom_y1 self.zoom_y1+=dy self.zoom_y2+=dy if self.zoom_y2>self.sy-1: dy = self.zoom_y2-(self.sy-1) self.zoom_y1-=dy self.zoom_y2-=dy #print 'zooming to %d,%d,%d,%d'%(self.zoom_x1,self.zoom_x2,self.zoom_y1,self.zoom_y2) def set_draw_lines(self,val): self.draw_lines = val def set_draw_boxes(self,val): self.draw_boxes = val
class Overlay(QWidget): def __init__(self, parent, binpath): super().__init__(parent) sizePolicy = QSizePolicy() sizePolicy.setHorizontalPolicy(QSizePolicy.Maximum) sizePolicy.setVerticalPolicy(QSizePolicy.Maximum) #self.setSizePolicy(sizePolicy) self.setMouseTracking(True) self.on_selection = False self.selected = False self.c = Communicate() self.start_position = QPoint(0,0) self.last_position = QPoint(0,0) image = ( b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" b"\x00\x00\xFF\xFF\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00" b"\x00\x00\xFF\xFF\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\x00\x00" b"\x00\x00\xFF\xFF\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\x00\x00" b"\x00\x00\xFF\xFF\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\x00\x00" b"\x00\x00\xFF\xFF\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\x00\x00" b"\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00\xFF\xFF\x00\x00" b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") im = QImage(image, 8,8, QImage.Format_RGB16) im = im.scaled(64,64) self.crop = QPixmap() self.crop.convertFromImage(im) def insideSelection(self, point): width = self.last_position.x() - self.start_position.x() height = self.last_position.y() - self.start_position.y() return ( point.x() > self.start_position.x() and point.x() < self.start_position.x() + width and point.y() > self.start_position.y() and point.y() < self.start_position.y() + height ) def mouseMoveEvent(self, event): if self.on_selection: self.last_position = event.pos() self.update() def mousePressEvent(self, QMouseEvent): if not self.insideSelection(QMouseEvent.pos()): self.on_selection = True self.selected = True self.start_position = QMouseEvent.pos() self.last_position = QMouseEvent.pos() self.update() def mouseDoubleClickEvent(self, QMouseEvent): if self.insideSelection(QMouseEvent.pos()): width = self.last_position.x() - self.start_position.x() height = self.last_position.y() - self.start_position.y() self.c.cropImage.emit(self.start_position.x(), self.start_position.y(), width,height) def mouseReleaseEvent(self, QMouseEvent): self.on_selection = False self.update() def enterEvent(self, event): return super().enterEvent(event) def leaveEvent(self, event): return super().enterEvent(event) def paintEvent(self, e): qp = QPainter() qp.begin(self) #self.drawWidget(qp) if self.selected: qp.setCompositionMode(QPainter.CompositionMode_HardLight) qp.setBrush(QColor(0, 0, 0, 128)) qp.drawRect(0,0, self.width(), self.height()) qp.setCompositionMode(QPainter.CompositionMode_Overlay) qp.setBrush(QColor(255, 255, 255, 255)) width = self.last_position.x() - self.start_position.x() height = self.last_position.y()-self.start_position.y() qp.drawRect(self.start_position.x(), self.start_position.y(), width, height) qp.setCompositionMode(QPainter.CompositionMode_SourceOver) image_w = min([abs(width), abs(height), self.crop.width()]) #self.crop.width() image_h = image_w #self.crop.height() qp.drawPixmap(self.start_position.x() + width/2 - image_w/2, self.start_position.y() + height/2 - image_h/2, image_w, image_h, self.crop) qp.end()
class CamFrameGrabberThread(QThread): """ This class implements a background task that constantly grabs new frames from the selected camera """ DEFAULT_CAM = "USB 2.0 Camera" DEFAULT_FPS = 60 FPS_ESTIMATION_ALPHA = 0.98 FRAME_SIZE_STR_SPLITTER = " x " sig_update_cam_ui = pyqtSignal() # Signal that's emitted whenever the UI associated to the camera controls needs to be refreshed (eg: new frame size selected -> need to resize window, error grabbing camera frame -> disconnect camera...) sig_new_dev_selected = pyqtSignal(str) # Signal that's emitted when a device is selected (could be the device that was already selected). It's emitted either from the UI when the user changes the selected item in drpInput, or from the code when sig_new_dev is emitted (as a new device is connected or an old one disconnected) sig_new_img = pyqtSignal() # Signal that's emitted every time a new camera frame becomes available sig_error = pyqtSignal(str) # Signal that's emitted every time an error occurred def __init__(self): QThread.__init__(self) self.done = False self.dev_selected_name = self.DEFAULT_CAM self.cap = None self.qPix = QPixmap(1, 1) self.cv = DroneController() self.cv.load_color_thresh_settings() self.cv.load_blob_detector_settings() self.cv_do_color = True self.cv_do_blob = True self.cv_evaluate_px_at = np.array([0, 0]) self.cv_evaluate_px_value = np.array([0, 0, 0], dtype=np.uint8) self.index = 0 self.actual_fps = 0 def __del__(self): self.wait() @pyqtSlot() def stop_thread(self): # This method is used to externally request this thread to terminate self.done = True # Flag to indicate the outer while loop in run_experiment() to finish thread execution self.change_selected_device("EXIT! :P") # Choose a void device, to force the inner while loop in run_experiment() to exit after grabbing at most one frame if self.wait(5000) is not True or self.cap is not None: # Worst-case scenario: force quit if self.cap is still not None after 5sec logging.warning("Uh-ooohh, CamFrameGrabberThread didn't terminate even after waiting for 5sec. Force quitting :S") self.cap = None self.terminate() else: logging.info("CamFrameGrabberThread exited cleanly :)") @pyqtSlot(str) def change_selected_device(self, dev_selected): if self.dev_selected_name != dev_selected: logging.info("New device selected: {}".format(dev_selected)) self.dev_selected_name = str(dev_selected) @pyqtSlot(str, bool) def change_cam_frame_size(self, new_frame_size, emit_signal): if self.cap is not None and window.drpSize.count() > 0: # Sanity check (in case capture device was just closed or we're clearing drpSize to re-add available sizes) logging.info("Changing frame size to {}".format(new_frame_size)) self.cap.frame_size = tuple([int(x) for x in new_frame_size.split(self.FRAME_SIZE_STR_SPLITTER)]) if emit_signal: # If the user was the one who clicked on this combobox item (as opposed to me, manually from the code), update cam UI self.sig_update_cam_ui.emit() # drpFPS might need to be updated (different frame sizes might have different fps available) @pyqtSlot(str) def change_cam_frame_rate(self, new_frame_rate): if self.cap is not None and window.drpFPS.count() > 0: # Sanity check (in case capture device was just closed or we're clearing drpSize to re-add available sizes) logging.info("Changing frame rate to {}".format(new_frame_rate)) self.cap.frame_rate = int("".join(x for x in new_frame_rate if x.isdigit())) # Keep only the numbers (= remove the " fps" part, if exists) @pyqtSlot(str, int, bool) def change_cam_control_setting(self, ctrl_name, new_value, is_bool): """ Process a request (from the UI) to change a particular camera setting. :param ctrl_name: Particular camera setting that wants to be modified (eg: exposure time, white balance...) :param new_value: New value desired for the camera setting :param is_bool: True if the UI control is a CheckBox, False if it's a SpinBox (ie: TextBox with up&down arrows) """ if self.cap is not None: # Sanity check (in case capture device was just closed) for c in self.cap.controls: if c.display_name == ctrl_name: try: if is_bool: c.set_value(c.min_val if (new_value == Qt.Unchecked) else c.max_val) else: c.set_value(new_value) logging.info("'{}' changed to {}".format(c.display_name, c.value)) except: self.sig_error.emit("Unable to change '{}' property to '{}'! Make sure the value is valid (within bounds, not disabled by other setting like 'Auto' modes, etc).".format(ctrl_name, new_value)) return @pyqtSlot(bool) def set_cv_do_color(self, checked): self.cv_do_color = checked window.grpBlob.setEnabled(checked) self.set_cv_do_blob(False if not checked else window.grpBlob.isChecked()) @pyqtSlot(bool) def set_cv_do_blob(self, checked): self.cv_do_blob = checked @pyqtSlot(int, str, bool) def change_HSV_setting(self, new_value, letter, is_max): """ Updates the corresponding field (H,S or V variable, min or max) of the HSV color thresholding filter. :param new_value: New value to set the corresponding threshold to :param letter: either 'H', 'S', or 'V' (case insensitive), depending on which threshold should be modified :param is_max: True to change the upper threshold; False to change the lower one """ letter = letter.lower() # To avoid problems, convert the letter to lowercase and only compare to lowercase index = 0 if letter == 'h' else 1 if letter == 's' else 2 # Convert H, S, V to 0, 1, 2 # Now update the right variable based on is_max if is_max: self.cv.cv_HSV_thresh_max[index] = new_value else: self.cv.cv_HSV_thresh_min[index] = new_value @pyqtSlot(int, str, bool) def change_blob_setting(self, new_value, letter, is_max): """ Updates the corresponding setting (area, circularity, convexity or inertia, min or max) of the blob detector. :param new_value: If int: New value to set the corresponding threshold to; if bool: activate/deactivate filter :param letter: either 'A', 'C', 'V', or 'I' (case insensitive), depending on which setting should be modified :param is_max: True to change the upper threshold; False to change the lower one [ignored if new_value is bool] """ letter = letter.lower() # To avoid problems, convert the letter to lowercase and only compare to lowercase param = "Area" if letter == 'a' else "Circularity" if letter == 'c' else "Convexity" if letter == 'v' else "Inertia" if type(new_value) is bool: setattr(self.cv.cv_blob_detect_params, "filterBy{}".format(param), new_value) else: setattr(self.cv.cv_blob_detect_params, "{}{}{}".format("max" if is_max else "min", param, "Ratio" if letter == 'i' else ""), new_value) def run(self): while not self.done: self.sleep(1) # Outer while loop just waits until a device is selected self.cap = UvcCapture(self.dev_selected_name) if self.cap is None: # If we didn't find the desired cam, don't continue self.qPix = QPixmap(1, 1) # Default to a black pixel self.cv_evaluate_px_value = np.array([0, 0, 0], dtype=np.uint8) logging.info("No compatible cameras found or chosen camera name not available :(") self.sig_update_cam_ui.emit() # Make sure camera-related UI is updated (eg: don't show exposure time control if no camera is selected...) continue # If we made it here, we successfully connected to the selected camera. Print camera info and select default values for c in self.cap.controls: logging.info("\t{} = {} {} (def:{}, min:{}, max:{})".format(c.display_name, str(c.value), str(c.unit), str(c.def_val), str(c.min_val), str(c.max_val))) self.cap.select_best_frame_mode(self.DEFAULT_FPS) logging.info(self.cap.name + " has the following available modes:\n\t" + str([tuple(x) for x in self.cap.sorted_available_modes()]) + "\nSelected mode: " + str(self.cap.frame_mode)) self.cap.print_info() logging.debug("LOADING SETTINGS returned {}".format(self.cap.load_settings(self.cv.CAMERA_SETTINGS_FILE))) self.sig_update_cam_ui.emit() # Update camera-related UI (eg: add controls for exposure time, white balance, etc.) img = np.zeros(self.cap.frame_size) # Resize qPix to fit new image size self.qPix = QPixmap.fromImage(QImage(img.data, img.shape[1], img.shape[0], QImage.Format_RGB888)) self.actual_fps = self.cap.frame_rate tt = datetime.now() # Initialize tt (used to estimate actual frame rate) to prevent an error on the first loop iteration while self.cap.name == self.dev_selected_name: # Run an inner while loop to capture frames as long as the selected device is kept constant ok = False t = datetime.now() for a in range(5): try: frame = self.cap.get_frame_robust() self.index = frame.index # logging.debug("DEBUG - Successfully got frame {:d} after {:d} tries".format(frame.index, a+1)) ok = True break except uvc.CaptureError as e: logging.error('DEBUG - Could not get Frame. Error: "{}". Tried {} time{}.'.format(e.message, a+1, "s" if a > 0 else "")) if not ok: self.sig_error.emit("Couldn't get camera frame after 5 tries, reconnecting...") break # Exit inner loop (force an iteration on the outer loop) after 5 consecutive failed attempts to grab a frame # We successfully grabbed a frame, let's store the value of the pixel cv_evaluate_px_at for debugging purposes try: self.cv_evaluate_px_value = np.array(frame.bgr[self.cv_evaluate_px_at[1], self.cv_evaluate_px_at[0]]) # Create a new np.array so that the value at the pixel is not cached, but copied (ie: if frame.bgr is modified, cv_evaluate_px_value is not). Also note that images should be indexed [y,x]! except: self.cv_evaluate_px_at = np.array([0, 0]) # Now we can run the CF detection algorithm on it (if grpColor is checked) and modify frame.bgr if we want t2 = datetime.now() if self.cv_do_color: self.cv.detect_cf_in_camera(frame.bgr, self.cv_do_blob) # Run CF detection (and blob detection if checked) # Now overlay the mask over the camera frame t3 = datetime.now() if self.cv.cf_pos_tracked and self.cv_do_blob: cv2.circle(self.cv.cv_cam_frame, tuple(self.cv.cf_curr_pos[0:2].astype(int)), int(self.cv.cf_curr_pos[2]+5), [0, 255, 0], -1) # np.putmask(self.cv.cv_cam_frame[:,:,0], self.cv.cv_filtered_HSV_mask, 255) # np.putmask(self.cv.cv_cam_frame[:,:,1], self.cv.cv_filtered_HSV_mask, 0) # np.putmask(self.cv.cv_cam_frame[:,:,2], self.cv.cv_filtered_HSV_mask, 255) mask = cv2.cvtColor(self.cv.cv_filtered_HSV_mask, cv2.COLOR_GRAY2BGR).astype(bool) np.putmask(self.cv.cv_cam_frame, mask, np.array([255, 0, 255], dtype=np.uint8)) else: t3 = datetime.now() # For consistency, save current time as t3 (even if we didn't do anything # And finally convert the resulting image to qPix and emit the appropriate signal so the UI can refresh it t4 = datetime.now() img = cv2.cvtColor(frame.bgr, cv2.COLOR_BGR2RGB) self.qPix.convertFromImage(QImage(img.data, img.shape[1], img.shape[0], QImage.Format_RGB888)) self.sig_new_img.emit() t5 = datetime.now() self.actual_fps = self.FPS_ESTIMATION_ALPHA*self.actual_fps + (1-self.FPS_ESTIMATION_ALPHA)/(t5-tt).total_seconds() logging.debug("At t={} picture #{:03d} was taken; deltaTtotal={:6.2f}ms [{:6.2f}ms] (capture_frame->{:6.2f}ms + detect->{:6.2f}ms + blob->{:6.2f}ms + putmask->{:6.2f}ms + toQPixmap->{:6.2f}ms) -> Estimated FPS: {:.2f}".format(t2, frame.index, (t5-tt).total_seconds()*1000, (t5-t).total_seconds()*1000, (t2-t).total_seconds()*1000, (self.cv.t_events[-2]-t2).total_seconds()*1000 if self.cv_do_color else 0, (self.cv.t_events[-1]-self.cv.t_events[-2]).total_seconds()*1000 if self.cv_do_blob else 0, (t4-t3).total_seconds()*1000, (t5-t4).total_seconds()*1000, self.actual_fps)) tt = datetime.now() self.cap = None # Set cap to None to automatically release & disconnect from the camera
class Window(QQuickView): windowClosing = pyqtSignal() def __init__(self, context): QQuickView.__init__(self) self.context = context self.settings = context.settings surface_format = QSurfaceFormat() surface_format.setAlphaBufferSize(8) self.set_cursor_shape("shape_start_cursor") self.setColor(QColor(0, 0, 0, 0)) self.setFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.setResizeMode(QQuickView.SizeRootObjectToView) self.setFormat(surface_format) self.setTitle(_("Deepin screenshot")) self.qimage = QImage(self.settings.tmpImageFile) self.qpixmap = QPixmap() self.qpixmap.convertFromImage(self.qimage) self.window_info = context.windowInfo self._grabPointerStatus = False self._grabKeyboardStatus = False self._grabFocusTimer = self._getGrabFocusTimer() @pyqtSlot(int, int, result="QVariant") def get_color_at_point(self, x, y): if x >= 0 and y >= 0: rgb = self.qimage.pixel(x, y) return [qRed(rgb), qGreen(rgb), qBlue(rgb)] else: return [0, 0, 0] @pyqtSlot(result="QVariant") def get_window_info_at_pointer(self): wInfo = self.window_info.get_window_info_at_pointer() wInfo[0] -= self.x() wInfo[1] -= self.y() return wInfo @pyqtSlot(result="QVariant") def get_cursor_pos(self): ''' get the cursor position relative to the top-left corner of this window ''' pos = QCursor.pos() pos.setX(pos.x() - self.x()) pos.setY(pos.y() - self.y()) return pos @pyqtSlot(str) def set_cursor_shape(self, shape): ''' Set the shape of cursor, the param shape should be one of the keys of the global variable cursor_shape_dict. ''' if cursor_shape_dict.get(shape): pix = QPixmap(cursor_shape_dict[shape]) if shape == "shape_start_cursor": cur = QCursor(pix, hotX=8, hotY=8) elif shape.startswith(CURSOR_SHAPE_COLOR_PEN_PREFIX): cur = QCursor(pix, hotX=0, hotY=pix.height()) else: cur = QCursor(pix, hotX=5, hotY=5) else: cur = QCursor(Qt.ArrowCursor) self.setCursor(cur) @pyqtSlot(str,int,int,int,int) def save_overload(self, style, x, y, width, height): mosaic_radius = 10 blur_radius = 10 p = QPixmap.fromImage(self.grabWindow()) p = p.copy(x,y,width,height) if style == "mosaic": p = p.scaled(width / mosaic_radius, height / mosaic_radius, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) p = p.scaled(width, height) p.save(self.settings.tmpMosaiceFile) elif style == "blur": p = p.scaled(width / blur_radius, height / blur_radius, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) p = p.scaled(width, height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) p.save(self.settings.tmpBlurFile) def _getGrabFocusTimer(self): timer = QTimer() timer.setSingleShot(True) timer.setInterval(100) timer.timeout.connect(self._grabFocusInternal) return timer def _grabFocusInternal(self): if not self._grabPointerStatus: self._grabPointerStatus = self.setMouseGrabEnabled(True) if not self._grabKeyboardStatus: self._grabKeyboardStatus = self.setKeyboardGrabEnabled(True) if not (self._grabPointerStatus and self._grabKeyboardStatus): self._grabFocusTimer.start() def grabFocus(self): self._grabFocusTimer.start() def ungrabFocus(self): self._grabPointerStatus = False self._grabKeyboardStatus = False self.setMouseGrabEnabled(False) self.setKeyboardGrabEnabled(False) @pyqtSlot(str,str,result="QVariant") def get_save_config(self, group_name,op_name): return self.settings.getOption(group_name, op_name) @pyqtSlot(str,str,str) def set_save_config(self,group_name,op_name,op_index): self.settings.setOption(group_name, op_name, op_index) @pyqtSlot(int,int,int,int) def save_screenshot(self, x, y, width, height): pixmap = QPixmap.fromImage(self.grabWindow()) pixmap = pixmap.copy(x, y, width, height) pixmap.save(self.settings.tmpSaveFile) self.hide() self.context.saveScreenshot(pixmap) @pyqtSlot() def enable_zone(self): hotZoneInterface.enableZone() @pyqtSlot() def disable_zone(self): hotZoneInterface.disableZone() @pyqtSlot() def share(self): socialSharingInterface.share("", self.settings.tmpSaveFile) @pyqtSlot(int, int, str, result=bool) def checkKeySequenceEqual(self, modifier, key, targetKeySequence): keySequence = QKeySequence(modifier + key).toString() return keySequence == targetKeySequence @pyqtSlot(int, int, result=str) def keyEventToQKeySequenceString(self, modifier, key): keySequence = QKeySequence(modifier + key).toString() return keySequence def showWindow(self): self.showFullScreen() @pyqtSlot() def closeWindow(self): self.windowClosing.emit() self.close()