class ImageProvider(QQuickImageProvider): def __init__(self, imagetype=QQuickImageProvider.Image, parent=None): super(ImageProvider, self).__init__(imagetype) self.image = QImage() self.publishers = { 'network_architecture': NetArchitecture(), } # for p in self.publishers.values(): # p.sourceChanged.connect(self.publisherUpdated) def requestImage(self, image_id, size): """ This method overrides requestImage from QQuickImageProvider, which will be called from qml Images """ # print("requested image - size:") # print(size) publisher = self.publishers[image_id] # TODO not found self.image = publisher.get_image(size) # TODO has image? return self.image, QSize(self.image.width(), self.image.height())
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 createImage(self, transform): original = QImage(self.image) if original.isNull(): return original size = transform.map(QPoint(self.maxWidth, self.maxHeight)) w = size.x() h = size.y() # Optimization: if image is smaller than maximum allowed size, just # return the loaded image. if original.size().height() <= h and original.size().width() <= w and not self.adjustSize and self.scale == 1: return original # Calculate what the size of the final image will be. w = min(w, float(original.size().width()) * self.scale) h = min(h, float(original.size().height()) * self.scale) adjustx = 1.0 adjusty = 1.0 if self.adjustSize: adjustx = min(transform.m11(), transform.m22()) adjusty = max(transform.m22(), adjustx) w *= adjustx h *= adjusty # Create a new image with correct size, and draw original on it. image = QImage(int(w + 2), int(h + 2), QImage.Format_ARGB32_Premultiplied) image.fill(QColor(0, 0, 0, 0).rgba()) painter = QPainter(image) painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) if self.adjustSize: painter.scale(adjustx, adjusty) if self.scale != 1: painter.scale(self.scale, self.scale) painter.drawImage(0, 0, original) if not self.adjustSize: # Blur out edges. blur = 30 if h < original.height(): brush1 = QLinearGradient(0, h - blur, 0, h) brush1.setSpread(QLinearGradient.PadSpread) brush1.setColorAt(0.0, QColor(0, 0, 0, 0)) brush1.setColorAt(1.0, Colors.sceneBg1) painter.fillRect(0, int(h) - blur, original.width(), int(h), brush1) if w < original.width(): brush2 = QLinearGradient(w - blur, 0, w, 0) brush2.setSpread(QLinearGradient.PadSpread) brush2.setColorAt(0.0, QColor(0, 0, 0, 0)) brush2.setColorAt(1.0, Colors.sceneBg1) painter.fillRect(int(w) - blur, 0, int(w), original.height(), brush2) return image
def openImage(self, fileName): loadedImage = QImage() if not loadedImage.load(fileName): return False self.Owidth = loadedImage.width() self.Oheight = loadedImage.height() loadedImage = loadedImage.scaled(loadedImage.width()*0.3, loadedImage.height()*0.3) newSize = loadedImage.size().expandedTo(self.size()) self.resizeImage(loadedImage, newSize) self.image = loadedImage self.modified = False self.update() return True
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) #imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [image.height(), image.width(), 1 if image.isGrayscale() else 3] writer = PascalVocWriter(imgFolderName, imgFileName, imageShape,localImgPath=imagePath) writer.verified = self.verified for shape in shapes: points = shape['points'] label = shape['label'] # Add Chris difficult = int(shape['difficult']) illumination = str(shape['illumination']) distince = str(shape['distince']) yaw = str(shape['yaw']) pitch = str(shape['pitch']) roll = str(shape['roll']) glasses = str(shape['glasses']) # yyk add bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult, illumination, distince, yaw, pitch, roll, glasses) writer.save(targetFile=filename) return
def saveYoloFormat(self, filename, shapes, imagePath, imageData, classList, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) #imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [image.height(), image.width(), 1 if image.isGrayscale() else 3] writer = YOLOWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath) writer.verified = self.verified for shape in shapes: points = shape['points'] label = shape['label'] # Add Chris difficult = int(shape['difficult']) bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult) writer.save(targetFile=filename, classList=classList) return
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
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
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 _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)
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 brushValuePixmap(b): img = QImage(16, 16, QImage.Format_ARGB32_Premultiplied) img.fill(0) painter = QPainter(img) #painter.begin() painter.setCompositionMode(QPainter.CompositionMode_Source) painter.fillRect(0, 0, img.width(), img.height(), b) color = b.color() if (color.alpha() != 255): # indicate alpha by an inset opaqueBrush = b color.setAlpha(255) opaqueBrush.setColor(color) painter.fillRect(img.width() / 4, img.height() / 4, img.width() / 2, img.height() / 2, opaqueBrush) painter.end() return QPixmap.fromImage(img)
def createImageButtons(self,imagePath): groupImg = QImage(imagePath) width = groupImg.width() height = groupImg.height() frameSize = width for i in range(0,height//width): img = groupImg.copy(0,i*frameSize,frameSize,frameSize); self.addImageButton(img)
def resizeImage(self, img : QImage, size : tuple): x = img.width() y = img.height() if x <= size[0] and y <= size[1]: return img origK = img.height() / img.width() if x > size[0]: x = size[0] y = int(origK * x) if y > size[1]: y = size[1] x = (y / origK) return img.scaled(x, y, transformMode=QtCore.Qt.SmoothTransformation)
def load_texture(fname): img = QImage(fname) ptr = c_void_p(int(img.constBits())) tex_id = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, tex_id) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA8, img.width(), img.height(), 0, gl.GL_BGRA, gl.GL_UNSIGNED_BYTE, ptr) gl.glGenerateMipmap(gl.GL_TEXTURE_2D) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR_MIPMAP_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) return tex_id
def drop_shadow(image: QImage) -> 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(0) alpha = alpha.reshape((image.width(), image.height())) alpha = gaussian_filter(alpha, sigma=10) alpha = alpha.reshape(shape) arr = numpy.dstack((color, color, color, alpha)) return QImage(arr, image.width(), image.height(), QImage.Format_ARGB32)
def _rounded_qimage(qimg, radius): r_image = QImage(qimg.width(), qimg.height(), QImage.Format_ARGB32) r_image.fill(Qt.transparent) p = QPainter() pen = QPen(Qt.darkGray) pen.setJoinStyle(Qt.RoundJoin) p.begin(r_image) p.setRenderHint(p.Antialiasing) p.setPen(Qt.NoPen) p.setBrush(QBrush(qimg)) p.drawRoundedRect(0, 0, r_image.width(), r_image.height(), radius, radius) p.end() return r_image
def getImageBoundaries(image: QImage): # Look at the resulting image to get a good crop. # Get the pixels as byte array pixel_array = image.bits().asarray(image.byteCount()) width, height = image.width(), image.height() # Convert to numpy array, assume it's 32 bit (it should always be) pixels = numpy.frombuffer(pixel_array, dtype=numpy.uint8).reshape([height, width, 4]) # Find indices of non zero pixels nonzero_pixels = numpy.nonzero(pixels) min_y, min_x, min_a_ = numpy.amin(nonzero_pixels, axis=1) max_y, max_x, max_a_ = numpy.amax(nonzero_pixels, axis=1) return min_x, max_x, min_y, max_y
def initDefaultFrames(self): self.bmpFrames = [] defaultImage = QImage("..\\resource\\default.bmp") imageWidth = defaultImage.width() imageHeight = defaultImage.height() #判断各幀图片是否是横向排列 isHorizontal = min(imageWidth,imageHeight) == imageHeight #计算幀数 self.frameCount = imageWidth//frameWidth if isHorizontal else imageHeight//frameHeight for i in range(0,self.frameCount): pixmap = QPixmap(defaultImage.copy(i*frameWidth if isHorizontal else 0, 0 if isHorizontal else i*frameHeight,frameWidth,frameHeight)) eliminateBackgroundColor(pixmap) self.bmpFrames.append(pixmap)
def toImage(self): t = time.time() tWAIT = time.time() self._arrayreq.wait() tWAIT = 1000.0 * (time.time() - tWAIT) tAR = time.time() a = self._arrayreq.getResult() tAR = 1000.0 * (time.time() - tAR) has_no_mask = not np.ma.is_masked(a) tImg = None if has_no_mask and _has_vigra and hasattr(vigra.colors, "gray2qimage_ARGB32Premultiplied"): if not a.flags.contiguous: a = a.copy() tImg = time.time() img = QImage(a.shape[1], a.shape[0], QImage.Format_ARGB32_Premultiplied) tintColor = np.asarray( [self._tintColor.redF(), self._tintColor.greenF(), self._tintColor.blueF()], dtype=np.float32 ) normalize = np.asarray(self._normalize, dtype=np.float32) if normalize[0] > normalize[1]: normalize = np.array((0.0, 255.0)).astype(np.float32) vigra.colors.alphamodulated2qimage_ARGB32Premultiplied(a, byte_view(img), tintColor, normalize) tImg = 1000.0 * (time.time() - tImg) else: if has_no_mask: self.logger.warning("using unoptimized conversion functions") tImg = time.time() d = a[..., None].repeat(4, axis=-1) d[:, :, 0] = d[:, :, 0] * self._tintColor.redF() d[:, :, 1] = d[:, :, 1] * self._tintColor.greenF() d[:, :, 2] = d[:, :, 2] * self._tintColor.blueF() normalize = self._normalize img = array2qimage(d, normalize) img = img.convertToFormat(QImage.Format_ARGB32_Premultiplied) tImg = 1000.0 * (time.time() - tImg) if self.logger.isEnabledFor(logging.DEBUG): tTOT = 1000.0 * (time.time() - t) self.logger.debug( "toImage (%dx%d, normalize=%r) took %f msec. (array req: %f, wait: %f, img: %f)" % (img.width(), img.height(), normalize, tTOT, tAR, tWAIT, tImg) ) return img
def drawImg(self, path): img = QImage(path) for x in range(img.width()): for y in range(img.height()): red, green, blue, a = QColor(img.pixel(x, y)).getRgb() if red > green and red > blue: color = midifeedback.RED elif green > red and green > blue: color = midifeedback.GREEN elif red == green and green > blue: color = midifeedback.AMBER else: color = midifeedback.BLACK print( "r:{},g:{},b:{},color:{}".format(red, green, blue, color)) self.onenote(x, y, color)
def get_snapshot(self, bw=None, return_as_array=None): qimage = QImage(self.image) if return_as_array: qimage = qimage.convertToFormat(4) ptr = qimage.bits() ptr.setsize(qimage.byteCount()) image_array = np.array(ptr).reshape(qimage.height(), qimage.width(), 4) if bw: return np.dot(image_array[..., :3], [0.299, 0.587, 0.144]) else: return image_array else: if bw: return qimage.convertToFormat(QImage.Format_Mono) else: return qimage
def create_thumbnail(self, src, dest, size): from PyQt5.QtCore import Qt from PyQt5.QtGui import QImage img = QImage(str(src)) if img.isNull(): return res = { KEY_MTIME: _any2mtime(src), KEY_WIDTH: img.width(), KEY_HEIGHT: img.height(), } img = img.scaled(size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation) img.save(dest) return res
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()
def load_lcd_font(): files = sorted(glob('mcp_font/*.png')) img = QImage(files[0]) imgsize = (img.width(), img.height()) # Set-up the texture array tex_id = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D_ARRAY, tex_id) gl.glTexImage3D(gl.GL_TEXTURE_2D_ARRAY, 0, gl.GL_RGBA8, imgsize[0], imgsize[1], len(files), 0, gl.GL_BGRA, gl.GL_UNSIGNED_BYTE, None) gl.glTexParameteri(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameterf(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_BORDER) gl.glTexParameterf(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_BORDER) for i, fname in enumerate(files): img = QImage(fname).convertToFormat(QImage.Format_ARGB32) ptr = c_void_p(int(img.constBits())) gl.glTexSubImage3D(gl.GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, imgsize[0], imgsize[1], 1, gl.GL_BGRA, gl.GL_UNSIGNED_BYTE, ptr) return tex_id
def create_font_array(self, path): # Load the first image to get font size img = QImage(path + '32.png') imgsize = (img.width(), img.height()) self.char_ar = float(imgsize[1]) / imgsize[0] # Set-up the texture array self.tex_id = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D_ARRAY, self.tex_id) gl.glTexImage3D(gl.GL_TEXTURE_2D_ARRAY, 0, gl.GL_RGBA8, imgsize[0], imgsize[1], 127 - 32, 0, gl.GL_BGRA, gl.GL_UNSIGNED_BYTE, None) gl.glTexParameteri(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameterf(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_BORDER) gl.glTexParameterf(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_BORDER) # We're using the ASCII range 32-126; space, uppercase, lower case, numbers, brackets, punctuation marks for i in range(32, 127): img = QImage(path + '%d.png' % i).convertToFormat(QImage.Format_ARGB32) ptr = c_void_p(int(img.constBits())) gl.glTexSubImage3D(gl.GL_TEXTURE_2D_ARRAY, 0, 0, 0, i - 32, imgsize[0], imgsize[1], 1, gl.GL_BGRA, gl.GL_UNSIGNED_BYTE, ptr)
def setImage(self,fileName=None): """ Sets the image overlay Parameters: ---------- fileName:str """ if not fileName: fileName, _ = QFileDialog.getOpenFileName(self) image=QImage(fileName) (width,height)=(image.width(),image.height()) image=image.scaledToHeight(60) self.monitor.setPixmap(QPixmap.fromImage(image)) self.monitor.adjustSize() if fileName: print("Setting overlay image to %s"%fileName) self.sourceElement.set_property("location",fileName) self.comboSize.addItem("%sx%s"%(width,height)) self.comboSize.setCurrentIndex(self.comboSize.count()-1) self.imageSet.emit(fileName)
def save_yolo_format(self, filename, shapes, image_path, image_data, class_list, line_color=None, fill_color=None, database_src=None): img_folder_path = os.path.dirname(image_path) img_folder_name = os.path.split(img_folder_path)[-1] img_file_name = os.path.basename(image_path) # imgFileNameWithoutExt = os.path.splitext(img_file_name)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format if isinstance(image_data, QImage): image = image_data else: image = QImage() image.load(image_path) image_shape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] writer = YOLOWriter(img_folder_name, img_file_name, image_shape, local_img_path=image_path) writer.verified = self.verified for shape in shapes: points = shape['points'] label = shape['label'] # Add Chris difficult = int(shape['difficult']) bnd_box = LabelFile.convert_points_to_bnd_box(points) writer.add_bnd_box(bnd_box[0], bnd_box[1], bnd_box[2], bnd_box[3], label, difficult) writer.save(target_file=filename, class_list=class_list) return
def saveYoloOBBFormat(self, filename, shapes, imagePath, imageData, classList, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) #imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] writer = YOLOOBBWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath) writer.verified = self.verified for shape in shapes: centre_x_y = shape['centre_x_y'] height = shape['height'] width = shape['width'] angle = shape['angle'] label = shape['label'] # Add Chris difficult = int(shape['difficult']) writer.addBndBox(centre_x_y[0], centre_x_y[1], height, width, angle, label, difficult) writer.save(targetFile=filename, classList=classList) return
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) #imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format if isinstance(imageData, QImage): image = imageData else: image = QImage() image.load(imagePath) imageShape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] writer = PascalVocWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath) writer.verified = self.verified writer.background = self.background for shape in shapes: points = shape['points'] label = shape['label'] # Add Chris difficult = int(shape['difficult']) bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult) writer.save(targetFile=filename) return
class HudEndOfStageTotalPlayerPointsContainer(QGraphicsItem): def __init__(self, config, totalPlayerPoints): super().__init__() self.config = config self.totalPlayerPoints = totalPlayerPoints self.texture = QImage(self.config.endOfStageTotalPlayerPointsContainer) self.m_boundingRect = QRectF(0, 0, self.texture.width(), self.texture.height()) self.digits = [] for i in range(7): self.digits.append(i) self.extractDigitsFromPlayerPoints() self.numbers = [] for i in range(len(self.digits)): number = HudNumber(self, self.config.numberColors["white"], self.config.numberSize["big"], self.digits[i], self.config) number.setPos(self.x() + i * number.width, self.y()) self.numbers.append(number) def boundingRect(self): return self.m_boundingRect def paint(self, QPainter, QStyleOptionGraphicsItem, widget=None): QPainter.drawImage(0, 0, self.texture) def extractDigitsFromPlayerPoints(self): number_string = str(self.totalPlayerPoints).zfill(len(self.digits)) for idx, string_digit in enumerate(number_string): self.digits[idx] = int(string_digit) def updateTotalPlayerPoints(self, playerPoints=None): if playerPoints is not None: self.totalPlayerPoints = playerPoints self.extractDigitsFromPlayerPoints() for i in range(len(self.digits)): self.numbers[i].updateNumber(self.digits[i]) def reset(self): self.totalPlayerPoints = 0 self.updateTotalPlayerPoints()
def convert(image_path, annotation_path, save_path): for file in os.listdir(annotation_path): if file.endswith(".txt") and file != "classes.txt": #print("Convert", file) annotation_no_txt = os.path.splitext(file)[0] imagePath = image_path + "/" + annotation_no_txt + ".jpg" image = QImage() image.load(imagePath) imageShape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] imgFolderName = os.path.basename(annotation_path) imgFileName = os.path.basename(imagePath) writer = PascalVocWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath) # Read YOLO file txtPath = annotation_path + "/" + file tYoloParseReader = YoloReader(txtPath, image) shapes = tYoloParseReader.getShapes() num_of_box = len(shapes) for i in range(num_of_box): label = shapes[i][0] xmin = shapes[i][1][0][0] ymin = shapes[i][1][0][1] x_max = shapes[i][1][2][0] y_max = shapes[i][1][2][1] writer.addBndBox(xmin, ymin, x_max, y_max, label, 0) writer.save(targetFile=save_path + "/" + annotation_no_txt + ".xml")
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) image = QImage() image.load(imagePath) imageShape = [image.height(), image.width(), 1 if image.isGrayscale() else 3] writer = PascalVocWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath) writer.verified = self.verified for shape in shapes: points = shape['points'] label = shape['label'] # difficult = int(shape['difficult']) contour_points = shape['contour_points'] confidence = shape['confidence'] contourEdited = shape['contourEdited'] bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, contour_points, confidence, contourEdited) writer.save(targetFile=filename) return
def preRead(self, file_name, *args, **kwargs): img = QImage(file_name) if img.isNull(): Logger.log("e", "Image is corrupt.") return MeshReader.PreReadResult.failed width = img.width() depth = img.height() largest = max(width, depth) width = width / largest * self._ui.default_width depth = depth / largest * self._ui.default_depth self._ui.setWidthAndDepth(width, depth) self._ui.showConfigUI() self._ui.waitForUIToClose() if self._ui.getCancelled(): return MeshReader.PreReadResult.cancelled return MeshReader.PreReadResult.accepted
def saveArbitraryXMLformat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) #imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [image.height(), image.width(), 1 if image.isGrayscale() else 3] writer = ArbitraryXMLWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath) writer.verified = self.verified for shape in shapes: writer.addEllipse(shape) writer.save(targetFile=filename) return
def gif(self): if self.movie: # Movie is already created self.movie.start() return print("Creating movie for", str(self.iv_image.path)) self.movie = QMovie(str(self.iv_image.path)) image = QImage(str(self.iv_image.path)) if image.height() > imageviewer.settings.IMAGE_HEIGHT or image.width() > imageviewer.settings.IMAGE_WIDTH: # scale the movie if it doesn't fit in the frame # the frame is big enough we don't need the gif at full size to see what is going on image2 = image.scaled(imageviewer.settings.IMAGE_WIDTH, imageviewer.settings.IMAGE_HEIGHT, Qt.KeepAspectRatio) size = QSize() size.setHeight(image2.height()) size.setWidth(image2.width()) self.movie.setScaledSize(size) print("Scaled movie size") self.setMovie(self.movie) self.movie.start()
class Base(QGraphicsItem): def __init__(self, aliveImageUrl, deadImageUrl): super().__init__() self.isAlive = True self.aliveImage = QImage(aliveImageUrl) self.deadImage = QImage(deadImageUrl) self.m_boundingRect = QRectF(0, 0, self.aliveImage.width(), self.aliveImage.height()) def boundingRect(self): return self.m_boundingRect def paint(self, QPainter, QStyleOptionGraphicsItem, widget=None): if self.isAlive: QPainter.drawImage(0, 0, self.aliveImage) else: QPainter.drawImage(0, 0, self.deadImage) def destroyBase(self): self.isAlive = False self.update()
def preRead(self, file_name): img = QImage(file_name) if img.isNull(): Logger.log("e", "Image is corrupt.") return MeshReader.PreReadResult.failed width = img.width() depth = img.height() largest = max(width, depth) width = width / largest * self._ui.default_width depth = depth / largest * self._ui.default_depth self._ui.setWidthAndDepth(width, depth) self._ui.showConfigUI() self._ui.waitForUIToClose() if self._ui.getCancelled(): return MeshReader.PreReadResult.cancelled return MeshReader.PreReadResult.accepted
def get_image_color(imagePath): path, filename = os.path.split(imagePath) image = QImage(imagePath) for i in range(0, image.height()): for j in range(0, image.width()): if image.valid(i, j): color = QColor(image.pixel(i, j)) red = color.red() green = color.green() blue = color.blue() c = 255 - red m = 255 - green y = 255 - blue K = min(min(c, m), y) C = 0 M = 0 Y = 0 if K > 0: C = c + K M = m + K Y = y + K else: C = c M = m Y = y CMYKcolor = QColor() CMYKcolor.setCmyk(C, M, Y, 0) image.setPixel(i, j, CMYKcolor.value()) # image.save(path + '/' + filename) return image else: print(' invalid data ') break
class MapDBV(object): def __init__(self, map_data): """ map data: [img, cover, terrain, x, y] """ self.img = QImage(map_data[0]) self.cover_img = QImage(map_data[1]) self.terrain_img = QImage(map_data[2]) self.width = self.img.width() self.height = self.img.height() self.x = 0 self.y = 0 def show(self, num, painter): """ 渲染地图 """ if num == 1: show_img = self.img elif num == 2: show_img = self.cover_img else: raise ValueError( "arg 'num' in 'show()' can only be int '1' or '2'") painter.drawImage(0, 0, show_img, self.x, self.y, conf.screen_width, conf.screen_height) def setCoordinate(self, new_x, new_y): """ 改变显示坐标, 用于角色移动时 """ if (new_x < 0 or new_x > self.width - conf.screen_width or new_y < 0 or new_y > self.height - conf.screen_height): raise ValueError( "the coordinate in 'MapDBV.setCoordinate()' out of range") else: self.x = new_x self.y = new_y
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.sid = QImage("smallsid.jpg") self.w = self.sid.width() self.h = self.sid.height() self.setGeometry(200, 200, 320, 150) self.setWindowTitle('Sid') self.show() def paintEvent(self, event): painter = QPainter() painter.begin(self) self.drawImages(painter) painter.end() def grayScale(self, image): for i in range(self.w): for j in range(self.h): c = image.pixel(i, j) gray = qGray(c) alpha = qAlpha(c) image.setPixel(i, j, qRgba(gray, gray, gray, alpha)) return image def drawImages(self, painter): painter.drawImage(5, 15, self.sid) painter.drawImage(self.w + 10, 15, self.grayScale(self.sid.copy()))
def __init__(self, game): super().__init__() self.board = None self.flipped = False self.from_square = -1 self.game = game self.mousePressListeners = [] self.moveListeners = [] self.text = None if show_ascii: self.board_map = QPixmap('test.jpg') else: self.board_map = QPixmap('chess_board.png') temp_map = QImage('chess_pieces.png') pcx = temp_map.width() / 6 pcy = temp_map.height() / 2 self.piece_map = [] for y in range(2): for x in range(6): self.piece_map.append(temp_map.copy(int(x * pcx), int(y * pcy), int(pcx), int(pcy)))
def processFrame(self, frame, levels): histogram = [0.0] * levels if levels and frame.map(QAbstractVideoBuffer.ReadOnly): pixelFormat = frame.pixelFormat() if (pixelFormat == QVideoFrame.Format_YUV420P or pixelFormat == QVideoFrame.Format_NV12): # Process YUV data. bits = frame.bits() for idx in range(frame.height() * frame.width()): histogram[(bits[idx] * levels) >> 8] += 1.0 else: imageFormat = QVideoFrame.imageFormatFromPixelFormat( pixelFormat) if imageFormat != QImage.Format_Invalid: # Process RGB data. image = QImage(frame.bits(), frame.width(), frame.height(), imageFormat) for y in range(image.height()): for x in range(image.width()): pixel = image.pixel(x, y) histogram[(qGray(pixel) * levels) >> 8] += 1.0 # Find the maximum value. maxValue = 0.0 for value in histogram: if value > maxValue: maxValue = value # Normalise the values between 0 and 1. if maxValue > 0.0: for i in range(len(histogram)): histogram[i] /= maxValue frame.unmap() self.histogramReady.emit(histogram)
def __init__(self, xy, parent=None, extra=None): super().__init__(xy, parent, extra) if len(self.extra) == 4: self.d, self.exe, self.ico, self.name = self.extra elif len(self.extra) == 3: self.d, self.exe, self.ico = self.extra self.name = self.exe.split()[0] self.setwh((self.d, self.d)) icon = None if self.ico.split('.')[-1] == 'svg' or self.ico.split('.')[-1] == 'svgz': icon = QImage(int(self.d * UNIT / 2), int(self.d * UNIT / 2), QImage.Format_ARGB32) icon.fill(QColor(120, 120, 120, 0)) renderer = QSvgRenderer(self.ico) painter = QPainter(icon) renderer.render(painter) del painter else: icon = QImage(self.ico) iconm = icon.scaled(2, 2) b1 = (QColor(iconm.pixel(0, 0)).getRgb(), QColor(iconm.pixel(0, 1)).getRgb(), QColor(iconm.pixel(1, 0)).getRgb(), QColor(iconm.pixel(1, 1)).getRgb(),) b = (0, 0, 0) for c in b1: b = (b[0] + c[0] // 4, b[1] + c[1] // 4, b[2] + c[2] // 4) self.setcolor(b) scale = min(icon.height(), icon.width(), self.d * UNIT / 2) self.setPixmap(QPixmap(icon).scaledToHeight(scale, Qt.SmoothTransformation)) if self.d > 1: font = QFont('sans') # font.setStretch(QFont.SemiExpanded) font.setPixelSize(UNIT / 4) nametext = QLabel(parent=self) nametext.setFont(font) nametext.move(UNIT / 10, self.height() - UNIT / 10 - nametext.height() / 2) nametext.setAlignment(Qt.AlignBottom | Qt.AlignCenter) nametext.setIndent(self.d * UNIT / 20) nametext.setText('<font color=white>%s</font>' % self.name)
def testQImage(): img = QImage('G:\BrainSAR_Beta\SAR图片\show.jpg').rgbSwapped() print(img.width()) # 打印图片大小 print(img.height()) # 打印图片大小 print(img.pixel(2, 2)) for i in range(1000, 2000): # 遍历所有长度的点 for j in range(1000, 2000): # 遍历所有宽度的点 c = img.pixel(i, j) colors = QColor(c).getRgb() print("(%s,%s) = %s" % (i, j, colors)) # QColor.HexArgb # print(colors.HexArgb) img.setPixel(i, j, 4293539385) # 则这些像素点的颜色改成大红色 # img = img.convert("RGB") # for i in range(0, 1000): # 遍历所有长度的点 # for j in range(0, 1000): # 遍历所有宽度的点 # data = (img.getpixel((i, j))) # 打印该图片的所有点 # print("打印每个像素点的颜色RGBA的值(r,g,b,alpha):", data) # 打印每个像素点的颜色RGBA的值(r,g,b,alpha) # # if (data[0] > 100 or data[1] > 100 or data[2] > 100): # RGBA的r值大于170,并且g值大于170,并且b值大于170 # img.putpixel((i, j), (234, 53, 57, 10)) # 则这些像素点的颜色改成大红色 # img = img.convert("RGB") # 把图片强制转成RGB img.save("QImage.jpg")
def serveImage(self): self.send_response(200) self.send_header("Content-type", "image/jpeg") self.end_headers() cfg = self.server.appconfig # create an image for the final output img = QImage(cfg.saveSize, QImage.Format_RGB888) qp = QPainter(img) # black background and then the images dst = QRect(0,0,img.width(), img.height()) brush = QBrush(Qt.SolidPattern) brush.setColor(Qt.black) qp.setBrush(brush) qp.drawRect(dst) cfg.paintImage(qp, dst) qp.end() buffer = QBuffer() buffer.open(QBuffer.ReadWrite) img.save(buffer, "JPG") self.wfile.write(buffer.data())
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setPen(Qt.blue) #绘制弧 rect = QRect(0, 10, 100, 100) # alen: 1个alen等于1/16度 45 * 16 painter.drawArc(rect, 0, 90 * 16) painter.setPen(Qt.red) painter.drawArc(120, 10, 100, 100, 0, 360 * 16) # 绘制带弦的圆 painter.drawChord(10, 120, 100, 100, 12, 130 * 16) # 绘制扇形 painter.drawPie(10, 240, 100, 100, 12, 130 * 16) # 绘制椭圆 painter.drawEllipse(120, 120, 150, 100) # 绘制5边形 point1 = QPoint(140, 380) point2 = QPoint(270, 420) point3 = QPoint(290, 512) point4 = QPoint(290, 588) point5 = QPoint(200, 533) polygon = QPolygon([point1, point2, point3, point4, point5]) painter.drawPolygon(polygon) # 绘制图像 image = QImage('src\images\QQ截图20200219191139.jpg') rect = QRect(10, 400, image.width() / 3, image.height() / 3) painter.drawImage(rect, image) painter.end()
def b_layer_create(self): temp_dir = tempfile.gettempdir() + "/rcpg10.svg" body = self.rcpg_object.get_svg_string() with open(temp_dir, 'w', encoding='utf-8') as f: f.write(body) app = Krita.instance() doc = app.activeDocument() if doc != None: root = doc.rootNode() layer = doc.createNode("Panels", "paintLayer") img = QImage(temp_dir) img = img.scaled(doc.width(), doc.height(), aspectRatioMode=Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) if not img.isNull(): img.convertToFormat(QImage.Format_RGBA8888) ptr = img.constBits() ptr.setsize(img.byteCount()) layer.setPixelData(bytes(ptr.asarray()), 0, 0, img.width(), img.height()) root.addChildNode(layer, None) doc.refreshProjection()
def make_icon(template, color): """ Create an icon for the specified user color. It will be used to generate on the fly an icon representing the user. """ # Get a light and dark version of the user color r, g, b = StatusWidget.ida_to_python(color) h, l, s = colorsys.rgb_to_hls(r, g, b) r, g, b = colorsys.hls_to_rgb(h, 0.5, 1.0) light = StatusWidget.python_to_qt(r, g, b) r, g, b = colorsys.hls_to_rgb(h, 0.25, 1.0) dark = StatusWidget.python_to_qt(r, g, b) # Replace the icon pixel with our two colors image = QImage(template) for x in range(image.width()): for y in range(image.height()): c = image.pixel(x, y) if (c & 0xffffff) == 0xffffff: image.setPixel(x, y, light) if (c & 0xffffff) == 0x000000: image.setPixel(x, y, dark) return QPixmap(image)
def apply_groups(self, pixmap: QPixmap, *groups: ManipulationGroup) -> QPixmap: """Manipulate pixmap according all manipulations in groups. Args: pixmap: The QPixmap to manipulate. groups: Manipulation groups containing all manipulations to apply in series. Returns: The manipulated pixmap. """ _logger.debug("Manipulate: applying %d groups", len(groups)) # Convert original pixmap to python bytes image = pixmap.toImage() bits = image.constBits() bits.setsize(image.byteCount()) data = bits.asstring() # Apply changes on the byte-level for group in groups: data = self._apply_group(group, data) # Convert updated bytes back to pixmap image = QImage( data, image.width(), image.height(), image.bytesPerLine(), image.format() ) return QPixmap(image)
def open(self, fn=None): if not fn: fn = dialogs.getBitmapFileName(self.mw, unicode(self.config.currentPath)) if fn: self.mw.view.clean() image_fn = unicode(fn) self.config.currentPath = unicode(os.path.dirname(image_fn)) img = QImage(image_fn) img_w = float(img.width()) img_h = float(img.height()) if img_w: self.document = DOM([img_w, img_h]) self.document.image_fn = image_fn img = desaturate(img) self.document.image = grayscale(img) event.emit(event.DOC_OPENED) event.emit(event.DOC_EXPECTS) else: QMessageBox.warning( self.mw, self.tr("Open file"), self.tr("This file is corrupt or not supported?"))
def __init__(self, parent, img: QImage = None): super(ScreenCaptureFrame, self).__init__() # 保存父窗口 self.parentWin = parent # 设置窗口无标题栏 self.setWindowFlags(Qt.FramelessWindowHint) # 设置窗口透明 self.setAttribute(Qt.WA_TranslucentBackground, True) # 设置模态窗口 # self.setWindowModality(Qt.ApplicationModal) if img != None: self.backImg = img self.setFixedSize(img.width(), img.height()) # 设置控件背影图片 # palette = QPalette() # palette.setBrush(QPalette.Background, QBrush(img)) # self.setPalette(palette) self.show() else: self.setFixedSize(500, 500) self.show()
def processFrame(self, frame, levels): print("In processor processFrame()") histogram = [0.0] * levels if levels and frame.map(QAbstractVideoBuffer.ReadOnly): pixelFormat = frame.pixelFormat() if pixelFormat == QVideoFrame.Format_YUV420P or pixelFormat == QVideoFrame.Format_NV12: # Process YUV data. bits = frame.bits() for idx in range(frame.height() * frame.width()): histogram[(bits[idx] * levels) >> 8] += 1.0 else: imageFormat = QVideoFrame.imageFormatFromPixelFormat(pixelFormat) if imageFormat != QImage.Format_Invalid: # Process RGB data. image = QImage(frame.bits(), frame.width(), frame.height(), imageFormat) for y in range(image.height()): for x in range(image.width()): pixel = image.pixel(x, y) histogram[(qGray(pixel) * levels) >> 8] += 1.0 # Find the maximum value. maxValue = 0.0 for value in histogram: if value > maxValue: maxValue = value # Normalise the values between 0 and 1. if maxValue > 0.0: for i in range(len(histogram)): histogram[i] /= maxValue frame.unmap() self.histogramReady.emit(histogram)
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) #print(imgFileName) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [image.height(), image.width(), 1 if image.isGrayscale() else 3] writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt, imageShape, localImgPath=imagePath) writer.verified = self.verified for shape in shapes: points = shape['points'] label = shape['label'] # Add Chris difficult = int(shape['difficult']) direction = shape['direction'] isRotated = shape['isRotated'] # if shape is normal box, save as bounding box # print('direction is %lf' % direction) if not isRotated: bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult) else: #if shape is rotated box, save as rotated bounding box robndbox = LabelFile.convertPoints2RotatedBndBox(shape) writer.addRotatedBndBox(robndbox[0],robndbox[1], robndbox[2],robndbox[3],robndbox[4],label,difficult) writer.save(targetFile=filename) return
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] writer = PascalVocWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath) writer.verified = self.verified for shape in shapes: points = shape['points'] label = shape['label'] # Add Chris difficult = int(shape['difficult']) # # Add Jerry shapeType = shape["shapeType"] writer.addShape(shapeType, label, points, difficult) writer.save(targetFile=filename) return
def saveYoloFormat(self, annPath, shapes, imagePath, imageData): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) # imageShape = [image.height(),, # 1 if image.isGrayscale() else 3] isRotated_check = None with open(str(annPath), 'w') as myfile: for shape in shapes: points = shape['points'] label = shape['label'] # Add Chris difficult = int(shape['difficult']) direction = shape['direction'] isRotated = shape['isRotated'] if isRotated_check is None: isRotated_check = isRotated assert (isRotated_check == isRotated) pmins, pmaxs = LabelFile.convertPoints2BndBox2(points) print(pmins, pmaxs) # if shape is normal box, save as bounding box # print('direction is %lf' % direction) bndbox = yolo_format(self.labels[str(label)], pmins, pmaxs, image.width(), image.height()) if not isRotated: save_bb(myfile, bndbox) else: # if shape is rotated box, save as rotated bounding box save_bb(myfile, bndbox + " " + str(direction)) return
def classFrequenciesOnDataset(self, labels_dir, target_classes, labels_colors): """ Returns the frequencies of the target classes on the given dataset. """ num_classes = len(target_classes) image_label_names = [ x for x in glob.glob(os.path.join(labels_dir, '*.png')) ] total_pixels = 0 counters = np.zeros(num_classes, dtype='float') for label_name in image_label_names: image_label = QImage(label_name) # image_label = image_label.convertToFormat(QImage.Format_RGB32) label_w = image_label.width() label_h = image_label.height() total_pixels += label_w * label_h imglbl = utils.qimageToNumpyArray(image_label) # class 0 --> background labelsint = np.zeros((label_h, label_w), dtype='int64') for i, cl in enumerate(target_classes): class_colors = labels_colors[cl] idx = np.where((imglbl[:, :, 0] == class_colors[0]) & (imglbl[:, :, 1] == class_colors[1]) & (imglbl[:, :, 2] == class_colors[2])) labelsint[idx] = i + 1 for i in range(len(target_classes)): counters[i] += float(np.count_nonzero(labelsint == i + 1)) freq = counters / float(total_pixels)
def get_scaled_pixmap(path): if type(path) != str: image = path.convert("RGB") data = image.tobytes("raw", "RGB") image = QImage(data, image.size[0], image.size[1], QImage.Format_RGB888) else: image = QImage(path) if not image.width(): # 如果QImage打不开用PIL打开强转 image = Image.open(path) image = image.convert("RGB") data = image.tobytes("raw", "RGB") image = QImage(data, image.size[0], image.size[1], QImage.Format_RGB888) width = image.width() height = image.height() # 窄的图片取上方,宽的图片取中间,保持和神经网络一样的剪切方式 if width < height: rect = QRect(0, 0, width, width) else: rect = QRect(int(width / 2 - height / 2), 0, height, height) image = image.copy(rect) return QPixmap(image.scaled(256, 256))
def __init__(self, fileName, image: QtGui.QImage, bg, context, bg_image=None): self.fileName = fileName self.image = image if bg_image is None: self.bg_image = QtGui.QImage( image.width(), image.height(), QtGui.QImage.Format_ARGB32_Premultiplied) else: self.bg_image = bg_image self.ori_bg_img = self.bg_image self.bgColor = bg self.context = context self.zoom = 1 self.selection = None self.history = [QtGui.QImage(self.image)] self.posHistory = 0 self.modified = False self.random_walker = RandomWalker(palette=self.context.defaultPalette)
def saveYoloFormat(self, filename, shapes, imagePath, imageData, classList, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) #imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [image.height(), image.width(), 1 if image.isGrayscale() else 3] writer = YoloWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath) writer.verified = self.verified for shape in shapes: points = shape['points'] label = shape['label'] difficult = int(shape['difficult']) bndbox = self.convertPoints2BndBox(points, label, difficult) writer.boxes.append(bndbox) writer.save(targetFile=filename, classList=classList) return