def get_pixmap(icon_name): ''' Retrieve a QPixmap for the named image Any icons belonging to the plugin must be prefixed with 'images/' ''' global plugin_icon_resources, plugin_name if not icon_name.startswith('images/'): # We know this is definitely not an icon belonging to this plugin pixmap = QPixmap() pixmap.load(I(icon_name)) return pixmap # Check to see whether the icon exists as a Calibre resource # This will enable skinning if the user stores icons within a folder like: # ...\AppData\Roaming\calibre\resources\images\Plugin Name\ if plugin_name: local_images_dir = get_local_images_dir(plugin_name) local_image_path = os.path.join(local_images_dir, icon_name.replace('images/', '')) if os.path.exists(local_image_path): pixmap = QPixmap() pixmap.load(local_image_path) return pixmap # As we did not find an icon elsewhere, look within our zip resources if icon_name in plugin_icon_resources: pixmap = QPixmap() pixmap.loadFromData(plugin_icon_resources[icon_name]) return pixmap return None
def get_pixmap(icon_name): ''' Retrieve a QPixmap for the named image Any icons belonging to the plugin must be prefixed with 'images/' ''' if not icon_name.startswith('images/'): # We know this is definitely not an icon belonging to this plugin pixmap = QPixmap() pixmap.load(I(icon_name)) return pixmap # Check to see whether the icon exists as a Calibre resource # This will enable skinning if the user stores icons within a folder like: # ...\AppData\Roaming\calibre\resources\images\Plugin Name\ if plugin_name: local_images_dir = get_local_images_dir(plugin_name) local_image_path = os.path.join(local_images_dir, icon_name.replace('images/', '')) if os.path.exists(local_image_path): pixmap = QPixmap() pixmap.load(local_image_path) return pixmap # As we did not find an icon elsewhere, look within our zip resources if icon_name in plugin_icon_resources: pixmap = QPixmap() pixmap.loadFromData(plugin_icon_resources[icon_name]) return pixmap return None
def files_dropped_on_book(self, event, paths, cid=None, do_confirm=True): accept = False if self.gui.current_view() is not self.gui.library_view: return db = self.gui.library_view.model().db cover_changed = False current_idx = self.gui.library_view.currentIndex() if cid is None: if not current_idx.isValid(): return cid = db.id(current_idx.row()) if cid is None else cid formats = [] from calibre.gui2.dnd import image_extensions image_exts = set(image_extensions()) - set( tweaks['cover_drop_exclude']) if iswindows: from calibre.gui2.add import resolve_windows_links paths = list( resolve_windows_links(paths, hwnd=int(self.gui.effectiveWinId()))) for path in paths: ext = os.path.splitext(path)[1].lower() if ext: ext = ext[1:] if ext in image_exts: pmap = QPixmap() pmap.load(path) if not pmap.isNull(): accept = True db.set_cover(cid, pmap) cover_changed = True else: formats.append((ext, path)) accept = True if accept and event is not None: event.accept() add_as_book = False if do_confirm and formats: ok, add_as_book = confirm(_( 'You have dropped some files onto the book <b>%s</b>. This will' ' add or replace the files for this book. Do you want to proceed?' ) % db.title(cid, index_is_id=True), 'confirm_drop_on_book', parent=self.gui, extra_button=ngettext( 'Add as new book', 'Add as new books', len(formats))) if ok and add_as_book: add_as_book = [path for ext, path in formats] if not ok or add_as_book: formats = [] for ext, path in formats: db.add_format_with_hooks(cid, ext, path, index_is_id=True) if current_idx.isValid(): self.gui.library_view.model().current_changed( current_idx, current_idx) if cover_changed: self.gui.refresh_cover_browser() if add_as_book: self.files_dropped(add_as_book)
def get_icon(self, icon_name): """ Check to see whether the icon exists as a Calibre resource This will enable skinning if the user stores icons within a folder like: ...\AppData\Roaming\calibre\resources\images\Plugin Name\ """ icon_path = os.path.join(config_dir, 'resources', 'images', self.name, icon_name) if not os.path.exists(icon_path): return get_icons(self.plugin_path, 'images/{0}'.format(icon_name)) pixmap = QPixmap() pixmap.load(icon_path) return QIcon(pixmap)
def get_icon(self, icon_name): """ Check to see whether the icon exists as a Calibre resource This will enable skinning if the user stores icons within a folder like: ...\AppData\Roaming\calibre\resources\images\Plugin Name\ """ icon_path = os.path.join(config_dir, 'resources', 'images', self.name, icon_name) if not os.path.exists(icon_path): return get_icons(self.plugin_path, 'images/{0}'.format(icon_name)) pixmap = QPixmap() pixmap.load(icon_path) return QIcon(pixmap)
def get_icon(icon_name): # Check to see whether the icon exists as a Calibre resource # This will enable skinning if the user stores icons within a folder like: # ...\AppData\Roaming\calibre\resources\images\Plugin Name\ icon_path = os.path.join(config_dir, 'resources', 'images', 'Diaps Editing Toolbag', icon_name.replace('images/', '')) if os.path.exists(icon_path): pixmap = QPixmap() pixmap.load(icon_path) return QIcon(pixmap) # As we did not find an icon elsewhere, look within our zip resources return get_icons(icon_name)
def files_dropped_on_book(self, event, paths, cid=None, do_confirm=True): accept = False if self.gui.current_view() is not self.gui.library_view: return db = self.gui.library_view.model().db cover_changed = False current_idx = self.gui.library_view.currentIndex() if cid is None: if not current_idx.isValid(): return cid = db.id(current_idx.row()) if cid is None else cid formats = [] from calibre.gui2.dnd import image_extensions for path in paths: ext = os.path.splitext(path)[1].lower() if ext: ext = ext[1:] if ext in image_extensions(): pmap = QPixmap() pmap.load(path) if not pmap.isNull(): accept = True db.set_cover(cid, pmap) cover_changed = True else: formats.append((ext, path)) accept = True if accept and event is not None: event.accept() if do_confirm and formats: if not confirm(_( 'You have dropped some files onto the book <b>%s</b>. This will' ' add or replace the files for this book. Do you want to proceed?' ) % db.title(cid, index_is_id=True), 'confirm_drop_on_book', parent=self.gui): formats = [] for ext, path in formats: db.add_format_with_hooks(cid, ext, path, index_is_id=True) if current_idx.isValid(): self.gui.library_view.model().current_changed( current_idx, current_idx) if cover_changed: self.gui.refresh_cover_browser()
def __init__(self, parent, icon_name, title): QHBoxLayout.__init__(self) title_font = QFont() title_font.setPointSize(16) title_image_label = QLabel(parent) pixmap = QPixmap() pixmap.load(I(icon_name)) if pixmap is None: error_dialog(parent, _('Restart required'), _('You must restart calibre before using this plugin!'), show=True) else: title_image_label.setPixmap(pixmap) title_image_label.setMaximumSize(32, 32) title_image_label.setScaledContents(True) self.addWidget(title_image_label) shelf_label = QLabel(title, parent) shelf_label.setFont(title_font) self.addWidget(shelf_label) self.insertStretch(-1)
def __init__(self, parent, icon_name, title): QHBoxLayout.__init__(self) title_font = QFont() title_font.setPointSize(16) title_image_label = QLabel(parent) pixmap = QPixmap() pixmap.load(I(icon_name)) if pixmap is None: error_dialog(parent, _('Restart required'), _('You must restart calibre before using this plugin!'), show=True) else: title_image_label.setPixmap(pixmap) title_image_label.setMaximumSize(32, 32) title_image_label.setScaledContents(True) self.addWidget(title_image_label) shelf_label = QLabel(title, parent) shelf_label.setFont(title_font) self.addWidget(shelf_label) self.insertStretch(-1)
def render_images(self, outpath, mi, items): printer = get_pdf_printer(self.opts, for_comic=True, output_file_name=outpath) printer.setDocName(mi.title) painter = QPainter(printer) painter.setRenderHints(QPainter.Antialiasing|QPainter.SmoothPixmapTransform) for i, imgpath in enumerate(items): self.log('Rendering image:', i) p = QPixmap() p.load(imgpath) if not p.isNull(): if i > 0: printer.newPage() draw_image_page(printer, painter, p) else: self.log.warn('Failed to load image', i) painter.end()
def render_images(self, outpath, mi, items): printer = get_pdf_printer(self.opts, for_comic=True, output_file_name=outpath) printer.setDocName(mi.title) painter = QPainter(printer) painter.setRenderHints(QPainter.Antialiasing|QPainter.SmoothPixmapTransform) for i, imgpath in enumerate(items): self.log('Rendering image:', i) p = QPixmap() p.load(imgpath) if not p.isNull(): if i > 0: printer.newPage() draw_image_page(printer, painter, p) else: self.log.warn('Failed to load image', i) painter.end()
def files_dropped_on_book(self, event, paths, cid=None, do_confirm=True): accept = False if self.gui.current_view() is not self.gui.library_view: return db = self.gui.library_view.model().db cover_changed = False current_idx = self.gui.library_view.currentIndex() if cid is None: if not current_idx.isValid(): return cid = db.id(current_idx.row()) if cid is None else cid formats = [] from calibre.gui2.dnd import image_extensions image_exts = set(image_extensions()) - set(tweaks['cover_drop_exclude']) for path in paths: ext = os.path.splitext(path)[1].lower() if ext: ext = ext[1:] if ext in image_exts: pmap = QPixmap() pmap.load(path) if not pmap.isNull(): accept = True db.set_cover(cid, pmap) cover_changed = True else: formats.append((ext, path)) accept = True if accept and event is not None: event.accept() if do_confirm and formats: if not confirm( _('You have dropped some files onto the book <b>%s</b>. This will' ' add or replace the files for this book. Do you want to proceed?') % db.title(cid, index_is_id=True), 'confirm_drop_on_book', parent=self.gui): formats = [] for ext, path in formats: db.add_format_with_hooks(cid, ext, path, index_is_id=True) if current_idx.isValid(): self.gui.library_view.model().current_changed(current_idx, current_idx) if cover_changed: self.gui.refresh_cover_browser()
def view_image(self, name): path = get_path_for_name(name) if path: pmap = QPixmap() if pmap.load(path): self.image_popup.current_img = pmap self.image_popup.current_url = QUrl.fromLocalFile(path) self.image_popup() else: error_dialog(self, _('Invalid image'), _( "Failed to load the image {}").format(name), show=True) else: error_dialog(self, _('Image not found'), _( "Failed to find the image {}").format(name), show=True)
class GuiRunner(QObject): '''Make sure an event loop is running before starting the main work of initialization''' def __init__(self, opts, args, actions, listener, app, gui_debug=None): self.startup_time = time.time() self.opts, self.args, self.listener, self.app = opts, args, listener, app self.gui_debug = gui_debug self.actions = actions self.main = None QObject.__init__(self) self.splash_screen = None self.timer = QTimer.singleShot(1, self.initialize) if DEBUG: prints('Starting up...') def start_gui(self, db): from calibre.gui2.ui import Main main = self.main = Main(self.opts, gui_debug=self.gui_debug) if self.splash_screen is not None: self.splash_screen.showMessage(_('Initializing user interface...')) with gprefs: # Only write gui.json after initialization is complete main.initialize(self.library_path, db, self.listener, self.actions) if self.splash_screen is not None: self.splash_screen.finish(main) if DEBUG: prints( 'Started up in %.2f seconds' % (time.time() - self.startup_time), 'with', len(db.data), 'books') add_filesystem_book = partial( main.iactions['Add Books'].add_filesystem_book, allow_device=False) sys.excepthook = main.unhandled_exception if len(self.args) > 1: files = [ os.path.abspath(p) for p in self.args[1:] if not os.path.isdir(p) ] if len(files) < len(sys.argv[1:]): prints('Ignoring directories passed as command line arguments') if files: add_filesystem_book(files) for event in self.app.file_event_hook.events: add_filesystem_book(event) self.app.file_event_hook = add_filesystem_book def initialization_failed(self): print 'Catastrophic failure initializing GUI, bailing out...' QCoreApplication.exit(1) raise SystemExit(1) def initialize_db_stage2(self, db, tb): from calibre.db.legacy import LibraryDatabase if db is None and tb is not None: # DB Repair failed error_dialog(self.splash_screen, _('Repairing failed'), _('The database repair failed. Starting with ' 'a new empty library.'), det_msg=tb, show=True) if db is None: candidate = choose_dir( self.splash_screen, 'choose calibre library', _('Choose a location for your new calibre e-book library'), default_dir=get_default_library_path()) if not candidate: self.initialization_failed() try: self.library_path = candidate db = LibraryDatabase(candidate) except: error_dialog( self.splash_screen, _('Bad database location'), _('Bad database location %r. calibre will now quit.') % self.library_path, det_msg=traceback.format_exc(), show=True) self.initialization_failed() try: self.start_gui(db) except Exception: error_dialog( self.main, _('Startup error'), _('There was an error during {0} startup.' ' Parts of {0} may not function. Click Show details to learn more.' ).format(__appname__), det_msg=traceback.format_exc(), show=True) def initialize_db(self): from calibre.db.legacy import LibraryDatabase db = None try: db = LibraryDatabase(self.library_path) except apsw.Error: repair = question_dialog( self.splash_screen, _('Corrupted database'), _('The library database at %s appears to be corrupted. Do ' 'you want calibre to try and rebuild it automatically? ' 'The rebuild may not be completely successful. ' 'If you say No, a new empty calibre library will be created.' ) % force_unicode(self.library_path, filesystem_encoding), det_msg=traceback.format_exc()) if repair: if repair_library(self.library_path): db = LibraryDatabase(self.library_path) except: error_dialog(self.splash_screen, _('Bad database location'), _('Bad database location %r. Will start with ' ' a new, empty calibre library') % self.library_path, det_msg=traceback.format_exc(), show=True) self.initialize_db_stage2(db, None) def show_splash_screen(self): self.splash_pixmap = QPixmap() self.splash_pixmap.load(I('library.png')) self.splash_screen = QSplashScreen(self.splash_pixmap) self.splash_screen.showMessage( _('Starting %s: Loading books...') % __appname__) self.splash_screen.show() QApplication.instance().processEvents() def initialize(self, *args): if gprefs['show_splash_screen']: self.show_splash_screen() self.library_path = get_library_path(parent=self.splash_screen) if not self.library_path: self.initialization_failed() self.initialize_db()
def __init__(self, parent): self.current_img = QPixmap() self.current_url = QUrl() self.parent = parent self.dialogs = [] def __call__(self): if self.current_img.isNull(): return d = ImageView(self.parent, self.current_img, self.current_url) self.dialogs.append(d) d.finished.connect(self.cleanup, type=Qt.QueuedConnection) d() def cleanup(self): for d in tuple(self.dialogs): if not d.isVisible(): self.dialogs.remove(d) if __name__ == '__main__': import sys from calibre.gui2 import Application app = Application([]) p = QPixmap() p.load(sys.argv[-1]) u = QUrl.fromLocalFile(sys.argv[-1]) d = ImageView(None, p, u) d() app.exec_()
def _fetch_marvin_cover(border_width=0): ''' Retrieve LargeCoverJpg from cache ''' #self._log_location('border_width: {0}'.format(border_width)) con = sqlite3.connect(self.marvin_db_path) with con: con.row_factory = sqlite3.Row # Fetch Hash from mainDb cover_cur = con.cursor() cover_cur.execute('''SELECT Hash FROM Books WHERE ID = '{0}' '''.format(self.book_id)) row = cover_cur.fetchone() book_hash = row[b'Hash'] large_covers_subpath = self.connected_device._cover_subpath( size="large") cover_path = '/'.join([large_covers_subpath, '%s.jpg' % book_hash]) stats = self.parent.ios.exists(cover_path) if stats: self._log("fetching large cover from cache") #self._log("cover size: {:,} bytes".format(int(stats['st_size']))) cover_bytes = self.parent.ios.read(cover_path, mode='rb') m_image = QImage() m_image.loadFromData(cover_bytes) if border_width: # Construct a QPixmap with oversized yellow background m_image = m_image.scaledToHeight( self.COVER_ICON_SIZE - border_width * 2, Qt.SmoothTransformation) self.m_pixmap = QPixmap( QSize(m_image.width() + border_width * 2, m_image.height() + border_width * 2)) m_painter = QPainter(self.m_pixmap) m_painter.setRenderHints(m_painter.Antialiasing) m_painter.fillRect(self.m_pixmap.rect(), self.MISMATCH_COLOR) m_painter.drawImage(border_width, border_width, m_image) else: m_image = m_image.scaledToHeight(self.COVER_ICON_SIZE, Qt.SmoothTransformation) self.m_pixmap = QPixmap( QSize(m_image.width(), m_image.height())) m_painter = QPainter(self.m_pixmap) m_painter.setRenderHints(m_painter.Antialiasing) m_painter.drawImage(0, 0, m_image) self.marvin_cover.setPixmap(self.m_pixmap) else: # No cover available, use generic self._log("No cached cover, using generic") pixmap = QPixmap() pixmap.load(I('book.png')) pixmap = pixmap.scaled(self.COVER_ICON_SIZE, self.COVER_ICON_SIZE, aspectRatioMode=Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) self.marvin_cover.setPixmap(pixmap)
class MainWindow(QMainWindow, Ui_mainWidget): # 为了实现窗口的显示和业务逻辑分离,新建另一个调用窗口的文件 def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.board = QPixmap(865, 485) self.board.fill(Qt.white) self.is_empty = True # 空画板 self.last_pos = QPoint(0, 0) self.current_pos = QPoint(0, 0) self.painter = QPainter() self.painter.setRenderHint(QPainter.Antialiasing) # 反锯齿 self.clearButton.clicked.connect(self.clear) self.uploadButton.clicked.connect(self.upload) self.runButton.clicked.connect(self.run) # 在此处识别,调用算法中的识别函数 def run(self): algorithm = self.algorithmCombo.currentText() target = self.targetCombo.currentText() print(algorithm, target) # 先保存图片然后找到该图片识别 image = self.board.toImage() # 这里可以改图片存储路径 image_save_path = 'images/testImage.jpg' image.save(image_save_path) # 为了方便,识别时直接去存储路径下获取图片 img_path = image_save_path # 由于尚未尝试用除NN外的算法去同时识别数字+字母,所以当选择其他算法时需要输出提示信息 try: # 需要更名选择不同的model,可能会不存在,先load下来看是否报错 model_path = model_path_dic[algorithm][target_sub[target]] if algorithm == "SVM" or algorithm == "KNN": model = joblib.load(model_path) else: model = load_model(model_path) except: # 如果图片路径下没有相应的图片或是模型路径下没有相应的模型,报错 QMessageBox.about(self, "提示", "暂不支持") self.resultLineEdit.setText("") self.board.fill(Qt.white) else: # 运行并返回预测结果 prediction = run(img_path, model_path, algorithmName_sub[algorithm], target_sub[target]) prediction = ' '.join([str(x) for x in prediction]) print(prediction) self.resultLineEdit.setText(prediction) # 将结果存放在LineEdit中 self.board.load("result.png") self.update() def upload(self): filename = QFileDialog.getOpenFileName(None, 'open', ".") self.board.load(filename[0]) self.update() def clear(self): self.board.fill(Qt.white) self.update() self.is_empty = True self.resultLineEdit.setText("") def paintEvent(self, paintEvent): self.painter.begin(self) self.painter.drawPixmap(0, 0, self.board) self.painter.end() def mouseReleaseEvent(self, QMouseEvent): self.is_empty = False def mousePressEvent(self, QMouseEvent): self.current_pos = QMouseEvent.pos() self.last_pos = self.current_pos def mouseMoveEvent(self, QMouseEvent): self.current_pos = QMouseEvent.pos() self.painter.begin(self.board) self.painter.setPen(QPen(Qt.black, 6)) self.painter.drawLine(self.last_pos, self.current_pos) self.painter.end() self.last_pos = self.current_pos self.update()
class GuiRunner(QObject): '''Make sure an event loop is running before starting the main work of initialization''' def __init__(self, opts, args, actions, listener, app, gui_debug=None): self.startup_time = time.time() self.opts, self.args, self.listener, self.app = opts, args, listener, app self.gui_debug = gui_debug self.actions = actions self.main = None QObject.__init__(self) self.splash_screen = None self.timer = QTimer.singleShot(1, self.initialize) if DEBUG: prints('Starting up...') def start_gui(self, db): from calibre.gui2.ui import Main main = self.main = Main(self.opts, gui_debug=self.gui_debug) if self.splash_screen is not None: self.splash_screen.showMessage(_('Initializing user interface...')) with gprefs: # Only write gui.json after initialization is complete main.initialize(self.library_path, db, self.listener, self.actions) if self.splash_screen is not None: self.splash_screen.finish(main) if DEBUG: prints('Started up in %.2f seconds'%(time.time() - self.startup_time), 'with', len(db.data), 'books') add_filesystem_book = partial(main.iactions['Add Books'].add_filesystem_book, allow_device=False) sys.excepthook = main.unhandled_exception if len(self.args) > 1: files = [os.path.abspath(p) for p in self.args[1:] if not os.path.isdir(p)] if len(files) < len(sys.argv[1:]): prints('Ignoring directories passed as command line arguments') if files: add_filesystem_book(files) for event in self.app.file_event_hook.events: add_filesystem_book(event) self.app.file_event_hook = add_filesystem_book def initialization_failed(self): print 'Catastrophic failure initializing GUI, bailing out...' QCoreApplication.exit(1) raise SystemExit(1) def initialize_db_stage2(self, db, tb): from calibre.db.legacy import LibraryDatabase if db is None and tb is not None: # DB Repair failed error_dialog(self.splash_screen, _('Repairing failed'), _('The database repair failed. Starting with ' 'a new empty library.'), det_msg=tb, show=True) if db is None: candidate = choose_dir(self.splash_screen, 'choose calibre library', _('Choose a location for your new calibre e-book library'), default_dir=get_default_library_path()) if not candidate: self.initialization_failed() try: self.library_path = candidate db = LibraryDatabase(candidate) except: error_dialog(self.splash_screen, _('Bad database location'), _('Bad database location %r. calibre will now quit.' )%self.library_path, det_msg=traceback.format_exc(), show=True) self.initialization_failed() try: self.start_gui(db) except Exception: error_dialog(self.main, _('Startup error'), _('There was an error during {0} startup.' ' Parts of {0} may not function. Click Show details to learn more.').format(__appname__), det_msg=traceback.format_exc(), show=True) def initialize_db(self): from calibre.db.legacy import LibraryDatabase db = None try: db = LibraryDatabase(self.library_path) except apsw.Error: repair = question_dialog(self.splash_screen, _('Corrupted database'), _('The library database at %s appears to be corrupted. Do ' 'you want calibre to try and rebuild it automatically? ' 'The rebuild may not be completely successful. ' 'If you say No, a new empty calibre library will be created.') % force_unicode(self.library_path, filesystem_encoding), det_msg=traceback.format_exc() ) if repair: if repair_library(self.library_path): db = LibraryDatabase(self.library_path) except: error_dialog(self.splash_screen, _('Bad database location'), _('Bad database location %r. Will start with ' ' a new, empty calibre library')%self.library_path, det_msg=traceback.format_exc(), show=True) self.initialize_db_stage2(db, None) def show_splash_screen(self): self.splash_pixmap = QPixmap() self.splash_pixmap.load(I('library.png')) self.splash_screen = QSplashScreen(self.splash_pixmap) self.splash_screen.showMessage(_('Starting %s: Loading books...') % __appname__) self.splash_screen.show() QApplication.instance().processEvents() def initialize(self, *args): if gprefs['show_splash_screen']: self.show_splash_screen() self.library_path = get_library_path(parent=self.splash_screen) if not self.library_path: self.initialization_failed() self.initialize_db()
def _fetch_marvin_cover(border_width=0): ''' Retrieve LargeCoverJpg from cache ''' #self._log_location('border_width: {0}'.format(border_width)) con = sqlite3.connect(self.marvin_db_path) with con: con.row_factory = sqlite3.Row # Fetch Hash from mainDb cover_cur = con.cursor() cover_cur.execute('''SELECT Hash FROM Books WHERE ID = '{0}' '''.format(self.book_id)) row = cover_cur.fetchone() book_hash = row[b'Hash'] large_covers_subpath = self.connected_device._cover_subpath(size="large") cover_path = '/'.join([large_covers_subpath, '%s.jpg' % book_hash]) stats = self.parent.ios.exists(cover_path) if stats: self._log("fetching large cover from cache") #self._log("cover size: {:,} bytes".format(int(stats['st_size']))) cover_bytes = self.parent.ios.read(cover_path, mode='rb') m_image = QImage() m_image.loadFromData(cover_bytes) if border_width: # Construct a QPixmap with oversized yellow background m_image = m_image.scaledToHeight( self.COVER_ICON_SIZE - border_width * 2, Qt.SmoothTransformation) self.m_pixmap = QPixmap( QSize(m_image.width() + border_width * 2, m_image.height() + border_width * 2)) m_painter = QPainter(self.m_pixmap) m_painter.setRenderHints(m_painter.Antialiasing) m_painter.fillRect(self.m_pixmap.rect(), self.MISMATCH_COLOR) m_painter.drawImage(border_width, border_width, m_image) else: m_image = m_image.scaledToHeight( self.COVER_ICON_SIZE, Qt.SmoothTransformation) self.m_pixmap = QPixmap( QSize(m_image.width(), m_image.height())) m_painter = QPainter(self.m_pixmap) m_painter.setRenderHints(m_painter.Antialiasing) m_painter.drawImage(0, 0, m_image) self.marvin_cover.setPixmap(self.m_pixmap) else: # No cover available, use generic self._log("No cached cover, using generic") pixmap = QPixmap() pixmap.load(I('book.png')) pixmap = pixmap.scaled(self.COVER_ICON_SIZE, self.COVER_ICON_SIZE, aspectRatioMode=Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) self.marvin_cover.setPixmap(pixmap)
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.bright_value = str() self.correct_scale = str() self.path_2_image = str() self.is_eyes = str() self.is_eyeglasses = str() self.is_open = str() self.blured = str() self.blur_value = int() self.brightness_value = int() self.pixmap = QPixmap() self.pixmap_token = QPixmap() self.pixmap_logo = QPixmap() self.brightFlag = bool self.blurFlag = bool self.eyesFlag = bool self.eyes_openedFlag = bool self.scaleFlag = bool uic.loadUi('window.ui', self) self.pushButton.clicked.connect(self.browse_image) self.pushButton_2.clicked.connect(self.start_second_window) def start_second_window(self): self.open_second_window(self.path_2_image) def browse_image(self): self.textBrowser.clear() self.path_2_image = QFileDialog.getOpenFileName( self, 'Open File', './photo')[0] self.open_image_func() def open_second_window(self, path): show_info(path, self.blur_value, self.brightness_value) def open_image_func(self): self.open_image() def open_image(self): self.img = cv2.imread(self.path_2_image) frame = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) self.load_image() self.start(frame) def load_image(self): self.pixmap.load(self.path_2_image) pixmap = self.pixmap.scaled(461, 671) self.label.setPixmap(pixmap) def start(self, frame): flag, faces = face_detection(frame) self.eyeglasses_status(flag, faces, frame) self.is_blured() self.is_right_scale() self.is_bright() self.append_result() def eyeglasses_status(self, flag, faces, frame): if flag: self.eyesFlag = is_eye_exist(faces, frame) if self.eyesFlag: self.is_eyeglasses = '<font color="green">Нет</font>' self.is_eyes = '<font color="green">Видны</font>' self.close_open_eyes() else: self.is_eyeglasses = '<font color="green">Есть</font>' self.is_eyes = '<font color="red">Не видны</font>' self.is_open = '<font color="red">Не удалось определить</font>' def close_open_eyes(self): self.eyes_openedFlag = is_eyes_opened(self.img) if self.eyes_openedFlag: self.is_open = '<font color="green">Окрыты</font>' else: self.is_open = '<font color="red">Закрыты</font>' def is_blured(self): self.blurFlag, self.blur_value = is_blured(self.img) if self.blurFlag: self.blured = '<font color="red">Не соответствует</font>' else: self.blured = '<font color="green">Соответствует</font>' def is_right_scale(self): self.scaleFlag = is_ratio_correct(self.img) if self.scaleFlag: self.correct_scale = '<font color="green">Соответствует</font>' else: self.correct_scale = '<font color="red">Не соответсвует</font>' def is_bright(self): bright, light = is_too_bright(self.img) notbright, dark = is_not_bright(self.img) if bright: self.bright_value = '<font color="red">Избыток</font>' self.brightness_value = light self.brightFlag = False elif notbright: self.bright_value = '<font color="red">Недостаточно</font>' self.brightness_value = dark self.brightFlag = False else: self.bright_value = '<font color="green">Достаточно</font>' self.brightness_value = light self.brightFlag = True def access_token(self): green_token = './labels/green_gal.png' red_token = './labels/red_cross.png' if self.brightFlag and not self.blurFlag and self.eyesFlag and self.eyes_openedFlag and self.scaleFlag: self.pixmap_token.load(green_token) self.pixmap_token.scaled(191, 151) self.label_4.setPixmap(self.pixmap_token) else: self.pixmap_token.load(red_token) self.pixmap_token.scaled(191, 151) self.label_4.setPixmap(self.pixmap_token) def load_logo(self): self.pixmap_logo.load('./labels/unnamed.png') self.MyDocuments.setPixmap(self.pixmap_logo) def append_result(self): self.textBrowser.append( f'<h1>Наличие очков: {self.is_eyeglasses}</h1>' f'<h1>Глаза: {self.is_eyes}</h1>' f'<h1>Сотояние глаз: {self.is_open}' f'<h1>Фон: {self.blured}</h1>' f'<h1>Соотношение лица относительно фона: {self.correct_scale}</h1>' f'<h1>Свет в изображении: {self.bright_value}</h1>') self.access_token()
class ImagePopup(object): def __init__(self, parent): self.current_img = QPixmap() self.current_url = QUrl() self.parent = parent self.dialogs = [] def __call__(self): if self.current_img.isNull(): return d = ImageView(self.parent, self.current_img, self.current_url) self.dialogs.append(d) d.finished.connect(self.cleanup, type=Qt.QueuedConnection) d() def cleanup(self): for d in tuple(self.dialogs): if not d.isVisible(): self.dialogs.remove(d) if __name__ == '__main__': import sys app = QApplication([]) p = QPixmap() p.load(sys.argv[-1]) u = QUrl.fromLocalFile(sys.argv[-1]) d = ImageView(None, p, u) d() app.exec_()
class PaintBoard(QWidget): def __init__(self): QWidget.__init__(self) # self.label = QLabel(self) # self.gridLayout = QGridLayout(self) # self.gridLayout.addWidget(self.label) self.pixmap = QPixmap(1,1) self.pixmap.fill(Qt.white) self.img = QImage(self.pixmap.toImage()) # self.label.setFrameShape(1) # # self.label.setPixmap(self.pixmap) # self.label.setScaledContents(True) # self.label.setVisible(False) self.pen = QPainter() def paintEvent(self, paintEvent): self.pixmap = self.pixmap.scaled(self.width(), self.height()) self.pen.begin(self) # self.pen.drawPixmap(0, 0, self.pixmap) self.img = QImage(self.pixmap.toImage()) self.pen.drawImage(0, 0, self.img) self.pen.end() def drawPoints(self, x, y): # print(self.width(),self.height()) m = int(self.width()/2) + x n = int(self.height()/2) - y self.pen.begin(self.pixmap) self.pen.setPen(QPen(Qt.black,1)) self.pen.drawPoint(m, n) self.pen.end() self.update() # self.repaint() def load_img(self, img): self.pixmap.load(img) self.update() #DDA def drawLine(self, x0, y0, x1, y1): self.Clear() dx = x1 - x0 dy = y1 - y0 if fabs(dx) > fabs(dy): steps = fabs(dx) else: steps = fabs(dy) self.drawPoints(int(x0+0.5), int(y0+0.5)) xInc = dx/steps yInc = dy/steps for i in range(int(steps+0.5)): x0 += xInc y0 += yInc self.drawPoints(int(x0+0.5), int(y0+0.5)) #中点法画圆 def CirclePlot(self, xc, yc, x, y): self.drawPoints(x+xc, y+yc) self.drawPoints(-x+xc, y+yc) self.drawPoints(x+xc, -y+yc) self.drawPoints(-x+xc, -y+yc) self.drawPoints(y+xc, x+yc) self.drawPoints(y+xc, -x+yc) self.drawPoints(-y+xc, x+yc) self.drawPoints(-y+xc, -x+yc) def drawRound(self, xc, yc, r): self.Clear() x = 0 y = r d = 3-2*r self.CirclePlot(xc, yc, x, y) while x<y: if d<0: d = d+4*x+6 else: d = d+4*(x-y)+10 y -= 1 x +=1 self.CirclePlot(xc, yc, x, y) ''' # 边界填充 def fill(self, x, y): w = int(self.width()/2) h = int(self.height()/2) block = deque([(x, y)]) while 1: if len(block) == 0: break else: # print(block) point = block.popleft() m = point[0] n = point[1] # c = self.img.pixel(w+m, h+n) # colors = QColor(c).getRgb() # if colors != (0, 0, 0, 255): self.drawPoints(m, n) # result.append((m,n)) c = self.img.pixel(w+m, h+n-1) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m,n-1) not in block: block.append((m,n-1)) c = self.img.pixel(w+m, h+n+1) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m,n+1) not in block: block.append((m,n+1)) c = self.img.pixel(w+m-1, h+n) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m-1,n) not in block: block.append((m-1,n)) c = self.img.pixel(w+m+1, h+n) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m+1,n) not in block: block.append((m+1,n)) print(results) ''' #边界填充 #种子边界填充 def fill(self, x, y): w = int(self.width()/2) h = int(self.height()/2) block = deque([(x, y)]) results = [] while 1: if len(block) == 0: break else: point = block.popleft() m = point[0] n = point[1] results.append((m,n)) c = self.img.pixel(w+m, h+n-1) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m,n-1) not in block: if (m,n-1) not in results: block.append((m,n-1)) c = self.img.pixel(w+m, h+n+1) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m,n+1) not in block: if (m,n+1) not in results: block.append((m,n+1)) c = self.img.pixel(w+m-1, h+n) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m-1,n) not in block: if (m-1,n) not in results: block.append((m-1,n)) c = self.img.pixel(w+m+1, h+n) colors = QColor(c).getRgb() if colors != (0, 0, 0, 255): if (m+1,n) not in block: if (m+1,n) not in results: block.append((m+1,n)) for point in results: self.drawPoints(point[0], point[1]) def Clear(self): self.pixmap.fill(Qt.white) self.update()