def __init__(self, file_path, make_opengl_textures=True): image_reader = QImageReader(file_path) self.is_animated = image_reader.supportsAnimation() if self.is_animated: self.num_frames = image_reader.imageCount() # -1 means loop infinitely, 0 means no loop, > 0 is finite # of loops self.loop_count = image_reader.loopCount() self.loops_remaining = 0 self.frames = [] self.delays = [] while image_reader.currentImageNumber() < image_reader.imageCount() - 1: self.frames.append(image_reader.read()) self.delays.append(image_reader.nextImageDelay()) if make_opengl_textures: self.open_gl_textures = [QOpenGLTexture(this_frame.mirrored()) for this_frame in self.frames] self.made_opengl_textures = True self.frames_and_delays = zip(self.frames, self.delays) self.current_frame = 0 self.animating = False else: self.image = image_reader.read() assert isinstance(self.image, QImage) if make_opengl_textures: self.open_gl_texture = QOpenGLTexture(self.image.mirrored()) self.made_opengl_textures = True
def findIconHelper(self, size=int, themeName=str, iconName=str): pixmap = QPixmap() if iconName == '' or self.themeName == '': return pixmap if themeName == '': themeName = self.themeName if themeName == self.themeName: index = self.themeIndex else: index = self.readThemeIndex(themeName) subDirs = filter(lambda x: x[0] == str(size), index.dirList) for iconDir in self.iconDirs: if path.exists(path.join(iconDir, themeName)): for theme in subDirs: fileName = path.join(iconDir, themeName, theme[1], '%s.png' % str(iconName)) fileName_svg = path.join(iconDir, themeName, theme[1], '%s.svg' % str(iconName)) logging.debug('Looking for : %s' % fileName) if path.exists(fileName): pixmap.load(fileName) logging.debug('Icon: %s found in theme %s' % \ (iconName, themeName)) return pixmap elif path.exists(fileName_svg): pixmap.load(fileName_svg) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) return pixmap for iconDir in self.extraIcons: fileName = path.join(iconDir, '%s.png' % str(iconName)) fileName_svg = path.join(iconDir, '{}.svg'.format(str(iconName))) if path.exists(fileName): pixmap.load(fileName) #print "pixmap ->{}".format(fileName) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) return pixmap elif path.exists(fileName_svg): image = QImage(size, size, QImage.Format_RGB32) reader = QImageReader(fileName) reader.read(image) pixmap.convertFromImage(image) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) #print "pixmap ->{}".format(fileName) return pixmap if len(self._themes) > 0: self._themes.pop(0) if not len(self._themes) == 0 and pixmap.isNull(): pixmap = self.findIconHelper(size, self._themes[0], iconName) return pixmap
def findIconHelper(self, size = int, themeName = str, iconName = str): pixmap = QPixmap() if iconName == '' or self.themeName == '': return pixmap if themeName == '': themeName = self.themeName if themeName == self.themeName: index = self.themeIndex else: index = self.readThemeIndex(themeName) subDirs = filter(lambda x:x[0] == str(size), index.dirList) for iconDir in self.iconDirs: if path.exists(path.join(iconDir, themeName)): for theme in subDirs: fileName = path.join(iconDir, themeName, theme[1], '%s.png' % str(iconName)) fileName_svg = path.join(iconDir, themeName, theme[1], '%s.svg' % str(iconName)) logging.debug('Looking for : %s' % fileName) if path.exists(fileName): pixmap.load(fileName) logging.debug('Icon: %s found in theme %s' % \ (iconName, themeName)) return pixmap elif path.exists(fileName_svg): pixmap.load(fileName_svg) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) return pixmap for iconDir in self.extraIcons: fileName = path.join(iconDir, '%s.png' % str(iconName)) fileName_svg = path.join(iconDir, '{}.svg'.format(str(iconName))) if path.exists(fileName): pixmap.load(fileName) #print "pixmap ->{}".format(fileName) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) return pixmap elif path.exists(fileName_svg): image=QImage(size, size, QImage.Format_RGB32) reader=QImageReader(fileName) reader.read(image) pixmap.convertFromImage(image) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) #print "pixmap ->{}".format(fileName) return pixmap if len(self._themes) > 0: self._themes.pop(0) if not len(self._themes) == 0 and pixmap.isNull(): pixmap = self.findIconHelper(size, self._themes[0], iconName) return pixmap
def load(self, source): """Load anything that QImageReader or QMovie constructors accept""" # Use QImageReader to identify animated GIFs for separate handling # (Thanks to https://stackoverflow.com/a/20674469/435253 for this) image_reader = QImageReader(source) from PyQt5.QtGui import QImageIOHandler if image_reader.supportsAnimation() and image_reader.imageCount() > 1: movie = QMovie(source) # Calculate the aspect ratio and adjust the widget size movie.jumpToFrame(0) movie_size = movie.currentImage().size() self.movie_aspect = movie_size.width() / movie_size.height() self.resizeEvent() self.label.setMovie(movie) movie.start() # Free memory if the previous image was non-animated self.orig_pixmap = None else: self.orig_pixmap = QPixmap(image_reader.read()) self.label.setPixmap(self.orig_pixmap) # Fail quickly if our violated invariants result in stale # aspect-ratio information getting reused self.movie_aspect = None # Keep the image from preventing downscaling self.setMinimumSize(1, 1)
class QtReader(BaseReader): """Image reader using Qt's QImageReader implementation under the hood.""" def __init__(self, path: str, file_format: str): super().__init__(path, file_format) self._handler = QImageReader(path, file_format.encode()) self._handler.setAutoTransform(True) if not self._handler.canRead(): # TODO raise ValueError(f"'{path}' cannot be read as image") @classmethod def supports(cls, file_format: str) -> bool: return file_format in QImageReader.supportedImageFormats() @property def is_animation(self) -> bool: return self._handler.supportsAnimation() def get_pixmap(self) -> QPixmap: """Retrieve the pixmap directly from the image reader.""" pixmap = QPixmap.fromImageReader(self._handler) if self._handler.error(): raise ValueError( f"Error reading image '{self.path}': {self._handler.errorString()}" ) return pixmap def get_image(self, size: int) -> QImage: """Retrieve the down-scaled image directly from the image reader.""" qsize = self._handler.size() qsize.scale(size, size, Qt.KeepAspectRatio) self._handler.setScaledSize(qsize) return self._handler.read()
def replaceImage(self, filepath, title): self.title = title self.filepath = filepath # set custom properties self.setCustomProperty("title", title) self.setCustomProperty("filepath", self.filepath) self.setName(title) fileInfo = QFileInfo(filepath) ext = fileInfo.suffix() if ext == "pdf": s = QSettings() oldValidation = s.value("/Projections/defaultBehavior") s.setValue( "/Projections/defaultBehavior", "useGlobal" ) # for not asking about crs path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) self.image = layer.previewAsImage(QSize(layer.width(), layer.height())) s.setValue("/Projections/defaultBehavior", oldValidation) else: reader = QImageReader(filepath) self.image = reader.read() self.repaint()
def _loadQtImage(path: str) -> QImage: reader = QImageReader(path) image = QImage(reader.read()) if not image.isNull(): return image else: return None
def run(self): self.sock.bind(('', configs['live']['port'])) self.sock.settimeout(1) print('LiveClient bind in ', self.sock.getsockname()) while not self.stop_run: while self.wait_recv: try: receive_data = self.sock.recv(1024 * 100) # , address self.wait_recv = False except: pass self.wait_recv = True if self.stop_run: break receive_data = zlib.decompress(receive_data) byte_array = QByteArray(receive_data) buffer = QBuffer(byte_array) buffer.open(QIODevice.ReadOnly) # 读取图片 reader = QImageReader(buffer) q_img = reader.read() if self.stop_run: break self._screen.emit(q_img) self.sock.close() # 关闭套接字
def image_and_format_from_data(data): ' Create an image object from the specified data which should be a bytestring and also return the format of the image ' ba = QByteArray(data) buf = QBuffer(ba) buf.open(QBuffer.ReadOnly) r = QImageReader(buf) fmt = bytes(r.format()).decode('utf-8') return r.read(), fmt
def initializeLayer(self, screenExtent=None): if self.error or self.initialized or self.initializing: return if self.filepath is not None: # not safe... self.initializing = True filepath = self.getAbsoluteFilepath() if not os.path.exists(filepath): # TODO integrate with BadLayerHandler ? loadErrorDialog = LoadErrorDialog(filepath) result = loadErrorDialog.exec_() if result == 1: # absolute filepath = loadErrorDialog.lineEditImagePath.text() # to relative if needed self.filepath = utils.toRelativeToQGS(filepath) self.setCustomProperty("filepath", self.filepath) QgsProject.instance().setDirty(True) else: self.error = True del loadErrorDialog reader = QImageReader(filepath) self.image = reader.read() self.initialized = True self.initializing = False self.setupCrs() if screenExtent: # constructor called from AddLayer action # if not, layer loaded from QGS project file # check if image already has georef info # use GDAL dataset = gdal.Open(filepath, gdal.GA_ReadOnly) georef = None if dataset: georef = dataset.GetGeoTransform() if georef and not self.is_default_geotransform(georef): self.initializeExistingGeoreferencing(dataset, georef) else: # init to default params self.setCenter(screenExtent.center()) self.setRotation(0.0) sw = screenExtent.width() sh = screenExtent.height() self.resetScale(sw, sh) self.commitTransformParameters()
def readImageFromFile(fileName): reader = QImageReader(fileName) reader.setAutoTransform(True) reader.setAutoDetectImageFormat(True) image = reader.read() if not image: raise CannotReadImageException() return image
def replaceImage(self, filepath, title): self.title = title self.filepath = filepath # set custom properties self.setCustomProperty("title", title) self.setCustomProperty("filepath", self.filepath) self.setName(title) reader = QImageReader(filepath) self.image = reader.read() self.repaint()
def loadImageFile(fname): reader = QImageReader(fname) reader.setAutoTransform(True) newImage = reader.read() if newImage.isNull(): msg = ("couldnt load " + QFileInfo(fname).fileName() + ": " + reader.errorString()) sb_txt.setText(msg) return False else: return newImage
def sourceFile(self, value): self._sourceFile = value p = QImageReader(self._sourceFile) if (p.canRead()): p.setAutoTransform(True) self._image = p.read() self._transform = QTransform() print("loaded image "+value) else: self._image = None self.changed.emit()
def __display_result_image(self, file_path): image_reader = QImageReader(file_path) if image_reader.canRead() is True: widget_height = self.resultView.height() widget_width = self.resultView.width() image = image_reader.read().scaled(widget_width, widget_height, Qt.KeepAspectRatio) item = QGraphicsPixmapItem(QPixmap.fromImage(image)) scene = QGraphicsScene() scene.addItem(item) self.resultView.setScene(scene) else: scene = QGraphicsScene() self.resultView.setScene(scene)
def onOpenFileAction(self): fileList = QFileDialog.getOpenFileNames(self, 'open', self.workPath, 'Images(*.jpg *.jpeg *.png *.bmp);;All file(*.*)')# type:list[str] if len(fileList)<=0 or len(fileList[0])<=0: return reader = QImageReader(fileList[0][0]) reader.setAutoTransform(True) img = reader.read() if img.isNull(): QMessageBox.information(self, 'error', 'can not open %s as image!'%fileList[0][0], QMessageBox.Ok) return self.opendFile = fileList[0][0] self.__setImage(img, self.zoomList[self.zoomIdx]) if len(fileList[0])>=2: reader1 =QImageReader(fileList[0][1]) reader1.setAutoTransform(True) img1 = reader1.read() if img1.isNull(): QMessageBox.information(self, 'error', 'can not open %s as image!'%fileList[0][0], QMessageBox.Ok) return self.__setImage1(img1, self.zoomList[self.zoomIdx]) self.opendFile1 = fileList[0][1] self.__setTitle()
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 reader0 = QImageReader(imagePath) reader0.setAutoTransform(True) image = reader0.read() 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']) direction = shape['direction'] isRotated = shape['isRotated'] extra_text = shape['extra_text'] if not isRotated: bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult, extra_text) 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, extra_text) writer.save(targetFile=filename) return
def __changed_image_line_edit(self): file_path = self.lineEdit_image.text() image_reader = QImageReader(file_path) if image_reader.canRead() is True: widget_height = self.queryView.height() widget_width = self.queryView.width() image = image_reader.read().scaled(widget_width, widget_height, Qt.KeepAspectRatio) item = QGraphicsPixmapItem(QPixmap.fromImage(image)) scene = QGraphicsScene() scene.addItem(item) self.queryView.setScene(scene) else: scene = QGraphicsScene() self.queryView.setScene(scene)
def load_and_unpickle_image_hash(self, filepath): image_hash = {} bytearray_hash = pickle.load(open(filepath, "rb")) for k in bytearray_hash.keys(): byte_array = bytearray_hash[k] buffer = QBuffer(byte_array) buffer.open(QIODevice.ReadOnly) reader = QImageReader(buffer) img = reader.read() image_hash[k] = img return image_hash
def load_image_data(self) -> QImage: """ Loads the image data from disk. This has to be called when the file content needs to be accessed. :return: """ logger.debug( f"Requested loading image data from the hard disk. File: {self.image_path}" ) image_reader = QImageReader(str(self.image_path)) if image_reader.canRead(): logger.debug("Image data can be read, performing file reading…") self.image_data = image_reader.read() logger.info( f"File reading done. Loaded image dimensions: " f"x={self.image_data.width()}, y={self.image_data.height()}, format={self.image_data.format()}" ) return self.image_data else: raise RuntimeError(f"Image {self.image_path} cannot be read.")
def dropEvent(self, event): # # 方法一:针对小图片 # pixmap = QPixmap(event.mimeData().urls()[0].toLocalFile()) # self.ui.LabPic.setPixmap(pixmap) # # # 方法二:小图片和PNG格式的大图片 # img = QImage() # print(event.mimeData().urls()[0].toLocalFile()) # img.load(event.mimeData().urls()[0].toLocalFile()) # pixmap = QPixmap.fromImage(img.scaled(self.ui.LabPic.size(), Qt.KeepAspectRatio)) # self.ui.LabPic.setPixmap(pixmap) # 方法三:小图片和大图片 reader = QImageReader() print(event.mimeData().urls()[0].toLocalFile()) reader.setFileName(event.mimeData().urls()[0].toLocalFile()) reader.setDecideFormatFromContent(True) if reader.canRead(): img = QImage(reader.read()) pixmap = QPixmap.fromImage( img.scaled(self.ui.LabPic.size(), Qt.KeepAspectRatio)) self.ui.LabPic.setPixmap(pixmap)
def load_cr3(path) -> QPixmap: """Extract the thumbnail from the image and initialize QPixmap""" process = QProcess() process.start(f"exiftool -b -JpgFromRaw {path}") process.waitForFinished() if process.exitStatus() != QProcess.NormalExit or process.exitCode() != 0: stderr = process.readAllStandardError() raise ValueError(f"Error calling exiftool: '{stderr.data().decode()}'") handler = QImageReader(process, "jpeg".encode()) handler.setAutoTransform(True) process.closeWriteChannel() process.terminate() # Extract QImage from QImageReader and convert to QPixmap pixmap = QPixmap() pixmap.convertFromImage(handler.read()) return pixmap
def _create_thumbnail(self, path: str, thumbnail_path: str) -> QPixmap: """Create thumbnail for an image. Args: path: Path to the image for which the thumbnail is created. thumbnail_path: Path to which the thumbnail is stored. Returns: The created QPixmap. """ # Cannot access source if not os.access(path, os.R_OK): return self._manager.fail_pixmap size = 256 if self._manager.large else 128 reader = QImageReader(path) reader.setAutoTransform(True) # Automatically apply exif orientation if reader.canRead(): qsize = reader.size() qsize.scale(size, size, Qt.KeepAspectRatio) reader.setScaledSize(qsize) image = reader.read() # Image was deleted in the time between reader.read() and now try: attributes = self._get_thumbnail_attributes(path, image) except FileNotFoundError: return self._manager.fail_pixmap for key, value in attributes.items(): image.setText(key, value) # First create temporary file and then move it. This avoids # problems with concurrent access of the thumbnail cache, since # "move" is an atomic operation handle, tmp_filename = tempfile.mkstemp( dir=self._manager.directory) os.close(handle) os.chmod(tmp_filename, 0o600) image.save(tmp_filename, format="png") os.replace(tmp_filename, thumbnail_path) return QPixmap(image) return self._manager.fail_pixmap
def load_frame(path) -> QPixmap: """Extract the first frame from the video and initialize QPixmap""" process = QProcess() process.start( f"ffmpeg -loglevel quiet -i {path} -vframes 1 -f image2 pipe:1") process.waitForFinished() if process.exitStatus() != QProcess.NormalExit or process.exitCode() != 0: stderr = process.readAllStandardError() raise ValueError(f"Error calling ffmpeg: '{stderr.data().decode()}'") handler = QImageReader(process, "jpeg".encode()) handler.setAutoTransform(True) process.closeWriteChannel() process.terminate() # Extract QImage from QImageReader and convert to QPixmap pixmap = QPixmap() pixmap.convertFromImage(handler.read()) return pixmap
def get_archive_wallpapers(self): """ Generator returning the date, path and copyright info (via db lookup) of each file found in the archive location. :rtype: QDate, unicode, unicode """ image_reader = QImageReader() regex_date_split = re.compile(r'(\d{4})(\d{2})(\d{2})') copyright_info = self.copyright_db.get_all_info() archive_folder = self.settings.archive_location for filename in reversed([ x for x in os.listdir(archive_folder) if re_archive_file.match(x) ]): year, month, day = list( map(int, regex_date_split.findall(filename)[0])) wallpaper_date = QDate(year, month, day) wallpaper_copyright = copyright_info.get( '{0:04d}-{1:02d}-{2:02d}'.format(year, month, day), '') wallpaper_filename = os.path.join(str(archive_folder), filename) image_reader.setFileName(wallpaper_filename) image_size = image_reader.size() image_size.scale(QSize(200, 125), Qt.IgnoreAspectRatio) image_reader.setScaledSize(image_size) thumbnail_image = image_reader.read() if thumbnail_image.isNull(): continue self.lw_wallpaper_history.add_item(thumbnail_image, wallpaper_date, wallpaper_copyright, archive_path=wallpaper_filename) self.app.processEvents() self.lw_wallpaper_history.sortItems(Qt.AscendingOrder)
def replaceImage(self, filepath, title): self.title = title self.filepath = filepath # set custom properties self.setCustomProperty("title", title) self.setCustomProperty("filepath", self.filepath) self.setName(title) fileInfo = QFileInfo(filepath) ext = fileInfo.suffix() if ext == "pdf": s = QSettings() oldValidation = s.value("/Projections/defaultBehavior") s.setValue("/Projections/defaultBehavior", "useGlobal") # for not asking about crs path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) self.image = layer.previewAsImage(QSize(layer.width(), layer.height())) s.setValue("/Projections/defaultBehavior", oldValidation) else: reader = QImageReader(filepath) self.image = reader.read() self.repaint()
def load(self, source, adaptSize=True): """Load anything that QImageReader or QMovie constructors accept adaptSize=True: Initial image size to fit container adaptSize=False: Set container's size the same as image """ # Use QImageReader to identify animated GIFs for separate handling # (Thanks to https://stackoverflow.com/a/20674469/435253 for this) size = QSize(self.width(), self.height()) image_reader = QImageReader(source) if image_reader.supportsAnimation() and image_reader.imageCount() > 1: # Set content as Movie self.content = SaneQMovie(source) # Adjust the widget size if adaptSize: self.content.adaptScale(size) else: # Resizing container will trigger resizeEvent() self.resize(self.content.size()) # Start Movie replay self.setMovie(self.content) self.content.start() else: # Set content as Image self.content = SaneQPixmap(image_reader.read()) # Adjust the widget size if adaptSize: self.setPixmap(self.content.adaptScale(size)) else: # Resizing container will trigger resizeEvent() self.resize(self.content.size()) self.setPixmap(self.content) # Keep the image from preventing downscaling self.setMinimumSize(1, 1)
def initializeLayer(self, screenExtent=None): if self.error or self.initialized or self.initializing: return if self.filepath is not None: # not safe... self.initializing = True filepath = self.getAbsoluteFilepath() if not os.path.exists(filepath): # TODO integrate with BadLayerHandler ? loadErrorDialog = LoadErrorDialog(filepath) result = loadErrorDialog.exec_() if result == 1: # absolute filepath = loadErrorDialog.lineEditImagePath.text() # to relative if needed self.filepath = utils.toRelativeToQGS(filepath) self.setCustomProperty("filepath", self.filepath) QgsProject.instance().setDirty(True) else: self.error = True del loadErrorDialog fileInfo = QFileInfo(filepath) ext = fileInfo.suffix() if ext == "pdf": s = QSettings() oldValidation = s.value("/Projections/defaultBehavior") s.setValue("/Projections/defaultBehavior", "useGlobal") # for not asking about crs path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) self.image = layer.previewAsImage(QSize(layer.width(),layer.height())) s.setValue("/Projections/defaultBehavior", oldValidation) else: reader = QImageReader(filepath) self.image = reader.read() self.initialized = True self.initializing = False self.setupCrs() if screenExtent: # constructor called from AddLayer action # if not, layer loaded from QGS project file # check if image already has georef info # use GDAL dataset = gdal.Open(filepath, gdal.GA_ReadOnly) georef = None if dataset: georef = dataset.GetGeoTransform() if georef and not self.is_default_geotransform(georef): self.initializeExistingGeoreferencing(dataset, georef) else: # init to default params self.setCenter(screenExtent.center()) self.setRotation(0.0) sw = screenExtent.width() sh = screenExtent.height() self.resetScale(sw, sh) self.commitTransformParameters()
def initializeLayer(self, screenExtent=None): if self.error or self.initialized or self.initializing: return if self.filepath is not None: # not safe... self.initializing = True filepath = self.getAbsoluteFilepath() if not os.path.exists(filepath): # TODO integrate with BadLayerHandler ? loadErrorDialog = LoadErrorDialog(filepath) result = loadErrorDialog.exec_() if result == 1: # absolute filepath = loadErrorDialog.lineEditImagePath.text() # to relative if needed self.filepath = utils.toRelativeToQGS(filepath) self.setCustomProperty("filepath", self.filepath) QgsProject.instance().setDirty(True) else: self.error = True del loadErrorDialog fileInfo = QFileInfo(filepath) ext = fileInfo.suffix() if ext == "pdf": s = QSettings() oldValidation = s.value("/Projections/defaultBehavior") s.setValue("/Projections/defaultBehavior", "useGlobal") # for not asking about crs path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) self.image = layer.previewAsImage( QSize(layer.width(), layer.height())) s.setValue("/Projections/defaultBehavior", oldValidation) else: reader = QImageReader(filepath) self.image = reader.read() self.initialized = True self.initializing = False self.setupCrs() if screenExtent: # constructor called from AddLayer action # if not, layer loaded from QGS project file # check if image already has georef info # use GDAL dataset = gdal.Open(filepath, gdal.GA_ReadOnly) georef = None if dataset: georef = dataset.GetGeoTransform() if georef and not self.is_default_geotransform(georef): self.initializeExistingGeoreferencing(dataset, georef) else: # init to default params self.setCenter(screenExtent.center()) self.setRotation(0.0) sw = screenExtent.width() sh = screenExtent.height() self.resetScale(sw, sh) self.commitTransformParameters()
def initializeLayer(self, screenExtent=None): if self.error or self.initialized or self.initializing: return if self.filepath is not None: # not safe... self.initializing = True absPath = self.getAbsoluteFilepath() if not os.path.exists(absPath): # TODO integrate with BadLayerHandler ? loadErrorDialog = LoadErrorDialog(absPath) result = loadErrorDialog.exec_() if result == 1: # absolute absPath = loadErrorDialog.lineEditImagePath.text() # to relative if needed self.filepath = utils.toRelativeToQGS(absPath) self.setCustomProperty("filepath", self.filepath) QgsProject.instance().setDirty(True) else: self.error = True del loadErrorDialog imageFormat = utils.imageFormat(absPath) if imageFormat == "pdf": s = QSettings() oldValidation = s.value("/Projections/defaultBehavior") s.setValue( "/Projections/defaultBehavior", "useGlobal" ) # for not asking about crs layer = QgsRasterLayer(absPath, os.path.basename(absPath)) self.image = layer.previewAsImage(QSize(layer.width(), layer.height())) s.setValue("/Projections/defaultBehavior", oldValidation) else: has_corrected = False if imageFormat == "tif": # other than TIFF => assumes can be loaded by Qt has_corrected = self.preCheckImage(absPath) if has_corrected: # image already loaded by preCheckImage self.showBarMessage( "Raster changed", "Raster content has been transformed for display in the " "plugin. " "When exporting, select the 'Only export world file' checkbox.", Qgis.Warning, 10, ) else: reader = QImageReader(absPath) self.image = reader.read() self.initialized = True self.initializing = False self.setupCrs() if screenExtent: # constructor called from AddLayer action # if not, layer loaded from QGS project file # check if image already has georef info # use GDAL dataset = gdal.Open(absPath, gdal.GA_ReadOnly) georef = None if dataset: georef = dataset.GetGeoTransform() if georef and not self.is_default_geotransform(georef): self.initializeExistingGeoreferencing(dataset, georef) else: # init to default params self.setCenter(screenExtent.center()) self.setRotation(0.0) sw = screenExtent.width() sh = screenExtent.height() self.resetScale(sw, sh) self.commitTransformParameters()
def readImage(self, filename): image_reader = QImageReader(filename) image_reader.setAutoTransform(True) return image_reader.read()
def loadFile(self, filename=None): ''' 根据文件名加载文件 并在canvas中显示 ''' if not filename: return # 如果该文件已经被加载 则直接返回 if filename in self.imageList and self.listWidget_files.currentRow( ) != self.imageList.index(filename): self.listWidget_files.setCurrentRow(self.imageList.index(filename)) self.listWidget_files.repaint() return self.statusbar.showMessage('opening {}'.format(filename)) self.resetState() self.canvas.setEnabled(False) # 使用QIamgeReader读取图像 reader = QImageReader(filename) reader.setAutoTransform(True) image = reader.read() if image.isNull(): self.statusbar.showMessage('Error loading {}'.format(filename)) return # 假设该图像已经被标记 # 那么应该存在同名 Json 文件 label_file = os.path.splitext(filename)[0] + '.json' # 如果存在同名 Json文件 # TODO: 进行 Json 合法性检查 这里直接忽略了 if QFile.exists(label_file): # 从 Json 文件中提取标注区域信息 shapes = loadJsonFile(label_file) # 交给 canvas 类处理 self.canvas.retrieveAndLoadShape(shapes) # 更新右侧的label列表 # labels 记录所有的标注信息 # Python Set 用于去重 labels = list(shape.label for shape in self.canvas.shapes) for label in set(labels): self.listWidget_labels.addItem(label) # 更新 itemToShapes 字典 for shape in self.canvas.shapes: self.itemToShapes[shape.label] = \ self.itemToShapes.get(shape.label, []) + [shape] self.image = image self.filename = filename self.canvas.scale = self.computeScale(image) self.spinbox_scale.setValue(int(self.canvas.scale * 100)) self.canvas.loadPixmap(QPixmap.fromImage(image)) self.canvas.setEnabled(True) self.statusbar.showMessage('{}'.format(filename)) self.setClean() self.actionCreate_Polygons.setEnabled(True) self.actionCreate_Rectangle.setEnabled(True) self.actionCreate_Circle.setEnabled(True)
def dropEvent(self, event:QDropEvent): mainWidget_rect = self.mainWidget.geometry() dropPt = event.pos() if dropPt.x()<mainWidget_rect.left() or dropPt.x()>mainWidget_rect.right() or dropPt.y()<mainWidget_rect.top() or dropPt.y()>mainWidget_rect.bottom(): return mData = event.mimeData() if not mData.hasUrls(): return urlList = mData.urls() if len(urlList)==1: scrollArea_rect = self.scrollArea.geometry().translated(mainWidget_rect.topLeft()) scrollArea1_rect = self.scrollArea1.geometry().translated(mainWidget_rect.topLeft()) if dropPt.x()>scrollArea_rect.left() and dropPt.x()<scrollArea_rect.right(): fileName = urlList[0].toLocalFile() if len(fileName)<=0 or fileName==None: return if fileName.endswith(('.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.bmp', '.BMP')): reader = QImageReader(fileName) reader.setAutoTransform(True) img = reader.read() if img.isNull(): QMessageBox.information(self, 'error', 'can not open %s as image!'%fileName, QMessageBox.Ok) return self.opendFile = fileName self.__setTitle() self.__setImage(img, self.zoomList[self.zoomIdx]) elif dropPt.x()>scrollArea1_rect.left() and dropPt.x()<scrollArea1_rect.right(): fileName = urlList[0].toLocalFile() if len(fileName)<=0 or fileName==None: return if fileName.endswith(('.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.bmp', '.BMP')): reader = QImageReader(fileName) reader.setAutoTransform(True) img = reader.read() if img.isNull(): QMessageBox.information(self, 'error', 'can not open %s as image!'%fileName, QMessageBox.Ok) return self.opendFile1 = fileName self.__setTitle() self.__setImage1(img, self.zoomList[self.zoomIdx]) else: pass elif len(urlList)>=2: fileName = urlList[0].toLocalFile() fileName1 = urlList[1].toLocalFile() if len(fileName)<=0 or fileName==None or len(fileName1)<=0 or fileName1==None: return if fileName.endswith(('.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.bmp', '.BMP')) and fileName1.endswith(('.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.bmp', '.BMP')): reader = QImageReader(fileName) reader.setAutoTransform(True) img = reader.read() reader1 = QImageReader(fileName1) reader1.setAutoTransform(True) img1 = reader1.read() if img.isNull() or img1.isNull(): QMessageBox.information(self, 'error', 'can not open %s %sas image!'%(fileName, fileName1), QMessageBox.Ok) return self.opendFile = fileName self.opendFile1 = fileName1 self.__setTitle() self.__setImage(img, self.zoomList[self.zoomIdx]) self.__setImage1(img1, self.zoomList[self.zoomIdx]) else: pass