def open_image(self, fileName): # fileName, _ = QFileDialog.getOpenFileName(self, "Open File", # QDir.currentPath()) if fileName: image = QImage(fileName) if image.isNull(): QMessageBox.information(self, "Image Viewer", "Cannot load %s." % fileName) return qpix = QPixmap.fromImage(image) self.imageLabel.setPixmap(qpix) self.image_obj = qpix # myScaledPixmap = myPixmap.scaled(self.label.size(), Qt.KeepAspectRatio) self.scaleFactor = 1.0 # myPixmap = QPixmap(fileName) # myScaledPixmap = myPixmap.scaled(self.imageLabel.size(), Qt.KeepAspectRatio) # self.imageLabel.setPixmap(myScaledPixmap) self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() self.change_image_size()
def _convertBitmap(self, path, objects, compress, backcolor, verbose): """ Convert parsed bitmap to NGL_Bitmap object path - path for input bitmap compress - type of compressing - 'None', 'RLE', 'JPG', 'Auto' backcolor - background color for transparent input bitmap verbose - increase output verbosity flag """ if os.path.exists(path): image = QImage(path) name = os.path.basename(path).split(".")[0] ngl_bitmap = NBitmapsConverter.convertQImage(image, name, "format16", compress, backcolor) ngl_bitmap.objects = objects if verbose: inform( ( "converting bitmap {name}, size {width}x{height}, " "compress {compress}, data len {size} bytes" ).format( name=name, width=image.size().width(), height=image.size().height(), compress=ngl_bitmap.compressed, size=ngl_bitmap.data_len_in_bytes, ) ) return ngl_bitmap else: error( ('File "{0}" not found! Expected path - "{1}" not exist' " :( :( :( ").format( bitmap["name"], bitmap["path"] ) )
def open(self): fileName, _ = QFileDialog.getOpenFileName(self, "Open File", QDir.currentPath()) if fileName: image = QImage(fileName) if image.isNull(): QMessageBox.information(self, "Image Viewer", "Cannot load %s." % fileName) return # myPixmap = QPixmap.fromImage(image) qpix = QPixmap.fromImage(image) self.image_obj = qpix self.flag = 1 print(self.height/qpix.size().height()) # self.scaleImage(0.8) self.imageLabel.setPixmap(qpix) self.scaleFactor = 1.0 self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() self.change_image_size()
def convert_resource(): name_list = [] find_files("res", "png", name_list) for name in name_list: print(name) res = QImage(name) res.save(name)
def pixmap(name, size, mode, state): """Returns a (possibly cached) pixmap of the name and size with the default text color. The state argument is ignored for now. """ if mode == QIcon.Selected: color = QApplication.palette().highlightedText().color() else: color = QApplication.palette().text().color() key = (name, size.width(), size.height(), color.rgb(), mode) try: return _pixmaps[key] except KeyError: i = QImage(size, QImage.Format_ARGB32_Premultiplied) i.fill(0) painter = QPainter(i) # render SVG symbol QSvgRenderer(os.path.join(__path__[0], name + ".svg")).render(painter) # recolor to text color painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(i.rect(), color) painter.end() # let style alter the drawing based on mode, and create QPixmap pixmap = QApplication.style().generatedIconPixmap(mode, QPixmap.fromImage(i), QStyleOption()) _pixmaps[key] = pixmap return pixmap
def rgb2qimage(rgb): """Convert the 3D numpy array `rgb` into a 32-bit QImage. `rgb` must have three dimensions with the vertical, horizontal and RGB image axes. ATTENTION: This QImage carries an attribute `ndimage` with a reference to the underlying numpy array that holds the data. On Windows, the conversion into a QPixmap does not copy the data, so that you have to take care that the QImage does not get garbage collected (otherwise PyQt will throw away the wrapper, effectively freeing the underlying memory - boom!).""" if len(rgb.shape) != 3: raise ValueError("rgb2QImage can only convert 3D arrays") if rgb.shape[2] not in (3, 4): raise ValueError("rgb2QImage can expects the last dimension to contain exactly three (R,G,B) or four (R,G,B,A) channels") h, w, channels = rgb.shape # Qt expects 32bit BGRA data for color images: bgra = numpy.empty((h, w, 4), numpy.uint8, 'C') bgra[...,0] = rgb[...,2] bgra[...,1] = rgb[...,1] bgra[...,2] = rgb[...,0] if rgb.shape[2] == 3: bgra[...,3].fill(255) fmt = QImage.Format_RGB32 else: bgra[...,3] = rgb[...,3] fmt = QImage.Format_ARGB32 result = QImage(bgra.data, w, h, fmt) result.ndarray = bgra return result
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 _plat_get_blocks(self, block_count_per_side, orientation): image = QImage(str(self.path)) image = image.convertToFormat(QImage.Format_RGB888) # MYSTERY TO SOLVE: For reasons I cannot explain, orientations 5 and 7 don't work for # duplicate scanning. The transforms seems to work fine (if I try to save the image after # the transform, we see that the image has been correctly flipped and rotated), but the # analysis part yields wrong blocks. I spent enought time with this feature, so I'll leave # like that for now. (by the way, orientations 5 and 7 work fine under Cocoa) if 2 <= orientation <= 8: t = QTransform() if orientation == 2: t.scale(-1, 1) elif orientation == 3: t.rotate(180) elif orientation == 4: t.scale(1, -1) elif orientation == 5: t.scale(-1, 1) t.rotate(90) elif orientation == 6: t.rotate(90) elif orientation == 7: t.scale(-1, 1) t.rotate(270) elif orientation == 8: t.rotate(270) image = image.transformed(t) return getblocks(image, block_count_per_side)
def main(): """ Make a simple test """ global LIBPATH_W LIBPATH_W = r'..\win32' file_name = r'..\images\eurotext.tif' leptonica = get_leptonica() if not leptonica: print("Leptonica was not initialized! Quiting...") sys.exit(-1) leptonica_version = get_version(leptonica) print('Found %s' % leptonica_version) print(get_image_support(leptonica)) if os.path.exists(file_name) == False: print("File {} does not exists. There is nothing to check." .format(file_name)) pix_image = leptonica.pixRead(file_name.encode()) if pix_image: print('w', leptonica.pixGetWidth(pix_image)) print('h', leptonica.pixGetHeight(pix_image)) print('d', leptonica.pixGetDepth(pix_image)) else: print('Image can not be openned') sys.exit() qimage = QImage() qimage = pix_to_qimage(leptonica, pix_image) if qimage: qimage.save(r'..\images\test.png') else: print("PIX conversion was not successful!")
class MainWindow(QMainWindow): def __init__(self,parent=None): super(MainWindow,self).__init__(parent) self.setWindowTitle(self.tr("打印图片")) # 创建一个放置图像的QLabel对象imageLabel,并将该QLabel对象设置为中心窗体。 self.imageLabel=QLabel() self.imageLabel.setSizePolicy(QSizePolicy.Ignored,QSizePolicy.Ignored) self.setCentralWidget(self.imageLabel) self.image=QImage() # 创建菜单,工具条等部件 self.createActions() self.createMenus() self.createToolBars() # 在imageLabel对象中放置图像 if self.image.load("./images/screen.png"): self.imageLabel.setPixmap(QPixmap.fromImage(self.image)) self.resize(self.image.width(),self.image.height()) def createActions(self): self.PrintAction=QAction(QIcon("./images/printer.png"),self.tr("打印"),self) self.PrintAction.setShortcut("Ctrl+P") self.PrintAction.setStatusTip(self.tr("打印")) self.PrintAction.triggered.connect(self.slotPrint) def createMenus(self): PrintMenu=self.menuBar().addMenu(self.tr("打印")) PrintMenu.addAction(self.PrintAction) def createToolBars(self): fileToolBar=self.addToolBar("Print") fileToolBar.addAction(self.PrintAction) def slotPrint(self): # 新建一个QPrinter对象 printer=QPrinter() # 创建一个QPrintDialog对象,参数为QPrinter对象 printDialog=QPrintDialog(printer,self) ''' 判断打印对话框显示后用户是否单击“打印”按钮,若单击“打印”按钮, 则相关打印属性可以通过创建QPrintDialog对象时使用的QPrinter对象获得, 若用户单击“取消”按钮,则不执行后续的打印操作。 ''' if printDialog.exec_(): # 创建一个QPainter对象,并指定绘图设备为一个QPrinter对象。 painter=QPainter(printer) # 获得QPainter对象的视口矩形 rect=painter.viewport() # 获得图像的大小 size=self.image.size() # 按照图形的比例大小重新设置视口矩形 size.scale(rect.size(),Qt.KeepAspectRatio) painter.setViewport(rect.x(),rect.y(),size.width(),size.height()) # 设置QPainter窗口大小为图像的大小 painter.setWindow(self.image.rect()) # 打印 painter.drawImage(0,0,self.image)
def __init__(self, im): im_data = _toqclass_helper(im) QImage.__init__(self, im_data['data'], im_data['im'].size[0], im_data['im'].size[1], im_data['format']) if im_data['colortable']: self.setColorTable(im_data['colortable'])
def dropEvent(self, event): mimeData = event.mimeData() if mimeData.hasUrls(): paths = mimeData.urls() # pick just one image path = paths[0].toLocalFile() fileName = os.path.basename(path) with open(path, "rb") as imgFile: data = imgFile.read() ext = os.path.splitext(path)[1][1:] # TODO: make sure we cleanup properly when replacing an image with # another if ext.lower() != "png": # convert img = QImage(path) data = QByteArray() buffer = QBuffer(data) buffer.open(QIODevice.WriteOnly) img.save(buffer, 'PNG') # format data = bytearray(data) fileName = "%s.png" % os.path.splitext(fileName)[0] imageSet = self._glyph.font.images try: imageSet[fileName] = data except Exception as e: errorReports.showCriticalException(e) return image = self._glyph.instantiateImage() image.fileName = fileName event.setAccepted(True) else: super().dropEvent(event)
def init(self, ddir): """加载lolita.dat配置""" try: conf = json.loads(open(ddir + "/lolita.dat", "rb").read().decode()) normal = conf.get("normal", "").format(DATA_DIR = ddir) move = conf.get("move", "").format(DATA_DIR = ddir) hover = conf.get("hover", "").format(DATA_DIR = ddir) press = conf.get("press", "").format(DATA_DIR = ddir) image = QImage(normal) self.resize(image.size()) # 设置窗口的大小 self.setMinimumSize(image.size()) self.setMaximumSize((image.size())) del image self.movies = { "normal": QMovie(normal), # 普通 "move": QMovie(move), # 移动 "hover": QMovie(hover), # 悬停(会动) "press": QMovie(press), # 按下 } self.setMovie(self.movies.get("normal")).start() # 默认显示 # 声音播放列表 playList = conf.get("playList", []) self.player = LolitaPlayer(playList, ddir) self.player.setCurrentIndex(0) except Exception as e: self.close() traceback.print_exc(e)
def run_search(self): index = self.club_cbox.currentIndex() # Update the logo image url = soccer_club.team_data[index]['logo_url'] req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) data = urllib.request.urlopen(req).read() img = QImage() img.loadFromData(data) pix_img = img.scaled(66, 66, Qt.KeepAspectRatio) self.image_label.setPixmap(QPixmap(pix_img)) # Update the Club information self.club_label3.setText(soccer_club.team_data[index]['team_name'] + "\n\n" + soccer_club.team_data[index]['nick_name'] + "\n\n" + soccer_club.team_data[index]['year_found'] + "\n\n" + soccer_club.team_data[index]['manager'] + "\n\n" + soccer_club.team_data[index]['location'] + "\n\n" + soccer_club.team_data[index]['stadium'] + "\n\n") # Populate the table self.table1.setRowCount(len(soccer_club.team_data[index]['players'])) for number_of_player, key in enumerate(soccer_club.team_data[index]['players'].keys()): for number_of_data, item in enumerate(soccer_club.team_data[index]['players'][key]): self.table1.setItem(number_of_player, number_of_data, QTableWidgetItem(item)) self.table1.resizeRowsToContents()
def get_new_image(self): """ Descript. : """ raw_buffer, width, height = self.get_image() if raw_buffer is not None and raw_buffer.any(): if self.cam_type == "basler": raw_buffer = self.decoder(raw_buffer) qimage = QImage( raw_buffer, width, height, width * 3, QImage.Format_RGB888 ) else: qimage = QImage(raw_buffer, width, height, QImage.Format_RGB888) if self.cam_mirror is not None: qimage = qimage.mirrored(self.cam_mirror[0], self.cam_mirror[1]) if self.scale != 1: dims = self.get_image_dimensions() # should be already scaled qimage = qimage.scaled(QSize(dims[0], dims[1])) qpixmap = QPixmap(qimage) self.emit("imageReceived", qpixmap) return qimage.copy()
class ImageModel(QAbstractTableModel): def __init__(self, parent=None): super(ImageModel, self).__init__(parent) self.modelImage = QImage() def setImage(self, image): self.beginResetModel() self.modelImage = QImage(image) self.endResetModel() def rowCount(self, parent): return self.modelImage.height() def columnCount(self, parent): return self.modelImage.width() def data(self, index, role): if not index.isValid() or role != Qt.DisplayRole: return None return qGray(self.modelImage.pixel(index.column(), index.row())) def headerData(self, section, orientation, role): if role == Qt.SizeHintRole: return QSize(1, 1) return None
def __init__(self, text, parent): super(DragLabel, self).__init__(parent) metric = QFontMetrics(self.font()) size = metric.size(Qt.TextSingleLine, text) image = QImage(size.width() + 12, size.height() + 12, QImage.Format_ARGB32_Premultiplied) image.fill(qRgba(0, 0, 0, 0)) font = QFont() font.setStyleStrategy(QFont.ForceOutline) painter = QPainter() painter.begin(image) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(Qt.white) painter.drawRoundedRect(QRectF(0.5, 0.5, image.width() - 1, image.height() - 1), 25, 25, Qt.RelativeSize) painter.setFont(font) painter.setBrush(Qt.black) painter.drawText(QRect(QPoint(6, 6), size), Qt.AlignCenter, text) painter.end() self.setPixmap(QPixmap.fromImage(image)) self.labelText = text
class ImageViewer(QScrollArea): actualSizeChanged = pyqtSignal(bool) def __init__(self, parent=None): super(ImageViewer, self).__init__(parent, alignment=Qt.AlignCenter) self._actualsize = True self._image = QImage() self.setBackgroundRole(QPalette.Dark) self.setWidget(ImageWidget(self)) def setActualSize(self, enabled=True): if enabled == self._actualsize: return self.setWidgetResizable(not enabled) if enabled and not self._image.isNull(): self.widget().resize(self._image.size()) self._actualsize = enabled self.actualSizeChanged.emit(enabled) def actualSize(self): return self._actualsize def setImage(self, image): self._image = image self._pixmap = None self._pixmapsize = None if self._actualsize: self.widget().resize(image.size()) self.widget().update() def image(self): return self._image def pixmap(self, size): """Returns (and caches) a scaled pixmap for the image.""" if self._pixmapsize == size: return self._pixmap self._pixmap = QPixmap.fromImage( self._image.scaled(size, Qt.KeepAspectRatio, Qt.SmoothTransformation)) self._pixmapsize = size return self._pixmap def startDrag(self): image = self.image() data = QMimeData() data.setImageData(image) drag = QDrag(self) drag.setMimeData(data) if max(image.width(), image.height()) > 256: image = image.scaled(QSize(256, 256), Qt.KeepAspectRatio, Qt.SmoothTransformation) p = QPainter() p.begin(image) p.setCompositionMode(QPainter.CompositionMode_DestinationIn) p.fillRect(image.rect(), QColor(0, 0, 0, 160)) p.end() pixmap = QPixmap.fromImage(image) drag.setPixmap(pixmap) drag.setHotSpot(pixmap.rect().center()) drag.exec_(Qt.CopyAction)
class MyWidget(QWidget): def __init__(self, parent=None): super(MyWidget, self).__init__(parent) self.show_image() def show_image(self): image_path = (r'/Users/chensiye/zhizi.jpg') self.Image = QImage() self.Image.load(image_path) self.resize(800,600) height = self.size().height() width = self.size().width() pixmap = QPixmap.fromImage(self.Image.scaledToHeight(height)) #hbox = QHBoxLayout(self) lbl = QLabel(self) lbl.setPixmap(pixmap) #hbox.addWidget(lbl) #self.setLayout(hbox) pix_x = pixmap.size().width() pix_y = pixmap.size().height() x = int((width - pix_x)/2) screenRect = desktop.screenGeometry(desktop.primaryScreen()) print (type (self.size())) print (self.size()) print (pixmap.size()) print (lbl.size()) print (self.frameGeometry()) lbl.move(x,0) self.move(0,0)
def _addIcon(self): filter_ = self.tr("Images (*.jpg *.jpeg *.bmp *.png *.tiff *.gif);;" "All files (*.*)") fileName, _selectedFilter = QFileDialog.getOpenFileName(self, self.tr("Open File"), self.latestDir, filter_) if fileName: file_info = QFileInfo(fileName) self.latestDir = file_info.absolutePath() image = QImage() if image.load(fileName): maxWidth = 22 maxHeight = 15 if image.width() > maxWidth or image.height() > maxHeight: scaledImage = image.scaled(maxWidth, maxHeight, Qt.KeepAspectRatio, Qt.SmoothTransformation) else: scaledImage = image ba = QByteArray() buffer = QBuffer(ba) buffer.open(QIODevice.WriteOnly) scaledImage.save(buffer, 'png') model = self.model() index = model.index(self.selectedIndex().row(), model.fieldIndex('icon')) model.setData(index, ba)
def set_background(self, data): img = QImage() img.loadFromData(data) pixmap = QPixmap(img) if pixmap.isNull(): return None return pixmap
def createEditor(self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex): editor = QComboBox(parent) if sys.platform == "win32": # Ensure text entries are visible with windows combo boxes editor.setMinimumHeight(self.sizeHint(option, index).height() + 10) editor.addItems(self.items) if self.is_editable: editor.setEditable(True) editor.setInsertPolicy(QComboBox.NoInsert) if self.current_edit_text: editor.setEditText(self.current_edit_text) if self.colors: img = QImage(16, 16, QImage.Format_RGB32) painter = QPainter(img) painter.fillRect(img.rect(), Qt.black) rect = img.rect().adjusted(1, 1, -1, -1) for i, item in enumerate(self.items): color = self.colors[i] painter.fillRect(rect, QColor(color.red(), color.green(), color.blue(), 255)) editor.setItemData(i, QPixmap.fromImage(img), Qt.DecorationRole) del painter editor.currentIndexChanged.connect(self.currentIndexChanged) editor.editTextChanged.connect(self.on_edit_text_changed) return editor
def changeIcon(self): icon = QIcon() for row in range(self.imagesTable.rowCount()): item0 = self.imagesTable.item(row, 0) item1 = self.imagesTable.item(row, 1) item2 = self.imagesTable.item(row, 2) if item0.checkState() == Qt.Checked: if item1.text() == "Normal": mode = QIcon.Normal elif item1.text() == "Active": mode = QIcon.Active elif item1.text() == "Disabled": mode = QIcon.Disabled else: mode = QIcon.Selected if item2.text() == "On": state = QIcon.On else: state = QIcon.Off fileName = item0.data(Qt.UserRole) image = QImage(fileName) if not image.isNull(): icon.addPixmap(QPixmap.fromImage(image), mode, state) self.previewArea.setIcon(icon)
def createImage(self, transform): scaledRect = transform.mapRect(QRect(0, 0, 25, 25)) image = QImage(scaledRect.width(), scaledRect.height(), QImage.Format_ARGB32_Premultiplied) image.fill(0) painter = QPainter(image) painter.scale(transform.m11(), transform.m22()) painter.setRenderHints(QPainter.TextAntialiasing | QPainter.Antialiasing | QPainter.SmoothPixmapTransform) painter.setPen(Qt.NoPen) if Colors.useEightBitPalette: painter.setBrush(QColor(102, 175, 54)) painter.drawEllipse(0, 0, 25, 25) painter.setFont(Colors.tickerFont()) painter.setPen(QColor(255, 255, 255)) painter.drawText(10, 15, self.letter) else: brush = QLinearGradient(0, 0, 0, 25) brush.setSpread(QLinearGradient.PadSpread) brush.setColorAt(0.0, QColor(102, 175, 54, 200)) brush.setColorAt(1.0, QColor(102, 175, 54, 60)) painter.setBrush(brush) painter.drawEllipse(0, 0, 25, 25) painter.setFont(Colors.tickerFont()) painter.setPen(QColor(255, 255, 255, 255)) painter.drawText(10, 15, self.letter) return image
def _render_qwebpage_full(self, web_rect, render_rect, canvas_size): """Render web page in one step.""" if self._qpainter_needs_tiling(render_rect, canvas_size): # If this condition is true, this function may get stuck. raise ValueError("Rendering region is too large to be drawn" " in one step, use tile-by-tile renderer instead") canvas = QImage(canvas_size, self.qt_image_format) if self.is_jpeg(): # White background for JPEG images, same as we have in all browsers. canvas.fill(Qt.white) else: # Preserve old behaviour for PNG format. canvas.fill(0) painter = QPainter(canvas) try: painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.TextAntialiasing, True) painter.setRenderHint(QPainter.SmoothPixmapTransform, True) painter.setWindow(web_rect) painter.setViewport(render_rect) painter.setClipRect(web_rect) self.web_page.mainFrame().render(painter) finally: painter.end() return WrappedQImage(canvas)
def paintQR(self, data): if not data: return qr = qrcode.QRCode() qr.add_data(data) matrix = qr.get_matrix() k = len(matrix) border_color = Qt.white base_img = QImage(k * 5, k * 5, QImage.Format_ARGB32) base_img.fill(border_color) qrpainter = QPainter() qrpainter.begin(base_img) boxsize = 5 size = k * boxsize left = (base_img.width() - size)/2 top = (base_img.height() - size)/2 qrpainter.setBrush(Qt.black) qrpainter.setPen(Qt.black) for r in range(k): for c in range(k): if matrix[r][c]: qrpainter.drawRect(left+c*boxsize, top+r*boxsize, boxsize - 1, boxsize - 1) qrpainter.end() return base_img
def append_items(self, item_data_list): for data in item_data_list: pathname = data["pathname"] path,name = os.path.split(pathname) character = "" if "character" in data: character = data["character"] count = self.table.rowCount() self.table.insertRow(count) # thumbnail img = QImage() img.load(pathname) thumbnail_item = QTableWidgetItem() thumbnail_item.setTextAlignment(Qt.AlignCenter); thumbnail_item.setData(Qt.DecorationRole, QPixmap.fromImage(img)); self.table.setItem(count, 0, thumbnail_item) # name name_item = QTableWidgetItem(name) name_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.table.setItem(count, 1, name_item) # character self.table.setItem(count, 2, QTableWidgetItem(character)) self.image_config.append({ "image":pathname, "character":character, }) self.table.resizeColumnToContents(0)
def createImage(self, transform): if self.type == DemoTextItem.DYNAMIC_TEXT: return None sx = min(transform.m11(), transform.m22()) sy = max(transform.m22(), sx) textItem = QGraphicsTextItem() textItem.setHtml(self.text) textItem.setTextWidth(self.textWidth) textItem.setFont(self.font) textItem.setDefaultTextColor(self.textColor) textItem.document().setDocumentMargin(2) w = textItem.boundingRect().width() h = textItem.boundingRect().height() image = QImage(int(w * sx), int(h * sy), QImage.Format_ARGB32_Premultiplied) image.fill(QColor(0, 0, 0, 0).rgba()) painter = QPainter(image) painter.scale(sx, sy) style = QStyleOptionGraphicsItem() textItem.paint(painter, style, None) return image
def white_outline(image: QImage, sigma=6, repeat=6) -> QImage: if image.format() != QImage.Format_ARGB32: image = image.convertToFormat(QImage.Format_ARGB32) bits = image.bits() bits.setsize(image.byteCount()) shape = (image.width() * image.height()) strides = (4,) alpha = numpy.ndarray(shape=shape, dtype=numpy.uint8, buffer=bits, strides=strides, offset=3) color = numpy.ndarray(shape=shape, dtype=numpy.uint8) color.fill(255) alpha = alpha.reshape((image.width(), image.height())) alpha = alpha.astype(numpy.float) alpha = gaussian_filter(alpha, sigma=sigma) alpha *= repeat numpy.clip(alpha, 0, 255, out=alpha) alpha = alpha.astype(numpy.uint8) alpha = alpha.reshape(shape) arr = numpy.dstack((color, color, color, alpha)) return QImage(arr, image.width(), image.height(), QImage.Format_ARGB32)
def __init__(self, argv): super(Worker, self).__init__() self._isRunning = True q = QImage() q.load("test/by.png") self.frameRendered.emit(q) self.pass1 = pass1.Pass1(argv=argv)
def draw_contour_points(self): self.eveSite_dict = {} text = '' cntList = [] contours_list = self.combox_checkBox.getCheckItem() conn = MySqlConn() for contour in contours_list: text = text + contour + "," year_change = conn.year_change(self.choose_year) cntB = conn.contour_points(year_change[0], contour) cntA = loads(cntB[0][0]) cntList.append(cntA) self.qlineText.setText(text) imgb = cv.imread("img/" + self.choose_year + ".jpg") imgB = cv.medianBlur(imgb, 71) if self.baseMap_flag: img_contour = cv.drawContours(imgB.copy(), cntList, -1, (255, 255, 255), 3) elif not self.baseMap_flag: background = np.ones(imgB.shape, np.uint8) * 255 img_contour = cv.drawContours(background.copy(), cntList, -1, (0, 0, 255), 2) image_height, image_width, image_depth = img_contour.shape QIm = cv.cvtColor(img_contour, cv.COLOR_BGR2RGB) pil_im = Image.fromarray(QIm) icon = Image.open("img/icon.png") site = Image.open("img/site.png") if self.site_flag: site_list = self.site_show(self.choose_year, contours_list) for key, value in site_list.items(): draw = ImageDraw.Draw(pil_im) l_value = int(value[0]) // 2 font = ImageFont.truetype("font/simfang.ttf", 15, encoding="utf-8") c_value = value[1].split(",", 1) x_l = float(c_value[0][1:].rstrip()) y_l = float(c_value[1][:-1].rstrip()) icon_x = int(0.8 * l_value) icon_y = int(0.5 * l_value) y_2 = y_l - icon_y x_2 = x_l + 0.6 * icon_x x_3 = x_2 + 6 y_3 = y_2 - 10 icon = icon.resize((icon_x, icon_y), Image.ANTIALIAS) r, g, b, a = icon.split() pil_im.paste(icon, (int(x_2), int(y_2)), mask=a) if key in self.choose_sites: mark = self.choose_sites.index(key) + 1 self.eveSite_dict[mark] = (x_2, y_2) site = site.resize((10, 10), Image.ANTIALIAS) r1, g1, b1, a1 = site.split() pil_im.paste(site, (int(x_3), int(y_3)), mask=a1) draw.text((x_l, y_l), (str(mark) + key), (255, 255, 255), font=font) else: draw.text((x_l, y_l), key, (0, 0, 0), font=font) for i in range(1, len(self.eveSite_dict)): value1 = self.eveSite_dict[i] value2 = self.eveSite_dict[i + 1] draw.line((value1[0], value1[1], value2[0], value2[1]), fill=(150, 150, 255), width=5) QIm = np.array(pil_im) QIm = QImage(QIm.data, image_width, image_height, image_width * image_depth, QImage.Format_RGB888) self.viewer.setPhoto(QPixmap.fromImage(QIm))
def toQImage(im, copy=False): if im is None: return QImage() im = np.require(im, np.uint8, 'C') if im.dtype == np.uint8: if len(im.shape) == 2: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8) qim.setColorTable(gray_color_table) return qim.copy() if copy else qim elif len(im.shape) == 3: if im.shape[2] == 3: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888) return qim.copy() if copy else qim elif im.shape[2] == 4: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32) return qim.copy() if copy else qim
def capture(): global mainImg global currentSequence queue = [] queueSize = 6 resetCount = 0 resetCap = 65 threshold_initial = 75 cropBottomPercent = 0.33 state = "C" videoCapture = cv2.VideoCapture(0) cv2.namedWindow("image") cv2.createTrackbar("threshold", "image", threshold_initial, 255, lambda x: x) while True: _, colorCapture = videoCapture.read() face = getFace(colorCapture) if face is not None: eyeWidth, eye1, eye2 = getEyes(face) eyes = [eye1, eye2] for eye in eyes: if eye is not None: th = cv2.getTrackbarPos("threshold", "image") eye = cropBottom(eye, cropBottomPercent) keypoints = getBlobs(eye, th) for keypoint in keypoints: value = (keypoint.pt[0] * 100) / eyeWidth if len(queue) >= queueSize: queue.pop() queue.insert(0, value) act = activation(sum(queue) / len(queue)) if act < 25: if state != "R": resetCount = 0 state = "R" currentSequence += state myWin.updatePattern() print(currentSequence) #print(state) elif act > 75: if state != "L": resetCount = 0 state = "L" currentSequence += state myWin.updatePattern() print(currentSequence) #print(state) else: resetCount += 1 if resetCount >= resetCap: resetCount = 0 myWin.updateMessage() currentSequence = "" myWin.updatePattern() myWin.updateMessage() print("RESET") if state != "C": state = "C" currentSequence += state myWin.updatePattern() print(currentSequence) #print(state) break cv2.rectangle(eye, (0, 0), (eye.shape[1] - 1, eye.shape[0] - 1), (0, 255, 255)) eye = cv2.drawKeypoints( eye, keypoints, eye, (255, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) colorCapture = cv2.flip(colorCapture, 1) mainImg = QImage(colorCapture.data, colorCapture.shape[1], colorCapture.shape[0], QImage.Format_RGB888).rgbSwapped() _, g = cv2.threshold( cv2.cvtColor(cv2.flip(colorCapture, 1), cv2.COLOR_BGR2GRAY), cv2.getTrackbarPos('threshold', 'image'), 255, cv2.THRESH_BINARY) g = cv2.erode(g, None, iterations=3) g = cv2.dilate(g, None, iterations=4) cv2.imshow('image 2', g) if cv2.waitKey(1) & 0xFF == ord('q'): break videoCapture.release() cv2.destroyAllWindows()
def run(self): #线程执行的操作 -> 实时识别 print("启动实时识别的线程") # Load Yolo net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg") classes = [] with open("coco.names", "r") as f: classes = [line.strip() for line in f.readlines()] layer_names = net.getLayerNames() output_layers = [ layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers() ] colors = np.random.uniform(0, 255, size=(len(classes), 3)) # Initialize frame rate calculation frame_rate_calc = 1 freq = cv2.getTickFrequency() cap = cv2.VideoCapture(0) # 打开摄像头 print("实时识别的线程加载完毕") while True: print("正在识别") ret, frame = cap.read() height, width, channels = frame.shape # Detecting objects blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False) net.setInput(blob) outs = net.forward(output_layers) # Showing informations on the screen class_ids = [] confidences = [] boxes = [] for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.4: # Object detected center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) # Rectangle coordinates x = int(center_x - w / 2) y = int(center_y - h / 2) boxes.append([x, y, w, h]) confidences.append(float(confidence)) class_ids.append(class_id) indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) price = 0 meal = '' font = cv2.FONT_HERSHEY_SIMPLEX for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) color = colors[i] cv2.rectangle(frame, (x, y), (x + w, y + h), color, 1) frame = cv2ImgAddText(frame, label, x, y) price = price + sumPrice(label) meal = meal + label + '\n' self.update_variety.emit(meal) # print('total price is ' + str(price)) frame = cv2ImgAddText(frame, '总价为: ' + str(price), 15, 20) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) img = QImage(frame.data, width, height, QImage.Format_RGB888) self.update_picture.emit(img) #传递信号 self.update_price.emit("总价为: " + str(price))
class Window(QtWidgets.QMainWindow): SCENE_WIDTH = 1191 SCENE_HEIGHT = 725 def __init__(self): QtWidgets.QWidget.__init__(self) uic.loadUi("window.ui", self) self.scene = MyScene(self, 0, 0, self.SCENE_WIDTH, self.SCENE_HEIGHT) self.main_scene.setScene(self.scene) self.image = QImage(self.SCENE_WIDTH, self.SCENE_HEIGHT, QImage.Format_RGB32) self.image.fill(QColorConstants.White) self.add_dot_btn.clicked.connect(self.addPoint) self.clean_screen_btn.clicked.connect(self.clean) self.color_chooser.clicked.connect(self.__chooseColor) self.close_figure_btn.clicked.connect(self.closePoly) self.paint_figure_btn.clicked.connect(self.__paintOverFigure) self.color = QColor(0, 0, 0) self.pen = QPen(self.color) self.last_point = None self.edges = [] self.points = [] self.seed_point = QPoint(0, 0) self.backGroundColor = QColorConstants.DarkMagenta self.lineColor = QColorConstants.Black scene = QtWidgets.QGraphicsScene(0, 0, 68, 20) image = QPixmap(68, 20) image.fill(self.backGroundColor) scene.addPixmap(image) self.color_viewer.setScene(scene) def __getPoint(self): return QPoint(self.x_spinbox.value(), self.y_spinbox.value()) def addPoint(self, x_coord=None, y_coord=None): if x_coord is not None and y_coord is not None: x = QTableWidgetItem(str(x_coord)) y = QTableWidgetItem(str(y_coord)) self.drawPolyHandler(QPoint(int(x_coord), int(y_coord))) else: dot = self.__getPoint() x = QTableWidgetItem(str(dot.x())) y = QTableWidgetItem(str(dot.y())) self.drawPolyHandler(dot) curr_rows = self.coord_table.rowCount() self.coord_table.insertRow(curr_rows) self.coord_table.setItem(curr_rows, 0, x) self.coord_table.setItem(curr_rows, 1, y) def __chooseColor(self): self.backGroundColor = QColorDialog.getColor() if self.color.isValid(): scene = QtWidgets.QGraphicsScene(0, 0, 68, 20) image = QPixmap(68, 20) image.fill(self.backGroundColor) scene.addPixmap(image) self.color_viewer.setScene(scene) def clean(self): self.scene.clear() self.coord_table.clear() self.coord_table.setRowCount(0) self.last_point = None self.edges = [] self.points = [] self.image.fill(QColorConstants.White) def drawPolyHandler(self, p: QPoint): if self.last_point is not None: self.scene.addLine(self.last_point.x(), self.last_point.y(), p.x(), p.y(), self.pen) self.edges.append(Edge(self.last_point, p)) else: self.first_point = p self.last_point = p self.points.append(p) def drawEdges(self): pix = QPixmap() painter = QPainter() painter.begin(self.image) pen = QPen(QColorConstants.Black) pen.setWidth(1) painter.setPen(pen) for edge in self.edges: painter.drawLine(edge.l.x(), edge.l.y(), edge.r.x(), edge.r.y()) painter.end() pix.convertFromImage(self.image) self.scene.clear() self.scene.addPixmap(pix) def closePoly(self): if len(self.edges) > 1: last = self.edges[-1].r self.scene.addLine(self.first_point.x(), self.first_point.y(), last.x(), last.y(), self.pen) self.last_point = None self.edges.append(Edge(self.first_point, last)) def __delay(self): QtWidgets.QApplication.processEvents(QEventLoop.AllEvents, 1) def trace_edge(self, edge: Edge): ''' Traces edge with bresenhem algo ''' x1 = edge.l.x() x2 = edge.r.x() y1 = edge.l.y() y2 = edge.r.y() dx = int(x2 - x1) dy = int(y2 - y1) sx = math.copysign(1, dx) sy = math.copysign(1, dy) dx = abs(dx) dy = abs(dy) swap = False if (dy <= dx): swap = False else: swap = True dx, dy = dy, dx e = int(2 * dy - dx) x = int(x1) y = int(y1) for i in range(dx + 1): self.image.setPixel(int(x), int(y), self.backGroundColor.rgb()) if (e >= 0): if (swap): x += sx else: y += sy e = e - 2 * dx if (e < 0): if (swap): y += sy else: x += sx e = e + 2 * dy self.redraw() def trace_figure(self): for edge in self.edges: self.trace_edge(edge) def __paintOverFigure(self): self.scene.clear() self.trace_figure() stack = [self.seed_point] color = self.backGroundColor.rgb() start = perf_counter() while len(stack): if self.do_slow_drawing.isChecked(): QtWidgets.QApplication.processEvents() point = stack.pop() self.image.setPixel(int(point.x()), int(point.y()), color) x, y = point.x() + 1, point.y() while self.image.pixelColor(int(x), int(y)).rgb() not in [ self.backGroundColor.rgb(), self.lineColor.rgb() ]: self.image.setPixel(int(x), int(y), color) x += 1 rborder = x - 1 x = point.x() - 1 while self.image.pixelColor(int(x), int(y)).rgb() not in [ self.backGroundColor.rgb(), self.lineColor.rgb() ]: self.image.setPixel(int(x), int(y), color) x -= 1 self.redraw() lborder = x + 1 sign = [1, -1] for i in sign: x = lborder y = point.y() + i while x <= rborder: is_exist = False while self.image.pixelColor(int(x), int(y)).rgb() not in [ self.backGroundColor.rgb(), self.lineColor.rgb() ] and x <= rborder: is_exist = True x += 1 if is_exist: stack.append(QPoint(int(x - 1), int(y))) xi = x while self.image.pixelColor(int(x), int(y)).rgb() not in [ self.backGroundColor.rgb(), self.lineColor.rgb() ] and x <= rborder: x += 1 if x == xi: x += 1 end = perf_counter() if not self.do_slow_drawing.isChecked(): self.time_label.setText(f"{end - start:.6}") self.drawEdges() def redraw(self): self.scene.clear() self.scene.addPixmap(QPixmap.fromImage(self.image)) def update_seed(self, seed: QPoint): self.seed_point = seed self.seed_x.setText(str(seed.x())) self.seed_y.setText(str(seed.y()))
def copyfig_to_clipboard(self): """Saves the current BRF figure to the clipboard.""" buf = io.BytesIO() self.save_brf_fig(buf) QApplication.clipboard().setImage(QImage.fromData(buf.getvalue())) buf.close()
from PyQt5.QtCore import Qt, QRectF, QEvent from PyQt5.QtGui import QColor, QPen, QBrush, QCursor, QImage, QPainter from PyQt5.QtWidgets import QWidget, QApplication from PyQt5.uic import loadUi from types import MethodType import sys import numpy as np app = QApplication(sys.argv) ##################### importing the file made qt designer ##################### w = loadUi("03-circles.ui") #################### image for saving the picture of circles ################## img = QImage(w.widget.width(), w.widget.height(), QImage.Format_RGB32) img.fill(Qt.white) # image appears white in the beginning (not black) ################################ set painter ################################## imgPainter = QPainter() # first painter painter = QPainter() # second painter ################################## set pen #################################### line_drawer = QPen() line_drawer.setWidth(4) ############################ set switch and lists ############################# switch = 0 # switch at 0 for first circle, at 1 for second circle start_point_list = [0] end_point_list = [0]
def __init__(self): super().__init__() self.setupUi(self) self.client = Client("localhost", 6666) self.client.connectWithServer() self.client.run() ''' initCards : 랜덤으로 줘야 해 - 서버에서 해서 뿌려야 할 것 같음. 진영 용택 논의 필요 clientIndex : 서버에서 받아야 함 beginnerIndex : 서버에서 받아야 함 ''' self.beginnerIndex = 0 self.clientIndex = 0 self.isTurn = 1 self.gm = GM(initCards(5), self.clientIndex, self.beginnerIndex) self.gm.distributeCards() self.btnGiveHint.clicked.connect(self.clickedGiveHint) # 배경 사진 넣기 background = QImage("background.jpeg") palette = QPalette() palette.setBrush(10, QBrush(background)) self.setPalette(palette) self.notice.setText(" ") self.remainDeck.setText("남은 카드 \n%d" % len(self.gm.cards)) # 임의 부여함. # 들고 있는 카드의 list self.deckList = [[ self.player0Deck0, self.player0Deck1, self.player0Deck2, self.player0Deck3 ], [ self.player1Deck0, self.player1Deck1, self.player1Deck2, self.player1Deck3 ], [ self.player2Deck0, self.player2Deck1, self.player2Deck2, self.player2Deck3 ], [ self.player3Deck0, self.player3Deck1, self.player3Deck2, self.player3Deck3 ]] # 낸 카드의 list self.drpoedCardList = [ self.playedRed, self.playedGreen, self.playedBlue, self.playedWhite, self.playedYellow ] # 버린 카드의 list self.thrownCardList = [[ self.throwR1, self.throwR2, self.throwR3, self.throwR4, self.throwR5 ], [ self.throwG1, self.throwG2, self.throwG3, self.throwG4, self.throwG5 ], [ self.throwB1, self.throwB2, self.throwB3, self.throwB4, self.throwB5 ], [ self.throwW1, self.throwW2, self.throwW3, self.throwW4, self.throwW5 ], [ self.throwY1, self.throwY2, self.throwY3, self.throwY4, self.throwY5 ]] # 힌트 토큰의 list self.hintTokenList = [ self.hintToken0, self.hintToken1, self.hintToken2, self.hintToken3, self.hintToken4, self.hintToken5, self.hintToken6, self.hintToken7 ] # 목숨 토큰의 list self.lifeTokenList = [ self.lifeToken0, self.lifeToken1, self.lifeToken2 ] for card in self.drpoedCardList: card.setText("0") print(type(self.player3Deck2)) for deck in self.gm.playerDecks: print(deck) for i, deck in enumerate(self.deckList): # clinet 위치를 어떻게 잡느냐가 관건.. # 아래 주석은 자신의 카드를 가리기 위한 코드. test 시에는 무시하고 진행한다. ''' if i == self.clientIndex: for j in range(4): SetCardDesign("mine", deck[j]) ''' for j in range(4): SetCardDesign( self.gm.playerDecks[i].getCardOrNone(j).getColor(), deck[j]) deck[j].setText(str(self.gm.playerDecks[i].getCardOrNone(j))) self.btnThrow.clicked.connect(self.ShowThrowDeck) self.btnDrop.clicked.connect(self.ShowDropDeck) self.btnGiveHint.clicked.connect(self.ShowGiveHint) # 다음 내용은 불변. # 창 아이콘 self.setWindowIcon(QIcon('Hanabi.PNG')) # 창크기 조절, 출력 self.setFixedSize(1910, 990) self.setWindowTitle('Hanabi') self.show()
def _build_image(self, frame): height, width, channel = frame.shape bytesPerLine = 3 * width return QImage(frame.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped()
def init(cls): cls.Types[cls.Success] = QPixmap(QImage.fromData(base64.b64decode( 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADrElEQVRYR8WXXYgVZRjH///3bIntQkGKc7rpUwPpIkLRpHKFIvCii0DpYneniAhCZDajW1eELnP0IghvdvwgyIuoi+7CU0JERhdCoBa1EHiOrF0YrVnuef/xzpk5O2d2Po6usQOHA+888zy/5/N9X+I2nvb+yd00jVcAPQNgffJzGuZ7P/4o2/2ieezkl8OqZZ3gfDDRXIR5m+AkgMfq5JP3vwo6OQL78frwVLvqm0qAdjA1Y8C3BDw0pOEBMQJXLHS8GZ6YKfu+FODqtP+phD13Yjj/DYkzG45Ee4t0FQJ0Av83AI/cDeMZHXNeGD26DC6/0A6m5gmuu8vGY3WCrjXDE654+89ABNqB/w2B50uMt5L18ZXACTjXDKMXUh19AFdwBA9WKG95YbSrE/jKyKRQdUwD0IIOpYUZA7hWs2j8UFPthQAOqsp6J/DPAhgAcN1h0N3iWjQGqPC+Jejr1ICjvhpM9aMkMKOYn9vGP6dM994zqXwSsWUAST3EUUgA/EsENhV40hJ4aAlgttUOXu8bJeSUx0+Dja1W3T0C3k+Wrnth9EBRBHoAuNwMoyfpFGYV3WYNpOI/eWH0VCeY+hngE26RwC8bwmhjGUAPgrvYmfaPQthfV0UAimrAGfpT5IQVGgb6rK9H+M47Gj1bOVOIY+wE/vcAtta0Xvw6k9OeuPCwjF67KXN5LXSWxH0SrsSvxI9ocBHShQrnzjuA0qmXbZciJZ3A/9YLox0DY9vgRe/D6Ks/DryxedHamZpxPucA/gIwOkQK4pwBdjw7L9ycX8GesVAL4KLQKyoeLAJwa81wtnQg5QZX3s8YoHLjEbUNFj7Jd8oAkqjszGsvmJx5kTgFVUUIw5GNwuIHLsx5b513RVCJlcKuyRGcr23DtRx58IZuHSf4aty3xEuQdiSKxlcE4NqwbhB5YcTOe5Oj7JpzVnyX1ASEN1NPVgIQO+QUtYPSUXz6b3DfKLGd95gLi//aTQZ2p8D+EetOi7A/insAxVuxoN2CWWOg08boOWN1swvuVe+A+nia65oWLjw/pDOmcjuOwx/4RwAEAObcxtQMZ2edQZcW3WpsBu06yIzBaIziGKAxQWuyUBRfBrE9XVu2HRdFwW0mxmi6a3kYwNNLOcfvBrgo4hIgd+RegLAAsPcvLMiwOwigT0B4SzpyB5L0RcGR7DqA+4eZksPKlB7JliBW8VCaQtRNx2G9zckNdyxPP1rVi0kmHat3NUshVvVyms/1/3E9/w98zfU0PZUJ8gAAAABJRU5ErkJggg=='))) cls.Types[cls.Close] = QPixmap(QImage.fromData(base64.b64decode( 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAeElEQVQ4T2NkoBAwUqifgboGzJy76AIjE3NCWmL0BWwumzV/qcH/f38XpCfHGcDkUVwAUsDw9+8GBmbmAHRDcMlheAGbQnwGYw0DZA1gp+JwFUgKZyDCDQGpwuIlrGGAHHAUGUCRFygKRIqjkeKERE6+oG5eIMcFAOqSchGwiKKAAAAAAElFTkSuQmCC')))
class pyGraverGUI(QDialog): # ####################################################################### # init def __init__(self, parent=None): super().__init__(parent) uic.loadUi(op.join(op.dirname(__file__), "pyGraverGUI.ui"), self) # self.imgToBurn = QImage() self.graver = None self.previewMode = False self.pbUp.clicked.connect(self.onClickUp) self.pbDown.clicked.connect(self.onClickDown) self.pbLeft.clicked.connect(self.onClickLeft) self.pbRight.clicked.connect(self.onClickRight) self.pbBurn.clicked.connect(self.onClickBurn) self.pbGo.clicked.connect(self.onClickGo) self.pbStop.clicked.connect(self.onClickStop) self.pbPause.clicked.connect(self.onClickPause) self.pbConnect.clicked.connect(self.onClickConnect) self.pbRefresh.clicked.connect(self.onClickRefresh) self.pbPreview.clicked.connect(self.onClickPreview) self.pbLoad.clicked.connect(self.onClickLoad) self.pbGenerate.clicked.connect(self.onClickGenerate) self.onClickRefresh() def onClickUp(self): if self.graver is None: print("please connect before") return self.graver.moveUp() def onClickDown(self): print("onClickDown") if self.graver is None: print("please connect before") return self.graver.moveDown() def onClickLeft(self): if self.graver is None: print("please connect before") return self.graver.moveLeft() def onClickRight(self): if self.graver is None: print("please connect before") return self.graver.moveRight() def onClickLoad(self): print("onClickLoad") self.imgToBurn = QImage(self.leFileName.text()) self.laImg.setPixmap(QPixmap.fromImage(self.imgToBurn)) def onClickGenerate(self): doc = self.teText.document() font = QFont() font.setPointSizeF(self.sbFontSize.value()) doc.setDefaultFont(font) m = QFontMetricsF(font) nbLines = doc.lineCount() width = max([m.width(ll) for ll in doc.toPlainText().split("\n")]) pixmap = QPixmap(width*1.2, m.lineSpacing()*nbLines*1.2) pixmap.fill(Qt.white) painter = QPainter(pixmap) painter.setRenderHint(QPainter.Antialiasing, True) doc.drawContents(painter) painter.end() self.laImg.setPixmap(pixmap) self.imgToBurn = QImage(pixmap.toImage()) def onClickPreview(self): if self.graver is None: print("please connect before") return if self.previewMode: self.graver.stopShowWindow() self.previewMode = False else: x, y = self.sbPosX.value(), self.sbPosY.value() w = self.imgToBurn.width() h = self.imgToBurn.height() self.graver.showWindow(x, y, w, h) self.previewMode = True def onClickBurn(self): if self.graver is None: print("please connect before") return if self.previewMode: self.onClickPreview() x, y = self.sbPosX.value(), self.sbPosY.value() self.graver.sendImage(self.imgToBurn, x, y) self.refreshProgressBar() def onClickGo(self): if self.graver is None: print("please connect before") return if self.previewMode: self.onClickPreview() self.graver.moveXY(self.sbPosX.value(), self.sbPosY.value()) def onClickStop(self): if self.graver is None: print("please connect before") return self.graver.stopCarving() self.graver.close() def onClickPause(self): if self.graver is None: print("please connect before") return self.graver.pauseCarving() def onClickConnect(self): port = self.cbListPort.currentText() if self.graver is not None: self.graver.close() self.graver = None self.graver = pyGraver(port) def onClickRefresh(self): self.cbListPort.clear() for port in serial.tools.list_ports.comports(): print(port) self.cbListPort.addItem(port.device) def refreshProgressBar(self): if self.graver is not None: percent = self.graver.carvingPercentProgress self.pbProgressBurn.setValue(percent) if percent < 100: QTimer.singleShot(200, self.refreshProgressBar) else: self.graver.carvingPercentProgress = 0
def onClickLoad(self): print("onClickLoad") self.imgToBurn = QImage(self.leFileName.text()) self.laImg.setPixmap(QPixmap.fromImage(self.imgToBurn))
def display_thresh(self): #initialize output images (numpy array rep) cam_trsh = numpy.zeros((640,480,3), numpy.uint8) out_trsh1 = numpy.zeros((300,300,3), numpy.uint8) out_trsh2 = numpy.zeros((300,300,3), numpy.uint8) out_trsh2[::] = 255 #default white #calculate thresh, if histogram exists if self.hist_exist: #will detect hand anywhere in the frame if self.handCheckBox.isChecked(): #referenced face detection tutorial from Real Python [2] # Detect faces in the image faces = self.face_cascade.detectMultiScale( cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY), scaleFactor=1.1, #bring up to 1.3 for faster but less accurate detection minNeighbors=5, minSize=(60, 60), flags = cv2.CASCADE_SCALE_IMAGE ) #cover faces in the image for (x, y, w, h) in faces: cv2.rectangle(self.image, (x-25, y-25), (x+w+25, y+h+25), (0, 0, 0), -1) #calculate thresh of the whole frame cam_trsh = self.calc_thresh(self.image) #referenced contour detection tutorial from pyimagesearch [3] gray = cv2.cvtColor(cam_trsh.copy(), cv2.COLOR_BGR2GRAY) cnts = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] if len(cnts) > 0: #calculate boundaries of the largest contour c = max(cnts, key=cv2.contourArea) hull = cv2.convexHull(c) x,y,w,h = cv2.boundingRect(c) #calculate the center cntr_x, cntr_y = x+w//2, y+h//2 #calculate two points for the square cropping bounds if w > h : l = w // 2 x1, y1, x2, y2 = cntr_x-l, y+h-l*2, cntr_x+l, y+h else: l = h // 2 x1, y1, x2, y2 = cntr_x-l, cntr_y-l, cntr_x+l, cntr_y+l #output thresh for translation out_trsh1 = cam_trsh[y1:y2, x1:x2].copy() #output thresh with contours cv2.drawContours(cam_trsh, [c], -1, (255, 0, 255), 2) #magenta contour cv2.drawContours(cam_trsh, [hull], -1, (0, 255,255), 2) #yellow convex hull out_trsh2 = cam_trsh[y1:y2, x1:x2].copy() #bounding rectangle drawn on webcam tresh cv2.rectangle(cam_trsh,(x1,y1),(x2,y2),(255,255, 0), 2) #cyan square else: #will only traslate hand detected within a static box x, y, w, h = 300, 100, 300, 300 out_trsh1 = self.calc_thresh(self.image[y:y+h, x:x+w]) cam_trsh = self.calc_thresh(self.image) #output webcam processed thresh out_img = QImage(cam_trsh,cam_trsh.shape[1],cam_trsh.shape[0],cam_trsh.strides[0],QImage.Format_RGB888) self.threshDisplay.setPixmap(QPixmap.fromImage(out_img.rgbSwapped())) self.threshDisplay.setScaledContents(True) #output isolated thresh for translation out_img = QImage(out_trsh1,out_trsh1.shape[1],out_trsh1.shape[0],out_trsh1.strides[0],QImage.Format_RGB888) self.threshDisplay1.setPixmap(QPixmap.fromImage(out_img.rgbSwapped())) self.threshDisplay1.setScaledContents(True) #output thresh with contours out_img = QImage(out_trsh2,out_trsh2.shape[1],out_trsh2.shape[0],out_trsh2.strides[0],QImage.Format_RGB888) self.threshDisplay2.setPixmap(QPixmap.fromImage(out_img.rgbSwapped())) self.threshDisplay2.setScaledContents(True) #will translate the output thresh when translate box is checked #translates every ten frames to slow down the tranlsation rate if self.transCheckBox.isChecked() and self.frame_count > 10: self.translate(out_trsh1) self.frame_count = 0
def createArrowBackground(self, transform): scaledRect = transform.mapRect( QRect(0, 0, self.logicalSize.width(), self.logicalSize.height())) image = QImage(scaledRect.width(), scaledRect.height(), QImage.Format_ARGB32_Premultiplied) image.fill(QColor(0, 0, 0, 0).rgba()) painter = QPainter(image) painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.setRenderHint(QPainter.Antialiasing) painter.setPen(Qt.NoPen) if Colors.useEightBitPalette: painter.setPen(QColor(120, 120, 120)) if self.pressed: painter.setBrush(QColor(60, 60, 60)) elif self.highlighted: painter.setBrush(QColor(100, 100, 100)) else: painter.setBrush(QColor(80, 80, 80)) else: outlinebrush = QLinearGradient(0, 0, 0, scaledRect.height()) brush = QLinearGradient(0, 0, 0, scaledRect.height()) brush.setSpread(QLinearGradient.PadSpread) highlight = QColor(255, 255, 255, 70) shadow = QColor(0, 0, 0, 70) sunken = QColor(220, 220, 220, 30) normal1 = QColor(200, 170, 160, 50) normal2 = QColor(50, 10, 0, 50) if self.pressed: outlinebrush.setColorAt(0, shadow) outlinebrush.setColorAt(1, highlight) brush.setColorAt(0, sunken) painter.setPen(Qt.NoPen) else: outlinebrush.setColorAt(1, shadow) outlinebrush.setColorAt(0, highlight) brush.setColorAt(0, normal1) if not self.highlighted: brush.setColorAt(1, normal2) painter.setPen(QPen(outlinebrush, 1)) painter.setBrush(brush) painter.drawRect(0, 0, scaledRect.width(), scaledRect.height()) xOff = scaledRect.width() / 2 yOff = scaledRect.height() / 2 sizex = 3.0 * transform.m11() sizey = 1.5 * transform.m22() if self.type == TextButton.UP: sizey *= -1 path = QPainterPath() path.moveTo(xOff, yOff + (5 * sizey)) path.lineTo(xOff - (4 * sizex), yOff - (3 * sizey)) path.lineTo(xOff + (4 * sizex), yOff - (3 * sizey)) path.lineTo(xOff, yOff + (5 * sizey)) painter.drawPath(path) return image
def img_custom_logo(self): # load the custom PARSE icon graphic, unused at present (02.2021) return QImage(self.get_resource('custom_logo_256.png'))
def img_info_icon(self): # load the info icon graphic, used for tooltips return QImage(self.get_resource('info_icon.png'))
def img_parse_logo(self): # load the large PARSE graphic to be shown on the start window return QImage(self.get_resource('PARSE_logo.png'))
def img_usc_logo(self): # load the small USC logo to be shown on the start window return QImage(self.get_resource('usc_logo_2.png'))
class Interface(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): QWidget.__init__(self) self.statusBar() self.setGeometry(600, 300, 390, 250) self.setWindowTitle('Objects Update') self.setWindowIcon(QIcon('colliers.png')) self.oImage = QImage( "/home/EU/yury.festa/PycharmProjects/COLLIERS/apps/background.png") self.sImage = self.oImage.scaled(QSize( 390, 250)) # resize Image to widgets size self.palette = QPalette() self.palette.setBrush(10, QBrush(self.sImage)) # 10 = Windowrole self.setPalette(self.palette) self.UpdateCian_btn() self.UpdateAvito_btn() # self.setStatusBar(self.statusBar) # self.statusBar.show() self.show() def UpdateCian_btn(self): btn = QPushButton('Update Cian', self) btn.resize(btn.sizeHint()) btn.move(50, 50) btn.clicked.connect(self.openFileNameDialog_for_cian) def UpdateAvito_btn(self): btn = QPushButton('Update Avito', self) btn.resize(btn.sizeHint()) btn.move(240, 50) btn.clicked.connect(self.openFileNameDialog_for_avito) def openFileNameDialog_for_cian(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName( self, "QFileDialog.getOpenFileName()", "", "All Files (*);;Python Files (*.py)", options=options) if fileName: print(fileName) process = UpdateBase() process.get_data(fileName) process.login() process.update(QMainWindow) # process.pushUpdate() return fileName def openFileNameDialog_for_avito(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName( self, "QFileDialog.getOpenFileName()", "", "All Files (*);;Python Files (*.py)", options=options) # data = pd.read_excel(fileName) if fileName: print(fileName) return fileName
def _convert_array_to_qimage(a): cv2.cvtColor(a, cv2.COLOR_BGR2RGB, a) height, width, channels = a.shape bytes_per_line = channels * width return QImage(a.data, width, height, bytes_per_line, QImage.Format_RGB888)
def open(self): options = QFileDialog.Options() filename, _ = QFileDialog.getOpenFileName( self, 'Sélectionner un fichier', '', 'Images (*.pdf *.png *.jpeg *.jpg *.bmp *.gif)', options=options) self.filename = filename if developerMode: self.start = time.time() print('Open and convert file:') print('\tGot filename: ' + filename + ' => ' + str(time.time() - self.start)) if filename[-3:] == 'pdf': file = convert_from_path(filename, 300) filename = 'tmp/' + filename.split('/')[-1][:-3] + 'png' print(filename) file[0].save(filename, 'PNG') if developerMode: print('\tFile converted with success => ' + str(time.time() - self.start)) if filename: image = QImage(filename) if image is None: QMessageBox.information( self, '', "Impossible de charger {}".format(filename)) return self.imagePath = filename self.image = QPixmap.fromImage(image) self.label.resize(self.image.width(), self.image.height()) self.label.setPixmap(self.image) # Insert the image in the history self.history.append(self.image.copy()) self.factor = 1.0 self.sketch = True self.scrollArea.setVisible(True) self.fitWindowAction.setEnabled(True) self.zoomInAction.setEnabled(True) self.zoomOutAction.setEnabled(True) if not self.fitWindowAction.isChecked(): self.label.adjustSize() self.initAdjust() if developerMode: print('\tFile is now adjusted to the window => ' + str(time.time() - self.start)) else: pass # Remove a previous processed image if exists pathProcessed = os.listdir('tmp/') if "processedImage.png" in pathProcessed: os.remove('tmp/processedImage.png')
def display_rgb_image(self, rgb_image): convert_to_QtFormat = QImage(rgb_image.data, self.width, self.height, self.bytesPerLine, QImage.Format_RGB888) ready_image = convert_to_QtFormat.scaled(640, 480, Qt.KeepAspectRatio) self.setPixmap(QPixmap.fromImage(ready_image))
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(875, 378) # self.ui = QWidget() # uic.loadUi("mainwindow.ui", self.ui) self.imgPath = "" self.capture = VideoCapture(0) self.captureState = False self.colorState = False #False = color, true = gray self.winSelected = False self.warpState = False #Timer to control the capture. self.timer = QTimer() self.timer.timeout.connect(self.timerLoop) self.timer.start(16) #Values for window selection self.rectHeight = 0 self.rectWidth = 0 self.posX = 0 self.posY = 0 #Signals for window selection #Left image frame. Image prior to transformation self.imageFrameS = QtWidgets.QFrame(MainWindow) self.imageFrameS.setGeometry(QtCore.QRect(20, 20, 320, 240)) self.imageFrameS.setFrameShape(QtWidgets.QFrame.StyledPanel) self.imageFrameS.setFrameShadow(QtWidgets.QFrame.Raised) self.imageFrameS.setObjectName("imageFrameS") # FIXED: Opencv images where created with wrong width height values (switched) so the copy failed # self.colorImage = np.zeros((320,240)) # FIXED: original removed 2 of the 3 chanels with the np.zeros # self.colorImage = np.zeros((320,240)) self.colorImage = np.zeros((240, 320, 3)) self.grayImage = np.zeros((240, 320)) self.imgLeft = QImage(320, 240, QImage.Format_RGB888) self.imgVisorS = ImgViewer(320, 240, self.imgLeft, self.imageFrameS) self.imgVisorS.windowSelected.connect(self.selectWindow) self.label_S = QLabel(self.imgVisorS) self.label_S.setObjectName("label_S") self.label_S.setGeometry(QRect(0, 0, 320, 240)) self.label_S.setAttribute(Qt.WA_TransparentForMouseEvents, True) #TODO: Delete label, set as attribute of imgViewer #Isn't it the same? TODO later, it works *for now* #Right image frame. Image after transformation. self.imageFrameD = QtWidgets.QFrame(MainWindow) self.imageFrameD.setGeometry(QtCore.QRect(390, 20, 320, 240)) self.imageFrameD.setFrameShape(QtWidgets.QFrame.StyledPanel) self.imageFrameD.setFrameShadow(QtWidgets.QFrame.Raised) self.imageFrameD.setObjectName("imageFrameD") # FIXED: original removed 2 of the 3 chanels with the np.zeros #self.colorImageDest = np.zeros((240,320)) self.colorImageDest = np.zeros((240, 320, 3)) self.grayImageDest = np.zeros((240, 320)) self.imgRight = QImage(320, 240, QImage.Format_RGB888) self.imgVisorD = ImgViewer(320, 240, self.imgRight, self.imageFrameD) self.label_D = QLabel(self.imageFrameD) self.label_D.setObjectName("label_D") self.label_D.setGeometry(QRect(0, 0, 320, 240)) # self.visorHistoS = ImgViewer(256, self.ui.histoFrameS.height(), self.ui.histoFrameS) # self.visorHistoD = ImgViewer(256, self.ui.histoFrameS.height(), self.ui.histoFrameD) #Capture button. self.captureButton = QtWidgets.QPushButton(MainWindow) self.captureButton.setGeometry(QtCore.QRect(740, 20, 101, 31)) self.captureButton.setCheckable(True) self.captureButton.setChecked(False) self.captureButton.setObjectName("captureButton") self.captureButton.clicked.connect(self.captureButtonAction) #Gray/Color button. self.colorButton = QtWidgets.QPushButton(MainWindow) self.colorButton.setGeometry(QtCore.QRect(740, 60, 101, 31)) self.colorButton.setCheckable(True) self.colorButton.setChecked(False) self.colorButton.setObjectName("colorButton") self.colorButton.clicked.connect(self.colorButtonAction) #Load from file button. self.loadButton = QtWidgets.QPushButton(MainWindow) self.loadButton.setGeometry(QtCore.QRect(740, 100, 101, 31)) self.loadButton.setObjectName("loadButton") self.loadButton.clicked.connect(self.loadButtonAction) #Save to file button. self.saveButton = QtWidgets.QPushButton(MainWindow) self.saveButton.setGeometry(QtCore.QRect(740, 140, 101, 31)) self.saveButton.setObjectName("saveButton") self.saveButton.clicked.connect(self.saveButtonAction) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow)
def setBackground(self): oImage = QImage('figure2.png') sImage = oImage.scaled(QSize(907, 690)) palette = QPalette() palette.setBrush(QPalette.Background, QBrush(sImage)) self.setPalette(palette)
images = [] for root,dirs,files in os.walk(folderPath): for file in files: if file.lower().endswith('png'): relativePath = os.path.join(root,file) path = (os.path.abspath(relativePath)) images.append(path) images.sort() for image in images: img = cv.imread(image) print(image[-9:-4]) txtPath = os.path.splitext(image)[0] + TXT_EXT if os.path.isfile(txtPath) is False: break qimg = QImage() qimg.load(image) yoloParseReader = YoloReader(txtPath,qimg) shapes = yoloParseReader.getShapes() for shape in shapes: #print(shape[0]) #break if 'car' in shape[0]: #print(shape[1]) cv.line(img,shape[1][0],shape[1][1],(0,0,255),3) cv.line(img,shape[1][1],shape[1][2],(0,0,255),3) cv.line(img,shape[1][2],shape[1][3],(0,0,255),3) cv.line(img,shape[1][3],shape[1][0],(0,0,255),3) cv.imshow("hello",img) key = cv.waitKey(100)&0xff if key == 27:
def timerLoop(self): if (self.captureState == True and self.capture.isOpened() == True): if self.colorState == False: ret, self.colorImage = self.capture.read() #print("Captured shape %s"%str(self.colorImage.shape)) self.colorImage = cv2.resize(self.colorImage, (320, 240)) #print("Resized shape %s"%str(self.colorImage.shape)) self.colorImage = cv2.cvtColor(self.colorImage, cv2.COLOR_BGR2RGB) # FIXED: astype is needed to convert the cv type to the qt expected one self.imgVisorS.qimg = QImage(self.colorImage.astype(np.int8), self.colorImage.shape[1], self.colorImage.shape[0], QImage.Format_RGB888) #self.colorImageDest = self.colorImage # FIXED: astype is needed to convert the cv type to the qt expected one self.imgVisorD.qimg = QImage( self.colorImageDest.astype(np.int8), self.colorImageDest.shape[1], self.colorImageDest.shape[0], QtGui.QImage.Format_RGB888) else: ret, self.grayImage = self.capture.read() self.grayImage = cv2.resize(self.grayImage, (320, 240)) self.grayImage = cv2.cvtColor(self.grayImage, cv2.COLOR_BGR2GRAY) # FIXED: astype is needed to convert the cv type to the qt expected one self.imgVisorS.qimg = QImage(self.grayImage.astype(np.int8), self.grayImage.shape[1], self.grayImage.shape[0], self.grayImage.strides[0], QImage.Format_Grayscale8) # FIXED: astype is needed to convert the cv type to the qt expected one self.imgVisorD.qimg = QImage( self.grayImageDest.astype(np.int8), self.grayImageDest.shape[1], self.grayImageDest.shape[0], QImage.Format_Grayscale8) #To update the warping in real time. TODO translation if self.warpState == True: rotation_matrix = cv2.getRotationMatrix2D( (320 / 2, 240 / 2), -self.angleDial.value(), 1 + self.zoomSlider.value() / 3) translation_matrix = np.float32( [[1, 0, self.horizontalSlider.value()], [0, 1, self.verticalSlider.value()]]) if self.colorState == False: rotated_image = cv2.warpAffine(self.colorImage, rotation_matrix, (320, 240)) rotated_image = cv2.warpAffine(rotated_image, translation_matrix, (320, 240)) self.colorImageDest = rotated_image self.imgVisorD.qimg = QImage( self.colorImageDest.astype(np.int8), self.colorImageDest.shape[1], self.colorImageDest.shape[0], QtGui.QImage.Format_RGB888) else: rotated_image = cv2.warpAffine(self.grayImage, rotation_matrix, (320, 240)) rotated_image = cv2.warpAffine(rotated_image, translation_matrix, (320, 240)) self.grayImageDest = rotated_image self.imgVisorD.qimg = QImage( self.grayImageDest.astype(np.int8), self.grayImageDest.shape[1], self.grayImageDest.shape[0], QImage.Format_Grayscale8) if self.winSelected == True: self.imgVisorS.drawSquare(self.posX, self.posY, self.rectWidth, self.rectHeight) self.label_S.setPixmap(QPixmap.fromImage(self.imgVisorS.qimg)) self.label_D.setPixmap(QPixmap.fromImage(self.imgVisorD.qimg)) self.imgVisorS.repaint() self.imgVisorS.update()
def updateMask(control_image_path, rendered_image_path, mask_image_path): control_image = imageFromPath(control_image_path) if not control_image: error('Could not read control image {}'.format(control_image_path)) rendered_image = imageFromPath(rendered_image_path) if not rendered_image: error('Could not read rendered image {}'.format(rendered_image_path)) if not rendered_image.width() == control_image.width( ) or not rendered_image.height() == control_image.height(): print( ('Size mismatch - control image is {}x{}, rendered image is {}x{}'. format(control_image.width(), control_image.height(), rendered_image.width(), rendered_image.height()))) max_width = min(rendered_image.width(), control_image.width()) max_height = min(rendered_image.height(), control_image.height()) # read current mask, if it exist mask_image = imageFromPath(mask_image_path) if mask_image.isNull(): print('Mask image does not exist, creating {}'.format(mask_image_path)) mask_image = QImage(control_image.width(), control_image.height(), QImage.Format_ARGB32) mask_image.fill(QColor(0, 0, 0)) # loop through pixels in rendered image and compare mismatch_count = 0 linebytes = max_width * 4 for y in range(max_height): control_scanline = control_image.constScanLine(y).asstring(linebytes) rendered_scanline = rendered_image.constScanLine(y).asstring(linebytes) mask_scanline = mask_image.scanLine(y).asstring(linebytes) for x in range(max_width): currentTolerance = qRed( struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0]) if currentTolerance == 255: # ignore pixel continue expected_rgb = struct.unpack('I', control_scanline[x * 4:x * 4 + 4])[0] rendered_rgb = struct.unpack('I', rendered_scanline[x * 4:x * 4 + 4])[0] difference = colorDiff(expected_rgb, rendered_rgb) if difference > currentTolerance: # update mask image mask_image.setPixel(x, y, qRgb(difference, difference, difference)) mismatch_count += 1 if mismatch_count: # update mask mask_image.save(mask_image_path, "png") print('Updated {} pixels in {}'.format(mismatch_count, mask_image_path)) else: print('No mismatches in {}'.format(mask_image_path))
class ResultHandler(QDialog): def __init__(self, parent=None): super(ResultHandler, self).__init__() self.setWindowTitle('Dash results') self.control_label = QLabel() self.rendered_label = QLabel() self.diff_label = QLabel() self.mask_label = QLabel() self.new_mask_label = QLabel() self.scrollArea = QScrollArea() self.widget = QWidget() self.test_name_label = QLabel() grid = QGridLayout() grid.addWidget(self.test_name_label, 0, 0) grid.addWidget(QLabel('Control'), 1, 0) grid.addWidget(QLabel('Rendered'), 1, 1) grid.addWidget(QLabel('Difference'), 1, 2) grid.addWidget(self.control_label, 2, 0) grid.addWidget(self.rendered_label, 2, 1) grid.addWidget(self.diff_label, 2, 2) grid.addWidget(QLabel('Current Mask'), 3, 0) grid.addWidget(QLabel('New Mask'), 3, 1) grid.addWidget(self.mask_label, 4, 0) grid.addWidget(self.new_mask_label, 4, 1) self.widget.setLayout(grid) self.scrollArea.setWidget(self.widget) v_layout = QVBoxLayout() v_layout.addWidget(self.scrollArea, 1) next_image_button = QPushButton() next_image_button.setText('Skip') next_image_button.pressed.connect(self.load_next) self.overload_spin = QDoubleSpinBox() self.overload_spin.setMinimum(1) self.overload_spin.setMaximum(255) self.overload_spin.setValue(1) self.overload_spin.valueChanged.connect( lambda: save_mask_button.setEnabled(False)) preview_mask_button = QPushButton() preview_mask_button.setText('Preview New Mask') preview_mask_button.pressed.connect(self.preview_mask) preview_mask_button.pressed.connect( lambda: save_mask_button.setEnabled(True)) save_mask_button = QPushButton() save_mask_button.setText('Save New Mask') save_mask_button.pressed.connect(self.save_mask) button_layout = QHBoxLayout() button_layout.addWidget(next_image_button) button_layout.addWidget(QLabel('Mask diff multiplier:')) button_layout.addWidget(self.overload_spin) button_layout.addWidget(preview_mask_button) button_layout.addWidget(save_mask_button) button_layout.addStretch() v_layout.addLayout(button_layout) self.setLayout(v_layout) def closeEvent(self, event): self.reject() def parse_url(self, url): print('Fetching dash results from: {}'.format(url)) page = urllib.request.urlopen(url) soup = BeautifulSoup(page, "lxml") # build up list of rendered images measurement_img = [ img for img in soup.find_all('img') if img.get('alt') and img.get('alt').startswith('Rendered Image') ] images = {} for img in measurement_img: m = re.search('Rendered Image (.*?)\s', img.get('alt')) test_name = m.group(1) rendered_image = img.get('src') images[test_name] = '{}/{}'.format(dash_url, rendered_image) if images: print('found images:\n{}'.format(images)) else: print('no images found\n') self.images = images self.load_next() def load_next(self): if not self.images: # all done self.accept() exit(0) test_name, rendered_image = self.images.popitem() self.test_name_label.setText(test_name) control_image = self.get_control_image_path(test_name) if not control_image: self.load_next() return self.mask_image_path = control_image[:-4] + '_mask.png' self.load_images(control_image, rendered_image, self.mask_image_path) def load_images(self, control_image_path, rendered_image_path, mask_image_path): self.control_image = imageFromPath(control_image_path) if not self.control_image: error('Could not read control image {}'.format(control_image_path)) self.rendered_image = imageFromPath(rendered_image_path) if not self.rendered_image: error( 'Could not read rendered image {}'.format(rendered_image_path)) if not self.rendered_image.width() == self.control_image.width( ) or not self.rendered_image.height() == self.control_image.height(): print( 'Size mismatch - control image is {}x{}, rendered image is {}x{}' .format(self.control_image.width(), self.control_image.height(), self.rendered_image.width(), self.rendered_image.height())) max_width = min(self.rendered_image.width(), self.control_image.width()) max_height = min(self.rendered_image.height(), self.control_image.height()) # read current mask, if it exist self.mask_image = imageFromPath(mask_image_path) if self.mask_image.isNull(): print('Mask image does not exist, creating {}'.format( mask_image_path)) self.mask_image = QImage(self.control_image.width(), self.control_image.height(), QImage.Format_ARGB32) self.mask_image.fill(QColor(0, 0, 0)) self.diff_image = self.create_diff_image(self.control_image, self.rendered_image, self.mask_image) if not self.diff_image: self.load_next() return self.control_label.setPixmap(QPixmap.fromImage(self.control_image)) self.rendered_label.setPixmap(QPixmap.fromImage(self.rendered_image)) self.mask_label.setPixmap(QPixmap.fromImage(self.mask_image)) self.diff_label.setPixmap(QPixmap.fromImage(self.diff_image)) self.preview_mask() def preview_mask(self): self.new_mask_image = self.create_mask(self.control_image, self.rendered_image, self.mask_image, self.overload_spin.value()) self.new_mask_label.setPixmap(QPixmap.fromImage(self.new_mask_image)) def save_mask(self): self.new_mask_image.save(self.mask_image_path, "png") self.load_next() def create_mask(self, control_image, rendered_image, mask_image, overload=1): max_width = min(rendered_image.width(), control_image.width()) max_height = min(rendered_image.height(), control_image.height()) new_mask_image = QImage(control_image.width(), control_image.height(), QImage.Format_ARGB32) new_mask_image.fill(QColor(0, 0, 0)) # loop through pixels in rendered image and compare mismatch_count = 0 linebytes = max_width * 4 for y in range(max_height): control_scanline = control_image.constScanLine(y).asstring( linebytes) rendered_scanline = rendered_image.constScanLine(y).asstring( linebytes) mask_scanline = mask_image.scanLine(y).asstring(linebytes) for x in range(max_width): currentTolerance = qRed( struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0]) if currentTolerance == 255: # ignore pixel new_mask_image.setPixel( x, y, qRgb(currentTolerance, currentTolerance, currentTolerance)) continue expected_rgb = struct.unpack( 'I', control_scanline[x * 4:x * 4 + 4])[0] rendered_rgb = struct.unpack( 'I', rendered_scanline[x * 4:x * 4 + 4])[0] difference = min( 255, colorDiff(expected_rgb, rendered_rgb) * overload) if difference > currentTolerance: # update mask image new_mask_image.setPixel( x, y, qRgb(difference, difference, difference)) mismatch_count += 1 else: new_mask_image.setPixel( x, y, qRgb(currentTolerance, currentTolerance, currentTolerance)) return new_mask_image def get_control_image_path(self, test_name): if os.path.isfile(test_name): return path # else try and find matching test image script_folder = os.path.dirname(os.path.realpath(sys.argv[0])) control_images_folder = os.path.join( script_folder, '../tests/testdata/control_images') matching_control_images = [ x[0] for x in os.walk(control_images_folder) if test_name in x[0] ] if len(matching_control_images) > 1: QMessageBox.warning( self, 'Result', 'Found multiple matching control images for {}'.format( test_name)) return None elif len(matching_control_images) == 0: QMessageBox.warning( self, 'Result', 'No matching control images found for {}'.format(test_name)) return None found_control_image_path = matching_control_images[0] # check for a single matching expected image images = glob.glob(os.path.join(found_control_image_path, '*.png')) filtered_images = [i for i in images if not i[-9:] == '_mask.png'] if len(filtered_images) > 1: error('Found multiple matching control images for {}'.format( test_name)) elif len(filtered_images) == 0: error('No matching control images found for {}'.format(test_name)) found_image = filtered_images[0] print('Found matching control image: {}'.format(found_image)) return found_image def create_diff_image(self, control_image, rendered_image, mask_image): # loop through pixels in rendered image and compare mismatch_count = 0 max_width = min(rendered_image.width(), control_image.width()) max_height = min(rendered_image.height(), control_image.height()) linebytes = max_width * 4 diff_image = QImage(control_image.width(), control_image.height(), QImage.Format_ARGB32) diff_image.fill(QColor(152, 219, 249)) for y in range(max_height): control_scanline = control_image.constScanLine(y).asstring( linebytes) rendered_scanline = rendered_image.constScanLine(y).asstring( linebytes) mask_scanline = mask_image.scanLine(y).asstring(linebytes) for x in range(max_width): currentTolerance = qRed( struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0]) if currentTolerance == 255: # ignore pixel continue expected_rgb = struct.unpack( 'I', control_scanline[x * 4:x * 4 + 4])[0] rendered_rgb = struct.unpack( 'I', rendered_scanline[x * 4:x * 4 + 4])[0] difference = colorDiff(expected_rgb, rendered_rgb) if difference > currentTolerance: # update mask image diff_image.setPixel(x, y, qRgb(255, 0, 0)) mismatch_count += 1 if mismatch_count: return diff_image else: print('No mismatches') return None
def __init__(self, parent): super().__init__(parent) self._image = QImage()
import sys from PyQt5.QtWidgets import QMainWindow, QApplication, QVBoxLayout, QHBoxLayout, QWidget, QLabel, QTextEdit, QSlider from PyQt5.QtGui import QPixmap, QImage, QIcon from PyQt5.QtCore import QTimer, QThread, Qt import cv2 import numpy as np from QSharpTools import SharpButton face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') detector_params = cv2.SimpleBlobDetector_Params() detector_params.filterByArea = True detector_params.maxArea = 1500 detector = cv2.SimpleBlobDetector_create(detector_params) mainImg = QImage() currentSequence = "" patterns = {} def sigmoid(x): return 1 / (1 + np.exp(-x)) def activation(x): a = 45 b = 18 c = 50 return c * (sigmoid(x - a) + sigmoid(x - a - b))