def update_item_info(self, name, data): merged = {} defaults = self.assets.items().get_item(name) if defaults is not None: merged.update(defaults[0]) merged.update(data) item_info = "<html><body>" item_info += generate_item_info(merged) item_info += "</body></html>" self.ui.desc.setText(item_info) inv_icon = self.assets.items().get_item_icon(name) image = self.assets.items().get_item_image(name) if inv_icon is not None: inv_icon = self.assets.images().color_image(inv_icon, data) icon = QPixmap.fromImage(ImageQt(inv_icon)) elif image is not None: image = self.assets.images().color_image(image, data) icon = QPixmap.fromImage(ImageQt(image)) else: logging.warning("Unable to load image for %s", name) icon = QPixmap.fromImage(QImage.fromData(self.assets.items().missing_icon())) icon = self.scale_image_icon(icon, 64, 64) self.ui.icon.setPixmap(icon)
def preview_icon(race, gender): """Return an icon image for player race/gender previews.""" assets_db_file = Config().read("assets_db") starbound_folder = Config().read("starbound_folder") db = assets.Assets(assets_db_file, starbound_folder) icon_file = db.species().get_preview_image(race, gender) if icon_file is None: return QPixmap.fromImage(QImage.fromData(db.missing_icon())).scaledToHeight(48) else: return QPixmap.fromImage(QImage.fromData(icon_file)).scaledToHeight(48)
def update_item_view(self): """Update item details view with data from currently selected item.""" try: selected = self.ui.items.selectedItems()[0].name except IndexError: return try: item = self.items.get_item(selected) except TypeError: logging.warning("Unable to load asset "+selected) return image_file = self.items.get_item_image(selected) if image_file == None: inv_icon_file = self.items.get_item_icon(selected) if inv_icon_file != None: icon = QPixmap.fromImage(ImageQt(inv_icon_file)).scaled(32, 32) else: icon = QPixmap.fromImage(QImage.fromData(self.items.missing_icon())).scaled(32, 32) else: icon = QPixmap.fromImage(ImageQt(image_file)).scaledToHeight(64) # last ditch try: self.ui.item_icon.setPixmap(icon) except TypeError: logging.warning("Unable to load item image: "+selected) self.ui.item_icon.setPixmap(QPixmap()) # TODO: update qt objectnames, already not making sense try: self.ui.item_name.setText(item[0]["shortdescription"]) except KeyError: self.ui.item_name.setText("Missing short description") try: self.ui.short_desc.setText(item[0]["description"]) except KeyError: self.ui.short_desc.setText("Missing description") # populate default variant table row = 0 self.ui.info.setRowCount(len(item[0])) for key in sorted(item[0].keys()): try: text = str(key) + ": " + str(item[0][key]) table_item = QTableWidgetItem(text) table_item.setToolTip(text) self.ui.info.setItem(row, 0, table_item) except TypeError: pass row += 1 self.item_browse_select = selected
def initCommLayerUI(self): self.imgKinectAvailable=QImage("./image/kinect_available.png") self.imgKinectDisable=QImage("./image/kinect_disable.png") self.imgRobotAvailable=QImage("./image/robot_available.png") self.imgRobotDisable=QImage("./image/robot_disable.png") self.imgMain=QImage("./image/microbot_long.png") self.commKinectLabel=QLabel() self.commMainLabel=QLabel() self.commRobotLabel=QLabel() self.commKinectLabel.setPixmap(QPixmap.fromImage(self.imgKinectAvailable)) self.commMainLabel.setPixmap(QPixmap.fromImage(self.imgMain)) self.commRobotLabel.setPixmap(QPixmap.fromImage(self.imgRobotDisable)) #K Kinect #M Main #R Robot #self.commKMLabel=QLabel() #self.commMRLabel=QLabel() #self.imgConnected=QImage("./image/connected.png") #self.imgDisconnected=QImage("./image/disconnected.png") #self.commKMLabel.setPixmap(QPixmap.fromImage(self.imgDisconnected)) #self.commMRLabel.setPixmap(QPixmap.fromImage(self.imgDisconnected)) self.pmConnected=QPixmap("./image/connected.png") self.pmDisconnected=QPixmap("./image/disconnected.png") self.iconConnected=QIcon(self.pmConnected) self.iconDisconnected=QIcon(self.pmDisconnected) self.commKMButton=QPushButton() self.commMRButton=QPushButton() self.commKMButton.setIcon(self.iconDisconnected) self.commMRButton.setIcon(self.iconDisconnected) self.commKMButton.setIconSize(self.pmDisconnected.rect().size()) self.commMRButton.setIconSize(self.pmDisconnected.rect().size()) self.commKMButton.setDisabled(True) self.commMRButton.setDisabled(True) self.commLayerLayout=QHBoxLayout() self.commLayerLayout.addWidget(self.commKinectLabel) #self.commLayerLayout.addWidget(self.commKMLabel) self.commLayerLayout.addWidget(self.commKMButton) self.commLayerLayout.addWidget(self.commMainLabel) #self.commLayerLayout.addWidget(self.commMRLabel) self.commLayerLayout.addWidget(self.commMRButton) self.commLayerLayout.addWidget(self.commRobotLabel) self.commLayerLayout.setAlignment(Qt.AlignCenter) self.commLayerWidget=QWidget() self.commLayerWidget.setLayout(self.commLayerLayout) self.MRConnected=False self.KMConnected=False self.commMRButton.clicked.connect(self.MRButtonClick) self.commKMButton.clicked.connect(self.KMButtonClick)
def update_item_view(self): """Update item details view with data from currently selected item.""" try: selected = self.ui.items.selectedItems()[0].name except IndexError: return try: item = self.items.get_item(selected) except TypeError: logging.warning("Unable to load asset "+selected) return inv_icon_file = self.items.get_item_icon(selected) if inv_icon_file is not None: icon = QPixmap.fromImage(ImageQt(inv_icon_file)) else: image_file = self.items.get_item_image(selected) if image_file is not None: icon = QPixmap.fromImage(ImageQt(image_file)) else: icon = QPixmap.fromImage(QImage.fromData(self.assets.items().missing_icon())) # last ditch try: icon = self.scale_image_icon(icon, 64, 64) self.ui.item_icon.setPixmap(icon) except TypeError: logging.warning("Unable to load item image: "+selected) self.ui.item_icon.setPixmap(QPixmap()) self.ui.short_desc.setText(generate_item_info(item[0])) # populate default variant table try: row = 0 self.ui.info.setRowCount(len(item[0])) for key in sorted(item[0].keys()): text = str(key) + ": " + str(item[0][key]) table_item = QTableWidgetItem(text) table_item.setToolTip(text) self.ui.info.setItem(row, 0, table_item) row += 1 except TypeError: self.ui.info.setRowCount(0) logging.error("No item data") self.item_browse_select = selected
def write_appearance_values(self): hair = self.ui.hair_group.currentText(), self.ui.hair_type.currentText() facial_hair = (self.ui.facial_hair_group.currentText(), self.ui.facial_hair_type.currentText()) facial_mask = (self.ui.facial_mask_group.currentText(), self.ui.facial_mask_type.currentText()) personality = self.ui.personality.currentText() self.player.set_hair(*hair) self.player.set_facial_hair(*facial_hair) self.player.set_facial_mask(*facial_mask) self.player.set_personality(personality) self.player.set_body_directives(pack_color_directives(self.colors["body"])) self.player.set_hair_directives(pack_color_directives(self.colors["hair"])) self.player.set_facial_hair_directives(pack_color_directives(self.colors["facial_hair"])) self.player.set_facial_mask_directives(pack_color_directives(self.colors["facial_mask"])) # render player preview try: image = self.assets.species().render_player(self.player) pixmap = QPixmap.fromImage(ImageQt(image)) except (OSError, TypeError, AttributeError): logging.exception("Couldn't load species images") pixmap = QPixmap() self.ui.player_preview.setPixmap(pixmap) self.main_window.window.setWindowModified(True)
def append_items(self, item_data_list): for data in item_data_list: pathname = data["pathname"] path,name = os.path.split(pathname) character = "" if "character" in data: character = data["character"] count = self.table.rowCount() self.table.insertRow(count) # thumbnail img = QImage() img.load(pathname) thumbnail_item = QTableWidgetItem() thumbnail_item.setTextAlignment(Qt.AlignCenter); thumbnail_item.setData(Qt.DecorationRole, QPixmap.fromImage(img)); self.table.setItem(count, 0, thumbnail_item) # name name_item = QTableWidgetItem(name) name_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.table.setItem(count, 1, name_item) # character self.table.setItem(count, 2, QTableWidgetItem(character)) self.image_config.append({ "image":pathname, "character":character, }) self.table.resizeColumnToContents(0)
def populate(self): total = 0 self.ui.player_list.clear() names = [] for uuid in self.players.keys(): try: names.append((uuid, self.players[uuid]["player"].get_name())) except TypeError: logging.exception("Could not read %s", uuid) for name in sorted(names, key=lambda x: x[1]): player = self.players[name[0]]["player"] preview = self.players[name[0]]["preview"] pixmap = QPixmap.fromImage(ImageQt(preview)) played = datetime.timedelta(seconds=int(player.get_play_time())) list_item = PlayerWidget("%s [%s]" % (name[1], played), name[0]) list_item.setIcon(QtGui.QIcon(pixmap)) self.ui.player_list.addItem(list_item) total += 1 self.ui.total_label.setText(str(total) + " total") self.ui.player_list.setCurrentRow(0)
def pixmap(name, size, mode, state): """Returns a (possibly cached) pixmap of the name and size with the default text color. The state argument is ignored for now. """ if mode == QIcon.Selected: color = QApplication.palette().highlightedText().color() else: color = QApplication.palette().text().color() key = (name, size.width(), size.height(), color.rgb(), mode) try: return _pixmaps[key] except KeyError: i = QImage(size, QImage.Format_ARGB32_Premultiplied) i.fill(0) painter = QPainter(i) # render SVG symbol QSvgRenderer(os.path.join(__path__[0], name + ".svg")).render(painter) # recolor to text color painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(i.rect(), color) painter.end() # let style alter the drawing based on mode, and create QPixmap pixmap = QApplication.style().generatedIconPixmap(mode, QPixmap.fromImage(i), QStyleOption()) _pixmaps[key] = pixmap return pixmap
def draw_fft(self): """ This method is slow. But, computers are fast. """ #start = time.clock() if self.btn_receiving_audio.text() != "": self.btn_receiving_audio.setText("FFT Data Streaming") fft_data = self.mixer.audio.fft[0] self.fft_max.append(max(fft_data)) if len(self.fft_max) > 64: self.fft_max.pop(0) max_val = max(self.fft_max) width = 256 height = 64 if self.fft_pixmap is None: self.fft_pixmap = np.full([height, width * 4], 0, dtype=np.uint8) for row in range(height - 1): self.fft_pixmap[row] = self.fft_pixmap[row + 1] if max_val > 0: for x in range(0, width * 4, 4): f = np.interp(old_div(x, 4), np.arange(len(fft_data)), fft_data)# / max_val #f = math.sqrt(math.sqrt(f)) self.fft_pixmap[height - 1][x:x + 4] = \ (hsv_float_to_rgb_uint8((old_div(x, (4.0 * width)), 1.0, f)) + (255,)) pm = self.fft_pixmap.flatten() img = QImage(pm, width, height, QImage.Format_ARGB32) self.fft_graphics_view.setPixmap(QPixmap.fromImage(img))
def display_photo(self): if not self.housing.photos: self.ui.photosFrame.hide() return if self.displayed_photo_idx >= len(self.housing.photos): self.displayed_photo_idx = len(self.housing.photos) - 1 if self.displayed_photo_idx < 0: self.ui.photosFrame.hide() return self.ui.photosFrame.show() photo = self.housing.photos[self.displayed_photo_idx] if photo.data: data = photo.data if photo.id in self.process_photo: self.process_photo.pop(photo.id) else: self.process_photo[photo.id] = QtDo(self.weboob, lambda p: self.display_photo()) self.process_photo[photo.id].do('fillobj', photo, ['data'], backends=self.housing.backend) return img = QImage.fromData(data) img = img.scaledToWidth(self.width()/3) self.ui.photoLabel.setPixmap(QPixmap.fromImage(img)) if photo.url is not NotLoaded: text = '<a href="%s">%s</a>' % (photo.url, photo.url) self.ui.photoUrlLabel.setText(text)
def display_photo(self): if self.displayed_photo_idx >= len(self.contact.photos) or self.displayed_photo_idx < 0: self.displayed_photo_idx = len(self.contact.photos) - 1 if self.displayed_photo_idx < 0: self.ui.photoUrlLabel.setText('') return photo = self.contact.photos.values()[self.displayed_photo_idx] if photo.data: data = photo.data if photo.id in self.process_photo: self.process_photo.pop(photo.id) else: self.process_photo[photo.id] = QtDo(self.weboob, lambda p: self.display_photo()) self.process_photo[photo.id].do('fillobj', photo, ['data'], backends=self.contact.backend) if photo.thumbnail_data: data = photo.thumbnail_data else: return img = QImage.fromData(data) img = img.scaledToWidth(self.width()/3) self.ui.photoLabel.setPixmap(QPixmap.fromImage(img)) if photo.url is not NotLoaded: text = '<a href="%s">%s</a>' % (photo.url, photo.url) if photo.hidden: text += '<br /><font color=#ff0000><i>(Hidden photo)</i></font>' self.ui.photoUrlLabel.setText(text)
def saveChanges(self): reply = QMessageBox.question(self, 'Message', 'Are you sure you save?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: image = self.imageHolder.saveChanges() format = 'png' initialPath = QDir.currentPath() + "/untitled." + format fileName, _ = QFileDialog.getSaveFileName(self, "Save As", initialPath, "%s Files (*.%s);;All Files (*)" % (format.upper(), format)) if fileName: image.save(fileName) self.screenPixmap = QPixmap.fromImage(image) self.parent.screenshotHolder.setPixmap(QPixmap.fromImage(image).scaled( self.parent.screenshotHolder.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation )) self.close()
def show_image(self): print (self.image_path) self.Image = QImage() self.Image.load(self.image_path) if self.Image == None: print ("图像读取错误") sys.exit() else: from PIL import Image from PIL.ImageQt import ImageQt #img = Image.open(self.image_path) img = Image.open('/Users/chensiye/zhizi.jpg') w, h = img.size print (w,h) imgQ = ImageQt(img) pixMap = QPixmap.fromImage(imgQ) self.scene = QGraphicsScene() self.scene.addPixmap(pixMap) #self.scene.setSceneRect(0, 0, 1, 1) view = self.UI.graphicsView view.setScene(self.scene) view.setSceneRect(0,0,w,h) #view.resize(1000,1000) #print (view.size()) view.fitInView(QtCore.QRectF(0, 0, w, h), QtCore.Qt.KeepAspectRatio) """
def updateImage(self): if self.image_group == -1: return super(MWTrackerViewerSingle_GUI,self).readImage() self.img_h_ratio = self.frame_qimg.height()/self.image_height; self.img_w_ratio = self.frame_qimg.width()/self.image_width; #read the data of the particles that exists in the frame if isinstance(self.traj_time_grouped, pd.core.groupby.DataFrameGroupBy): try: self.frame_data = self.traj_time_grouped.get_group(self.frame_number) self.frame_data = self.frame_data[self.frame_data[self.worm_index_type] >= 0] except KeyError: self.frame_data = -1 #draw the boxes in each of the trajectories found if self.ui.checkBox_showLabel.isChecked(): self.drawROIBoxes(self.frame_qimg) #create the pixmap for the label pixmap = QPixmap.fromImage(self.frame_qimg) self.ui.imageCanvas.setPixmap(pixmap); self.updateROIcanvasN(1) self.updateROIcanvasN(2)
def createImage(self): """ Creates a new image by separating out the cyan, magenta, or yellow component, depending on the mask color specified in the constructor. The amount of the component found in each pixel of the image is used to determine how much of a user-selected ink is used for each pixel in the new image for the label widget. """ self.newImage = newImage = self.originalImage.copy() # Create CMY components for the ink being used. cyanInk = float(255 - QColor(self.paintColor).red()) / 255.0 magentaInk = float(255 - QColor(self.paintColor).green()) / 255.0 yellowInk = float(255 - QColor(self.paintColor).blue()) / 255.0 convert = self.convertMap[self.maskColor] for y in range(newImage.height()): for x in range(newImage.width()): p = self.originalImage.pixel(x, y) # Separate the source pixel into its cyan component. if self.inverted: amount = convert(p) else: amount = 255 - convert(p) newColor = QColor( 255 - min(int(amount * cyanInk), 255), 255 - min(int(amount * magentaInk), 255), 255 - min(int(amount * yellowInk), 255)) newImage.setPixel(x, y, newColor.rgb()) self.imageLabel.setPixmap(QPixmap.fromImage(newImage))
def gotThumbnail(self): if empty(self.person.thumbnail_url) and self.person.thumbnail_url != NotAvailable: self.backend.fill_person(self.person, ('thumbnail_url')) if not empty(self.person.thumbnail_url): data = urllib.urlopen(self.person.thumbnail_url).read() img = QImage.fromData(data) self.ui.imageLabel.setPixmap(QPixmap.fromImage(img).scaledToHeight(100,Qt.SmoothTransformation))
def from_document(self, document): """Load data from document """ # Load the new data # Document promises that either the thumbnail or scanned image will be # available if document.thumbnail.available: debug_print('Model will work on thumbnail') image_array = document.thumbnail.array else: debug_print('Model will work on full-res scan') image_array = document.scanned.array pixmap = QPixmap.fromImage(qimage_of_bgr(image_array)) if pixmap.isNull(): raise ValueError('Unable to create QPixmap') else: data = self._boxes_from_items( document.items, pixmap.width(), pixmap.height() ) # Inform views self.beginResetModel() self._data, self._image_array, self._pixmap = data, image_array, pixmap self.endResetModel()
def refresh_map(widget): """ Refresh map when map widget refresh event is set. This is asyncio coroutine. :param widget: Map widget. """ event = widget.refresh_map map = widget.map # use redis to cache map tiles client = redis.Redis('localhost') downloader = redis_downloader(client) render_map = functools.partial( geotiler.render_map_async, downloader=downloader ) while True: yield from event.wait() event.clear() logger.debug('fetching map image...') img = yield from render_map(map) logger.debug('got map image') pixmap = QPixmap.fromImage(ImageQt(img)) widget.map_layer.setPixmap(pixmap) scroll_map(widget, map.center)
def newImage(self, img): # Resize the incoming camera image to fit the display window if self.location == 'front': self.cur_img = img.scaled( self.shape[0], self.shape[1] ).mirrored(horizontal=True, vertical=True) else: self.cur_img = img.scaled( self.shape[0], self.shape[1] ) """ # save movie frame #self.pipe.communicate(input=img.bits()) if self.video_out == None or ((self.img_cnt % self.IMG_SAVE_MOD_CONST) == 0): if self.video_out != None: print 'Writing video to disk' self.video_out.release() avi_file = self.experiment_dir + '/' + datetime.now().strftime(self.FORMAT) + '_side_cam.avi' fourcc = cv2.cv.CV_FOURCC(*'XVID') self.video_out = cv2.VideoWriter(avi_file,fourcc, 20.0, (img.height(),img.width())) np_img = qimage2numpy( img ) # print 'np_img.shape', np_img.shape self.video_out.write( np_img ) self.img_cnt = self.img_cnt + 1 """ # Show image self.imageLabel.setPixmap(QPixmap.fromImage(self.cur_img))
def show_image(self): image_path = (r'/Users/chensiye/zhizi.jpg') self.Image = QImage() self.Image.load(image_path) self.resize(800,600) height = self.size().height() width = self.size().width() pixmap = QPixmap.fromImage(self.Image.scaledToHeight(height)) #hbox = QHBoxLayout(self) lbl = QLabel(self) lbl.setPixmap(pixmap) #hbox.addWidget(lbl) #self.setLayout(hbox) pix_x = pixmap.size().width() pix_y = pixmap.size().height() x = int((width - pix_x)/2) screenRect = desktop.screenGeometry(desktop.primaryScreen()) print (type (self.size())) print (self.size()) print (pixmap.size()) print (lbl.size()) print (self.frameGeometry()) lbl.move(x,0) self.move(0,0)
def __init__(self, text): QLabel.__init__(self) self.text = text self.layout = QVBoxLayout(self) self.image_label = QLabel() image = QImage('file_icon.png') self.image_label.setPixmap(QPixmap.fromImage(image)) self.image_label.setAlignment(Qt.AlignCenter) # Truncate the filename if it is too long (but its fullname and path are saved in an instance variable) last_path_seperator_index = text.rfind('/') text = text[last_path_seperator_index+1:] if len(text) > 12: text = text[0:12] + '...' self.text_label = QLabel(text) self.text_label.setWordWrap(True) self.text_label.setAlignment(Qt.AlignCenter) self.layout.addWidget(self.image_label) self.layout.addWidget(self.text_label) self.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
def go(): global graphic_view, status_label data_parent, data_child = Pipe(duplex=False) receiver = Process(target=generate_data, args=(data_child,)) receiver.daemon = True receiver.start() scene = QGraphicsScene() graphic_view.setScene(scene) scene.setSceneRect(0, 0, 1024, 1024) x_pos = 0 y_pos = 0 t = time.time() while True: speed = time.time() data = data_parent.recv() spectrogram = Spectrogram(data) pixmap = QPixmap.fromImage(spectrogram.create_spectrogram_image(transpose=True)) scene.setSceneRect(scene.sceneRect().adjusted(0, 0, 0, pixmap.height())) item = scene.addPixmap(pixmap) item.setPos(x_pos, y_pos) y_pos += pixmap.height() graphic_view.fitInView(scene.sceneRect()) status_label.setText("Height: {0:.0f} // Speed: {1:.2f} // Total Time: {2:.2f}".format(scene.sceneRect().height(), 1/(time.time()-speed), time.time()-t)) QApplication.instance().processEvents()
def createEditor(self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex): editor = QComboBox(parent) if sys.platform == "win32": # Ensure text entries are visible with windows combo boxes editor.setMinimumHeight(self.sizeHint(option, index).height() + 10) editor.addItems(self.items) if self.is_editable: editor.setEditable(True) editor.setInsertPolicy(QComboBox.NoInsert) if self.current_edit_text: editor.setEditText(self.current_edit_text) if self.colors: img = QImage(16, 16, QImage.Format_RGB32) painter = QPainter(img) painter.fillRect(img.rect(), Qt.black) rect = img.rect().adjusted(1, 1, -1, -1) for i, item in enumerate(self.items): color = self.colors[i] painter.fillRect(rect, QColor(color.red(), color.green(), color.blue(), 255)) editor.setItemData(i, QPixmap.fromImage(img), Qt.DecorationRole) del painter editor.currentIndexChanged.connect(self.currentIndexChanged) editor.editTextChanged.connect(self.on_edit_text_changed) return editor
def changeIcon(self): icon = QIcon() for row in range(self.imagesTable.rowCount()): item0 = self.imagesTable.item(row, 0) item1 = self.imagesTable.item(row, 1) item2 = self.imagesTable.item(row, 2) if item0.checkState() == Qt.Checked: if item1.text() == "Normal": mode = QIcon.Normal elif item1.text() == "Active": mode = QIcon.Active elif item1.text() == "Disabled": mode = QIcon.Disabled else: mode = QIcon.Selected if item2.text() == "On": state = QIcon.On else: state = QIcon.Off fileName = item0.data(Qt.UserRole) image = QImage(fileName) if not image.isNull(): icon.addPixmap(QPixmap.fromImage(image), mode, state) self.previewArea.setIcon(icon)
def imgInit(self): self.cv_img = cv2.imread(os.path.join(sampleDataPath,"color_filter_test.png")) self.frameBuffer = Queue() self.frameBufferItemGroup = QGraphicsItemGroup() self.frameBufferItemGroup.hide() self.inputPixmapRenderScene = QGraphicsScene() self.inputPixmapRenderScene.addItem(self.frameBufferItemGroup) self.inputScene = QGraphicsScene() self.inputGraphicsView.setScene(self.inputScene) self.inputGraphicsView.resizeEvent = self.graphicsViewResized # self.inputScene.addItem(self.frameBufferItemGroup) qimg = misc.cvMatToQImage(self.cv_img) self.inputPixmap = QPixmap.fromImage(qimg) self.inputPixmapItem = QGraphicsPixmapItem(self.inputPixmap) self.inputScene.addItem(self.inputPixmapItem) self.rubberBand = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self.inputGraphicsView) self.inputGraphicsView.mousePressEvent = self.inputGraphicsViewMousePressEvent self.inputGraphicsView.mouseMoveEvent = self.inputGraphicsViewMouseMoveEvent self.inputGraphicsView.mouseReleaseEvent = self.inputGraphicsViewMouseReleaseEvent self.inputGraphicsView.viewport().installEventFilter(self) self.inputGraphicsView.setMouseTracking(True) self.overlayScene = QGraphicsScene() self.inputGraphicsView.setOverlayScene(self.overlayScene) self.zoomedGraphicsView.setScene(self.inputScene) self.zoomedGraphicsView.setOverlayScene(self.overlayScene)
def initUI(self): row = col = 0 t=0 for pic in self.fslides: label = ImageLabel("") height, width, bytesPerComponent = pic[0].shape bytesPerLine = 3 * width cv.cvtColor(pic[0], cv.COLOR_BGR2RGB, pic[0]) QImg = QImage(pic[0].data, width, height, bytesPerLine,QImage.Format_RGB888) pixmap = QPixmap.fromImage(QImg) label.setPixmap(pixmap) label.move(25+t,25+row) self.layout().addWidget(label) label1 = QLabel('Слайд номер #'+str(pic[1]),self) label1.move(200+t,410+row) t +=425 col +=1 if col % 2 == 0: row = 325 t = 0 self.setGeometry(300, 300, 900, 800) self.setWindowTitle('DiplomProject')
def save_screenshot(self, x, y, width, height): pixmap = QPixmap.fromImage(self.grabWindow()) pixmap = pixmap.copy(x, y, width, height) pixmap.save(self.settings.tmpSaveFile) self.hide() self.context.saveScreenshot(pixmap)
def mouseMoveEvent(self, event): if QLineF(QPointF(event.screenPos()), QPointF(event.buttonDownScreenPos(Qt.LeftButton))).length() < QApplication.startDragDistance(): return drag = QDrag(event.widget()) mime = QMimeData() drag.setMimeData(mime) ColorItem.n += 1 if ColorItem.n > 2 and qrand() % 3 == 0: image = QImage(':/images/head.png') mime.setImageData(image) drag.setPixmap(QPixmap.fromImage(image).scaled(30,40)) drag.setHotSpot(QPoint(15, 30)) else: mime.setColorData(self.color) mime.setText("#%02x%02x%02x" % (self.color.red(), self.color.green(), self.color.blue())) pixmap = QPixmap(34, 34) pixmap.fill(Qt.white) painter = QPainter(pixmap) painter.translate(15, 15) painter.setRenderHint(QPainter.Antialiasing) self.paint(painter, None, None) painter.end() pixmap.setMask(pixmap.createHeuristicMask()) drag.setPixmap(pixmap) drag.setHotSpot(QPoint(15, 20)) drag.exec_() self.setCursor(Qt.OpenHandCursor)
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 preview_mask(self): self.new_mask_image = self.create_mask(self.control_image, self.rendered_image, self.mask_image, self.overload_spin.value()) self.new_mask_label.setPixmap(QPixmap.fromImage(self.new_mask_image))
def rectangle(self, ev): try: self.draw.rectangle((ev.pos().x() - 30 - 31, ev.pos().y() - 30, ev.pos().x() + 30 - 31, ev.pos().y() + 30), fill = "black") except: pass self.label.setPixmap(QPixmap.fromImage(ImageQt(self.image)))
def add_new_page(self, templateUrl): # check for page list and or location. pagesList = [] if "pages" in self.setupDictionary.keys(): pagesList = self.setupDictionary["pages"] if not "pageNumber" in self.setupDictionary.keys(): self.setupDictionary['pageNumber'] = 0 if (str(self.setupDictionary["pagesLocation"]).isspace()): self.setupDictionary["pagesLocation"] = os.path.relpath( QFileDialog.getExistingDirectory( caption=i18n("Where should the pages go?"), options=QFileDialog.ShowDirsOnly), self.projecturl) # Search for the possible name. extraUnderscore = str() if str(self.setupDictionary["projectName"])[-1].isdigit(): extraUnderscore = "_" self.setupDictionary['pageNumber'] += 1 pageName = str(self.setupDictionary["projectName"]).replace( " ", "_") + extraUnderscore + str( format(self.setupDictionary['pageNumber'], "03d")) url = os.path.join(str(self.setupDictionary["pagesLocation"]), pageName + ".kra") # open the page by opening the template and resaving it, or just opening it. absoluteUrl = os.path.join(self.projecturl, url) if (os.path.exists(absoluteUrl)): newPage = Application.openDocument(absoluteUrl) else: booltemplateExists = os.path.exists( os.path.join(self.projecturl, templateUrl)) if booltemplateExists is False: templateUrl = os.path.relpath( QFileDialog.getOpenFileName( caption=i18n( "Which image should be the basis the new page?"), directory=self.projecturl, filter=str(i18n("Krita files") + "(*.kra)"))[0], self.projecturl) newPage = Application.openDocument( os.path.join(self.projecturl, templateUrl)) newPage.waitForDone() newPage.setFileName(absoluteUrl) newPage.setName(pageName.replace("_", " ")) newPage.save() newPage.waitForDone() # Get out the extra data for the standard item. newPageItem = QStandardItem() newPageItem.setIcon( QIcon(QPixmap.fromImage(newPage.thumbnail(256, 256)))) newPageItem.setDragEnabled(True) newPageItem.setDropEnabled(False) newPageItem.setEditable(False) newPageItem.setText(pageName.replace("_", " ")) newPageItem.setToolTip(url) # close page document. while os.path.exists(absoluteUrl) is False: qApp.processEvents() newPage.close() # add item to page. description = QStandardItem() description.setText(str("")) description.setEditable(False) listItem = [] listItem.append(newPageItem) listItem.append(description) self.pagesModel.appendRow(listItem) self.comicPageList.resizeRowsToContents() self.comicPageList.resizeColumnToContents(0)
def start_webcam(self): ## ----------------------------------------------------------------------------------------------------------------- ## Show Cam1 information on window frame = video_thread_cam1.frame frame = cv2.resize(frame, (1152, 631)) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image = QImage(frame, frame.shape[1], frame.shape[0], frame.shape[1] * 3, QImage.Format_RGB888) self.ui.frame1_frame.setPixmap(QPixmap.fromImage(image)) self.ui.frame1_when.setText(video_thread_cam1.result[5]) self.ui.frame1_where.setText(video_thread_cam1.result[3]) self.ui.frame1_who.setText(video_thread_cam1.result[0]) self.ui.frame1_what.setText(video_thread_cam1.result[1]) self.ui.frame1_hearing.setText(video_thread_cam1.result[4]) self.ui.frame1_todo.setText(video_thread_cam1.result[22].replace( "_", "\n")) ## Show cam2 information on window frame = video_thread_cam2.frame frame = cv2.resize(frame, (1152, 631)) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image = QImage(frame, frame.shape[1], frame.shape[0], frame.shape[1] * 3, QImage.Format_RGB888) self.ui.frame2_frame.setPixmap(QPixmap.fromImage(image)) self.ui.frame2_when.setText(video_thread_cam2.result[5]) self.ui.frame2_where.setText(video_thread_cam2.result[3]) self.ui.frame2_who.setText(video_thread_cam2.result[0]) self.ui.frame2_what.setText(video_thread_cam2.result[1]) self.ui.frame2_hearing.setText(video_thread_cam2.result[4]) self.ui.frame2_todo.setText(video_thread_cam1.result[22].replace( "_", "\n")) ## ----------------------------------------------------------------------------------------------------------------- # Show cam1 detail speaking information for i in range(len(video_thread_cam1.speaking_word)): for j in range(len(video_thread_cam1.speaking_word[i])): self.speaking_ui_cam1.tableWidget.setItem( i, j, QTableWidgetItem(video_thread_cam1.speaking_word[i][j])) ## Show cam2 detail speaking information for i in range(len(video_thread_cam2.speaking_word)): for j in range(len(video_thread_cam2.speaking_word[i])): self.speaking_ui_cam2.tableWidget.setItem( i, j, QTableWidgetItem(video_thread_cam2.speaking_word[i][j])) ## ----------------------------------------------------------------------------------------------------------------- ## Show nobody record of Quardo W info table_size, record = nobody_record.getdatae() self.ui.tableWidget.setRowCount(table_size[0] - 2) self.ui.tableWidget.setColumnCount(table_size[1]) self.ui.tableWidget.setHorizontalHeaderLabels( self.record_header_labels) for i, row in enumerate(record): if i == 0: continue for j, string in enumerate(record[i]): self.ui.tableWidget.setItem(i - 1, j, QTableWidgetItem(string)) self.ui.tableWidget.resizeColumnsToContents() self.ui.tableWidget.resizeRowsToContents() ## Show chung_chih record of Quardo W info table_size, record = chung_chih_record.getdatae() self.ui.tableWidget_2.setRowCount(table_size[0] - 2) self.ui.tableWidget_2.setColumnCount(table_size[1]) self.ui.tableWidget.setHorizontalHeaderLabels( self.record_header_labels) for i, row in enumerate(record): if i == 0: continue for j, string in enumerate(record[i]): self.ui.tableWidget_2.setItem(i - 1, j, QTableWidgetItem(string)) self.ui.tableWidget_2.resizeColumnsToContents() self.ui.tableWidget_2.resizeRowsToContents() ## Show yu_sung record of Quardo W info table_size, record = yu_sung_record.getdatae() self.ui.tableWidget_3.setRowCount(table_size[0] - 2) self.ui.tableWidget_3.setColumnCount(table_size[1]) self.ui.tableWidget.setHorizontalHeaderLabels( self.record_header_labels) for i, row in enumerate(record): if i == 0: continue for j, string in enumerate(record[i]): self.ui.tableWidget_3.setItem(i - 1, j, QTableWidgetItem(string)) self.ui.tableWidget_3.resizeColumnsToContents() self.ui.tableWidget_3.resizeRowsToContents() ## Show chang_yu record of Quardo W info table_size, record = chang_yu_record.getdatae() self.ui.tableWidget_4.setRowCount(table_size[0] - 2) self.ui.tableWidget_4.setColumnCount(table_size[1]) self.ui.tableWidget.setHorizontalHeaderLabels( self.record_header_labels) for i, row in enumerate(record): if i == 0: continue for j, string in enumerate(record[i]): self.ui.tableWidget_4.setItem(i - 1, j, QTableWidgetItem(string)) self.ui.tableWidget_4.resizeColumnsToContents() self.ui.tableWidget_4.resizeRowsToContents() ## Show i_hsin record of Quardo W info table_size, record = i_hsin_record.getdatae() self.ui.tableWidget_5.setRowCount(table_size[0] - 2) self.ui.tableWidget_5.setColumnCount(table_size[1]) self.ui.tableWidget.setHorizontalHeaderLabels( self.record_header_labels) for i, row in enumerate(record): if i == 0: continue for j, string in enumerate(record[i]): self.ui.tableWidget_5.setItem(i - 1, j, QTableWidgetItem(string)) self.ui.tableWidget_5.resizeColumnsToContents() self.ui.tableWidget_5.resizeRowsToContents() ## Show tzu_yuan record of Quardo W info table_size, record = tzu_yuan_record.getdatae() self.ui.tableWidget_6.setRowCount(table_size[0] - 2) self.ui.tableWidget_6.setColumnCount(table_size[1]) self.ui.tableWidget.setHorizontalHeaderLabels( self.record_header_labels) for i, row in enumerate(record): if i == 0: continue for j, string in enumerate(record[i]): self.ui.tableWidget_6.setItem(i - 1, j, QTableWidgetItem(string)) self.ui.tableWidget_6.resizeColumnsToContents() self.ui.tableWidget_6.resizeRowsToContents() ## Show chih_yu record of Quardo W info table_size, record = chih_yu_record.getdatae() self.ui.tableWidget_7.setRowCount(table_size[0] - 2) self.ui.tableWidget_7.setColumnCount(table_size[1]) self.ui.tableWidget.setHorizontalHeaderLabels( self.record_header_labels) for i, row in enumerate(record): if i == 0: continue for j, string in enumerate(record[i]): self.ui.tableWidget_7.setItem(i - 1, j, QTableWidgetItem(string)) self.ui.tableWidget_7.resizeColumnsToContents() self.ui.tableWidget_7.resizeRowsToContents() ## ----------------------------------------------------------------------------------------------------------------- ## Show nobody reward table and q table reward_table_size, reward_table_header, reward_table, q_table_size, qtable_table_header, q_table = nobody_q_table.getdata( ) self.ui.tableWidget_16.setRowCount(reward_table_size[0]) self.ui.tableWidget_16.setColumnCount(reward_table_size[1]) self.ui.tableWidget_16.setHorizontalHeaderLabels(reward_table_header) self.ui.tableWidget_16.setVerticalHeaderLabels(reward_table_header) for i, row in enumerate(reward_table): for j, string in enumerate(reward_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_16.setItem(i, j, string) self.ui.tableWidget_16.resizeColumnsToContents() self.ui.tableWidget_16.resizeRowsToContents() self.ui.tableWidget_24.setRowCount(q_table_size[0]) self.ui.tableWidget_24.setColumnCount(q_table_size[1]) self.ui.tableWidget_24.setHorizontalHeaderLabels(qtable_table_header) self.ui.tableWidget_24.setVerticalHeaderLabels(qtable_table_header) for i, row in enumerate(q_table): for j, string in enumerate(q_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_24.setItem(i, j, string) self.ui.tableWidget_24.resizeColumnsToContents() self.ui.tableWidget_24.resizeRowsToContents() # Show chih_yu reward table and q table reward_table_size, reward_table_header, reward_table, q_table_size, qtable_table_header, q_table = chang_yu_q_table.getdata( ) self.ui.tableWidget_17.setRowCount(reward_table_size[0]) self.ui.tableWidget_17.setColumnCount(reward_table_size[1]) self.ui.tableWidget_17.setHorizontalHeaderLabels(reward_table_header) self.ui.tableWidget_17.setVerticalHeaderLabels(reward_table_header) for i, row in enumerate(reward_table): for j, string in enumerate(reward_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_17.setItem(i, j, string) self.ui.tableWidget_17.resizeColumnsToContents() self.ui.tableWidget_17.resizeRowsToContents() self.ui.tableWidget_25.setRowCount(q_table_size[0]) self.ui.tableWidget_25.setColumnCount(q_table_size[1]) self.ui.tableWidget_25.setHorizontalHeaderLabels(qtable_table_header) self.ui.tableWidget_25.setVerticalHeaderLabels(qtable_table_header) for i, row in enumerate(q_table): for j, string in enumerate(q_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_25.setItem(i, j, string) self.ui.tableWidget_25.resizeColumnsToContents() self.ui.tableWidget_25.resizeRowsToContents() # Show yu_sung reward table and q table reward_table_size, reward_table_header, reward_table, q_table_size, qtable_table_header, q_table = yu_sung_q_table.getdata( ) self.ui.tableWidget_18.setRowCount(reward_table_size[0]) self.ui.tableWidget_18.setColumnCount(reward_table_size[1]) self.ui.tableWidget_18.setHorizontalHeaderLabels(reward_table_header) self.ui.tableWidget_18.setVerticalHeaderLabels(reward_table_header) for i, row in enumerate(reward_table): for j, string in enumerate(reward_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_18.setItem(i, j, string) self.ui.tableWidget_18.resizeColumnsToContents() self.ui.tableWidget_18.resizeRowsToContents() self.ui.tableWidget_26.setRowCount(q_table_size[0]) self.ui.tableWidget_26.setColumnCount(q_table_size[1]) self.ui.tableWidget_26.setHorizontalHeaderLabels(qtable_table_header) self.ui.tableWidget_26.setVerticalHeaderLabels(qtable_table_header) for i, row in enumerate(q_table): for j, string in enumerate(q_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_26.setItem(i, j, string) self.ui.tableWidget_26.resizeColumnsToContents() self.ui.tableWidget_26.resizeRowsToContents() # Show chang_yu reward table and q table reward_table_size, reward_table_header, reward_table, q_table_size, qtable_table_header, q_table = chang_yu_q_table.getdata( ) self.ui.tableWidget_19.setRowCount(reward_table_size[0]) self.ui.tableWidget_19.setColumnCount(reward_table_size[1]) self.ui.tableWidget_19.setHorizontalHeaderLabels(reward_table_header) self.ui.tableWidget_19.setVerticalHeaderLabels(reward_table_header) for i, row in enumerate(reward_table): for j, string in enumerate(reward_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_19.setItem(i, j, string) self.ui.tableWidget_19.resizeColumnsToContents() self.ui.tableWidget_19.resizeRowsToContents() self.ui.tableWidget_27.setRowCount(q_table_size[0]) self.ui.tableWidget_27.setColumnCount(q_table_size[1]) self.ui.tableWidget_27.setHorizontalHeaderLabels(qtable_table_header) self.ui.tableWidget_27.setVerticalHeaderLabels(qtable_table_header) for i, row in enumerate(q_table): for j, string in enumerate(q_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_27.setItem(i, j, string) self.ui.tableWidget_27.resizeColumnsToContents() self.ui.tableWidget_27.resizeRowsToContents() # Show i_hsin reward table and q table reward_table_size, reward_table_header, reward_table, q_table_size, qtable_table_header, q_table = i_hsin_q_table.getdata( ) self.ui.tableWidget_20.setRowCount(reward_table_size[0]) self.ui.tableWidget_20.setColumnCount(reward_table_size[1]) self.ui.tableWidget_20.setHorizontalHeaderLabels(reward_table_header) self.ui.tableWidget_20.setVerticalHeaderLabels(reward_table_header) for i, row in enumerate(reward_table): for j, string in enumerate(reward_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_20.setItem(i, j, string) self.ui.tableWidget_20.resizeColumnsToContents() self.ui.tableWidget_20.resizeRowsToContents() self.ui.tableWidget_28.setRowCount(q_table_size[0]) self.ui.tableWidget_28.setColumnCount(q_table_size[1]) self.ui.tableWidget_28.setHorizontalHeaderLabels(qtable_table_header) self.ui.tableWidget_28.setVerticalHeaderLabels(qtable_table_header) for i, row in enumerate(q_table): for j, string in enumerate(q_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_28.setItem(i, j, string) self.ui.tableWidget_28.resizeColumnsToContents() self.ui.tableWidget_28.resizeRowsToContents() # Show tzu_yuan reward table and q table reward_table_size, reward_table_header, reward_table, q_table_size, qtable_table_header, q_table = tzu_yuan_q_table.getdata( ) self.ui.tableWidget_21.setRowCount(reward_table_size[0]) self.ui.tableWidget_21.setColumnCount(reward_table_size[1]) self.ui.tableWidget_21.setHorizontalHeaderLabels(reward_table_header) self.ui.tableWidget_21.setVerticalHeaderLabels(reward_table_header) for i, row in enumerate(reward_table): for j, string in enumerate(reward_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_21.setItem(i, j, string) self.ui.tableWidget_21.resizeColumnsToContents() self.ui.tableWidget_21.resizeRowsToContents() self.ui.tableWidget_29.setRowCount(q_table_size[0]) self.ui.tableWidget_29.setColumnCount(q_table_size[1]) self.ui.tableWidget_29.setHorizontalHeaderLabels(qtable_table_header) self.ui.tableWidget_29.setVerticalHeaderLabels(qtable_table_header) for i, row in enumerate(q_table): for j, string in enumerate(q_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_29.setItem(i, j, string) self.ui.tableWidget_29.resizeColumnsToContents() self.ui.tableWidget_29.resizeRowsToContents() # Show chang_yu reward table and q table reward_table_size, reward_table_header, reward_table, q_table_size, qtable_table_header, q_table = chang_yu_q_table.getdata( ) self.ui.tableWidget_22.setRowCount(reward_table_size[0]) self.ui.tableWidget_22.setColumnCount(reward_table_size[1]) self.ui.tableWidget_22.setHorizontalHeaderLabels(reward_table_header) self.ui.tableWidget_22.setVerticalHeaderLabels(reward_table_header) for i, row in enumerate(reward_table): for j, string in enumerate(reward_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_22.setItem(i, j, string) self.ui.tableWidget_22.resizeColumnsToContents() self.ui.tableWidget_22.resizeRowsToContents() self.ui.tableWidget_30.setRowCount(q_table_size[0]) self.ui.tableWidget_30.setColumnCount(q_table_size[1]) self.ui.tableWidget_30.setHorizontalHeaderLabels(qtable_table_header) self.ui.tableWidget_30.setVerticalHeaderLabels(qtable_table_header) for i, row in enumerate(q_table): for j, string in enumerate(q_table[i]): string = QtWidgets.QTableWidgetItem(str(string)) self.ui.tableWidget_30.setItem(i, j, string) self.ui.tableWidget_30.resizeColumnsToContents() self.ui.tableWidget_30.resizeRowsToContents()
def setPixmap(self, q_source): size = (self.width(), self.height()) self._original_image = q_source q_source = QPixmap.fromImage(q_source).scaled(*size, QtCore.Qt.KeepAspectRatio) super().setPixmap(q_source) self._pixmap = q_source
def show_frame(self): ret, frame = self.cap.read() frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB) self.frame = frame video_area = self.video_box.video_area # frame = cv.resize(frame, (video_area.width(), video_area.height())) img = QImage(frame.data, frame.shape[1], frame.shape[0], frame.shape[1] * 3, QImage.Format_RGB888) video_area.setPixmap(QPixmap.fromImage(img)) video_area.update() frame = self.get_valid_img() img = QImage(frame.data.tobytes(), frame.shape[1], frame.shape[0], frame.shape[1] * 3, QImage.Format_RGB888) self.show_box.origin.video.setPixmap(QPixmap.fromImage(img)) grey = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) _, binary = cv.threshold(grey, self.binary_threshold, 255, cv.THRESH_BINARY) img = QImage(binary.data.tobytes(), binary.shape[1], binary.shape[0], binary.shape[1], QImage.Format_Grayscale8) self.show_box.binary.video.setPixmap(QPixmap.fromImage(img)) kernel = np.ones((3, 3), np.int8) dilate = cv.dilate(binary, kernel, iterations=self.dilate_iteration) img = QImage(dilate.data.tobytes(), dilate.shape[1], dilate.shape[0], dilate.shape[1], QImage.Format_Grayscale8) self.show_box.dilate.video.setPixmap(QPixmap.fromImage(img)) self.show_box.update() contours, _ = cv.findContours(dilate, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) bounding = [] for c in contours: x, y, w, h = cv.boundingRect(c) if w * h * 10 > len(dilate) * len(dilate[0]) and h / w > 1: bounding.append([x, y, w, h]) bounding = sorted(bounding) num = "" for b in bounding: rec = cv.resize(dilate[b[1]:b[1] + b[3], b[0]:b[0] + b[2]], (5, 7)) # print(len(rec), len(rec[0])) num += match(rec) print(num) try: num = int(num) / 100 except: num = -0x3f3f3f3f self.video_box.configure.indicating_number.setText('当前读数为 ' + str(num)) if num < self.valid_interval[0] or num > self.valid_interval[1]: if self.exceed_cnt > 10 and ((datetime.datetime.now() - self.last_alarm_time).seconds > 300): self.last_alarm_time = datetime.datetime.now() for dst in self.to_miao_code: cur_msg = '您好:\n' cur_msg += '当前示数{}已不在您的预设区间[{}, {}]\n'.format( num, self.valid_interval[0], self.valid_interval[1]) cur_msg += '发送自\n{}\n{}\n{}'.format( socket.gethostbyname(socket.gethostname()), socket.gethostname(), datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) page = request.urlopen('http://miaotixing.com/trigger?' + parse.urlencode({ 'id': dst, 'text': cur_msg, 'type': 'json' })) jsonObj = json.loads(page.read()) if jsonObj['code'] == 0: print('成功') else: print('失败,错误原因:{},{}'.format(jsonObj['code'], jsonObj['msg'])) self.exceed_cnt += 1 else: self.exceed_cnt = 0
def set_image322(self, label, image): label.setPixmap(QPixmap.fromImage(image))
def mouseReleaseEvent(self, event): if event.button == Qt.LeftButton: #self.drawing = False self.label.setPixmap(QPixmap.fromImage(self.image))
def reverse(self): rever = QTransform().scale(1, -1) pixmap = QPixmap(self.image) revers = pixmap.transformed(rever) self.image = QImage(revers) self.image_label2.setPixmap(QPixmap.fromImage(self.image))
def circle(self, ev): try: self.draw.ellipse((ev.pos().x() - 30 - 31, ev.pos().y() - 30 - 10, ev.pos().x() + 30 - 31, ev.pos().y() + 30 - 10), fill = "red") except: pass self.label.setPixmap(QPixmap.fromImage(ImageQt(self.image)))
def process_pix(self, value): img = binaryzation(self.pix.img, threshold=value, alpha=FLAG) self.pix.load_img(QPixmap.fromImage(ImageQt(img)))
def setImage(self, image): self.imageLabel.setPixmap(QPixmap.fromImage(image))
def setThresholdImage(self): img = self.winParent.getCamera().getThresholdImage() if img is not None: image = QImage(img.data, img.shape[1], img.shape[0], img.shape[1] * img.shape[2], QImage.Format_RGB888) self.imgLabelBlackWhite.setPixmap(QPixmap.fromImage(image))
def draw_icon(icon, rect, painter, icon_mode, shadow=False): cache = icon.pixmap(rect.size()) dip_offset = QPoint(1, -2) cache = QPixmap() pixname = "icon {0} {1} {2}".format(icon.cacheKey(), icon_mode, rect.height()) if QPixmapCache.find(pixname) is None: pix = icon.pixmap(rect.size()) device_pixel_ratio = pix.devicePixelRatio() radius = 3 * device_pixel_ratio offset = dip_offset * device_pixel_ratio cache = QPixmap(pix.size() + QSize(radius * 2, radius * 2)) cache.fill(Qt.transparent) cache_painter = QPainter(cache) if icon_mode == QIcon.Disabled: im = pix.toImage().convertToFormat(QImage.Format_ARGB32) for y in range(0, im.height()): scanline = im.scanLine(y) for x in range(0, im.width()): pixel = scanline intensity = qGray(pixel) scanline = qRgba(intensity, intensity, intensity, qAlpha(pixel)) scanline += 1 pix = QPixmap.fromImage(im) # Draw shadow tmp = QImage(pix.size() + QSize(radius * 2, radius * 2), QImage.Format_ARGB32_Premultiplied) tmp.fill(Qt.transparent) tmp_painter = QPainter(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_Source) tmp_painter.drawPixmap( QRect(radius, radius, pix.width(), pix.height()), pix) tmp_painter.end() # Blur the alpha channel blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied) blur_painter = QPainter(blurred) blur_painter.end() # tmp = blurred tmp_painter.begin(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150)) tmp_painter.end() tmp_painter.begin(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150)) tmp_painter.end() # Draw the blurred drop shadow cache_painter.drawImage( QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp) # Draw the actual pixmap cache_painter.drawPixmap( QRect( QPoint(radius, radius) + offset, QSize(pix.width(), pix.height())), pix) cache_painter.end() cache.setDevicePixelRatio(device_pixel_ratio) QPixmapCache.insert(pixname, cache) target_rect = cache.rect() target_rect.setSize(target_rect.size() / cache.devicePixelRatio()) target_rect.moveCenter(rect.center() - dip_offset) painter.drawPixmap(target_rect, cache)
def setFingersImage(self, image): # update video frame as image to the window self.video_label_fingers.setPixmap(QPixmap.fromImage(image))
def show_picture(self): show = cv2.resize(self.current_photo, None, fx=1.3, fy=1.3, interpolation=cv2.INTER_CUBIC) show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB) showImage = QImage(show.data, show.shape[1], show.shape[0], QImage.Format_RGB888) self.label.setPixmap(QPixmap.fromImage(showImage))
def __init__(self): super().__init__() screen = QDesktopWidget().screenGeometry() self.setGeometry( QRect(screen.width() / 2 - window_width / 2, screen.height() / 2 - window_height / 2, window_width, window_height)) self.setWindowTitle('LCD APP Emulator') self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint) self.setFixedSize(self.width(), self.height()) self.btn_up = QPushButton(self) self.btn_up.setText('U') self.btn_up.setGeometry( QRect(left_keys_x_pos - left_keys_size / 2, window_height / 2 - left_keys_sprawl - left_keys_size / 2, left_keys_size, left_keys_size)) self.btn_right = QPushButton(self) self.btn_right.setText('R') self.btn_right.setGeometry( QRect(left_keys_x_pos + left_keys_sprawl - left_keys_size / 2, window_height / 2 - left_keys_size / 2, left_keys_size, left_keys_size)) self.btn_down = QPushButton(self) self.btn_down.setText('D') self.btn_down.setGeometry( QRect(left_keys_x_pos - left_keys_size / 2, window_height / 2 + left_keys_sprawl - left_keys_size / 2, left_keys_size, left_keys_size)) self.btn_left = QPushButton(self) self.btn_left.setText('L') self.btn_left.setGeometry( QRect(left_keys_x_pos - left_keys_sprawl - left_keys_size / 2, window_height / 2 - left_keys_size / 2, left_keys_size, left_keys_size)) self.btn_press = QPushButton(self) self.btn_press.setText('P') self.btn_press.setGeometry( QRect(left_keys_x_pos - left_keys_size / 2, window_height / 2 - left_keys_size / 2, left_keys_size, left_keys_size)) self.btn_1 = QPushButton(self) self.btn_1.setText('1') self.btn_1.setGeometry( QRect( RK_XPOS - right_keys_x_size / 2, window_height / 2 - right_keys_y_size / 2 - right_keys_sprawl, right_keys_x_size, right_keys_y_size)) self.btn_2 = QPushButton(self) self.btn_2.setText('2') self.btn_2.setGeometry( QRect(RK_XPOS - right_keys_x_size / 2, window_height / 2 - right_keys_y_size / 2, right_keys_x_size, right_keys_y_size)) self.btn_3 = QPushButton(self) self.btn_3.setText('3') self.btn_3.setGeometry( QRect( RK_XPOS - right_keys_x_size / 2, window_height / 2 - right_keys_y_size / 2 + right_keys_sprawl, right_keys_x_size, right_keys_y_size)) self.label = QLabel(self) self.q_img = ImageQt.ImageQt(Image.new('RGB', (240, 240), (0, 0, 0))) self.pixmap = QPixmap.fromImage(self.q_img) self.label.setPixmap(self.pixmap) self.label.setGeometry( QRect(SC_XPOS - 120, window_height / 2 - 120, 240, 240))
def setImage(self, image, index): pixmap = QPixmap.fromImage(image) self.pixmap_item.setPixmap(pixmap)
def update_screen(self, image): emulator_window.q_img = ImageQt.ImageQt(image) emulator_window.pixmap = QPixmap.fromImage(emulator_window.q_img) emulator_window.label.setPixmap(emulator_window.pixmap)
def show_slices(self, file_paths): """Creates the thumbnails from the selected file paths. :param file_paths: the selected file paths """ # If it's the first time that this function is called, the MiniViewer # has to be shown if self.first_time: self.setHidden(False) self.first_time = False # If the user has willingly hidden the MiniViewer, the Processes are # not made if self.isHidden(): pass else: self.do_nothing = [False] * len(file_paths) self.file_paths = file_paths self.max_scans = len(file_paths) self.setMinimumHeight(220) self.clearLayouts() self.frame = QFrame(self) self.frame_final = QFrame(self) # Limiting the legend of the thumbnails self.nb_char_max = 60 font = QFont() font.setPointSize(9) # Reading the images from the file paths for idx, file_path in enumerate(self.file_paths.copy()): try: self.img.insert(idx, nib.load(file_path)) except nib.filebasedimages.ImageFileError: print("Error while trying to display the image " + file_path) self.file_paths.remove(file_path) except FileNotFoundError: print("File " + file_path + " not existing") self.file_paths.remove(file_path) # If we are in the "cursors" display mode if self.check_box_slices.checkState() == Qt.Unchecked: # Layout to aligne each thumbnail (image + cursors) self.h_box_thumb = QHBoxLayout() # idx represents the index of the selected image for idx in range(min(self.max_scans, len(self.file_paths))): if not self.do_nothing[idx]: # Creating sliders and labels self.boxSlider(idx) self.enableSliders(idx) self.createDimensionLabels(idx) # Getting the sliders value and reading the image data self.indexImage(idx) # Making some pixel modification to display the image # correctly self.image2DModifications(idx) self.displayPosValue(idx) w, h = self.im_2D[idx].shape im_Qt = QImage(self.im_2D[idx].data, w, h, QImage.Format_Indexed8) pixm = QPixmap.fromImage(im_Qt) file_path_base_name = os.path.basename( self.file_paths[idx]) # imageLabel is the label where the image is displayed # (as a pixmap) self.imageLabel.insert(idx, QLabel(self)) self.imageLabel[idx].setPixmap(pixm) self.imageLabel[idx].setToolTip(file_path_base_name) self.label_description.insert(idx, ClickableLabel()) self.label_description[idx].setFont(font) self.label_description[idx].clicked.connect( self.openTagsPopUp) # Looking for the tag value to display as a # legend of the thumbnail file_path_base_name = os.path.relpath( self.file_paths[idx], self.project.folder) self.setThumbnail(file_path_base_name, idx) # Layout that corresponds to the 3D dimension self.h_box_slider_3D = QHBoxLayout() self.h_box_slider_3D.addWidget(self.label3D[idx]) self.h_box_slider_3D.addWidget(self.txt_slider_3D[idx]) self.h_box_slider_3D.addWidget(self.slider_3D[idx]) # Layout that corresponds to the 4D dimension self.h_box_slider_4D = QHBoxLayout() self.h_box_slider_4D.addWidget(self.label4D[idx]) self.h_box_slider_4D.addWidget(self.txt_slider_4D[idx]) self.h_box_slider_4D.addWidget(self.slider_4D[idx]) # Layout that corresponds to the 5D dimension self.h_box_slider_5D = QHBoxLayout() self.h_box_slider_5D.addWidget(self.label5D[idx]) self.h_box_slider_5D.addWidget(self.txt_slider_5D[idx]) self.h_box_slider_5D.addWidget(self.slider_5D[idx]) # Layout for the three sliders self.v_box_sliders = QVBoxLayout() self.v_box_sliders.addLayout(self.h_box_slider_3D) self.v_box_sliders.addLayout(self.h_box_slider_4D) self.v_box_sliders.addLayout(self.h_box_slider_5D) # Layout that corresponds to the image + the sliders self.h_box = QHBoxLayout() self.h_box.addWidget(self.imageLabel[idx]) self.h_box.addLayout(self.v_box_sliders) # Layout that corresponds to the image and sliders + # the description self.v_box_thumb = QVBoxLayout() self.v_box_thumb.addLayout(self.h_box) self.v_box_thumb.addWidget(self.label_description[idx]) # Layout that will contain all the thumbnails self.h_box_thumb.addLayout(self.v_box_thumb) self.frame.setLayout(self.h_box_thumb) # If we are in the "all slices" display mode else: self.h_box_images = QHBoxLayout() self.h_box_images.setSpacing(10) self.v_box_scans = QVBoxLayout() # idx represents the index of the selected image for idx in range(len(self.file_paths)): file_path_base_name = os.path.relpath( self.file_paths[idx], self.project.folder) self.label_description.insert(idx, ClickableLabel()) self.label_description[idx].setFont(font) self.label_description[idx].clicked.connect( self.openTagsPopUp) # Looking for the tag value to display as a legend # of the thumbnail self.setThumbnail(file_path_base_name, idx) # Depending of the dimension of the image, # the legend of each image and the number of images to # display will change if not self.do_nothing[idx]: if len(self.img[idx].shape) == 3: nb_slices = self.img[idx].shape[2] txt = "Slice n°" elif len(self.img[idx].shape) == 4: nb_slices = self.img[idx].shape[3] txt = "Time n°" elif len(self.img[idx].shape) == 5: nb_slices = self.img[idx].shape[4] txt = "Study n°" else: nb_slices = 0 # Limiting the number of images to the number # chosen by the user for i in range( min(nb_slices, int(self.line_edit_nb_slices.text()))): pixm = self.image_to_pixmap(self.img[idx], i) self.v_box = QVBoxLayout() # label corresponds to the label where one image # is displayed label = QLabel(self) label.setPixmap(pixm) label.setToolTip( os.path.basename(self.file_paths[idx])) # Legend of the image (depends on the number # of dimensions) label_info = QLabel() label_info.setFont(font) label_info.setText(txt + str(i + 1)) label_info.setAlignment(QtCore.Qt.AlignCenter) self.v_box.addWidget(label) self.v_box.addWidget(label_info) # This layout allows to chain each image self.h_box_images.addLayout(self.v_box) self.v_box_scans.addLayout(self.h_box_images) self.v_box_scans.addWidget(self.label_description[idx]) self.frame.setLayout(self.v_box_scans) # Adding a scroll area if the thumbnails are too large self.scroll_area = QScrollArea() self.scroll_area.setWidget(self.frame) self.h_box_check_box = QHBoxLayout() if self.check_box_slices.isChecked(): self.h_box_check_box.addStretch(1) self.label_nb_slices.setHidden(False) self.line_edit_nb_slices.setHidden(False) self.h_box_check_box.addWidget(self.label_nb_slices) self.h_box_check_box.addWidget(self.line_edit_nb_slices) self.check_box_cursors.setHidden(True) else: self.check_box_cursors.setHidden(False) self.h_box_check_box.addWidget(self.check_box_cursors) self.h_box_check_box.addStretch(1) self.label_nb_slices.setHidden(True) self.line_edit_nb_slices.setHidden(True) self.h_box_check_box.addWidget(self.check_box_slices) self.v_box_final.addLayout(self.h_box_check_box) self.v_box_final.addWidget(self.scroll_area)
def loadImage(self): self.viewer.qImage = self.readImage() pixmap = QPixmap.fromImage(self.viewer.qImage) self.viewer.setPhoto(pixmap)
def get_frame(self): sift = cv2.xfeatures2d.SIFT_create() fps = FPS().start() if self.localize_method == 3: self.Detector = Localize2.DetectorMorph() if self.localize_method == 2: self.Detector = Localize1.DetectorEdges() if self.localize_method == 1: self.Detector = Localize3.DetectorMorph() if self.exctact_method == 1: self.Extractor = Segmentation_chars.Segmentation() if self.exctact_method == 2: self.Extractor = Segmentation_chars2.Segmentation2() j = 0 while self.video.get(cv2.CAP_PROP_POS_FRAMES) < self.num_frames and self.stopped == False: #flag when plate is found on frame found = 0 ret, self.last_frame = self.video.read() frame = cv2.resize(self.last_frame, None, fx=0.5, fy=0.5) tablice = [] numbers = [] if self.roi == 1: frame_roi = frame[int(self.y*(frame.shape[0]/400)):int(self.y*(frame.shape[0]/400)+self.height*(frame.shape[0]/400)), int(self.x*(frame.shape[1]/630)):int(self.x*(frame.shape[1]/630)+self.width*(frame.shape[1]/630))] candidates,xy_candidates = self.Detector.find_plate(frame_roi) if self.roi == 2: candidates, xy_candidates = self.Detector.find_plate(frame) for i in range(0,len(candidates)): cand = self.last_frame[(xy_candidates[i][0]+int(self.y*(frame.shape[0]/400))) * 2: (xy_candidates[i][2]+int(self.y*(frame.shape[0]/400))) * 2, (xy_candidates[i][1]+int(self.x*(frame.shape[1]/630))) * 2: (xy_candidates[i][3]+int(self.x*(frame.shape[1]/630))) * 2] if self.flag==1: j = j + 1 filename = "tab/222_" + "%s.png" % str(j) cv2.imwrite(filename,cand) result = self.find_plate(cand) number = "" if result == 0: tablice.append(xy_candidates[i]) chars = self.Extractor.segment(cand) plate_numbers = [] for char in chars: plate_numbers.append(self.predict_character(char)) plate_numbers, ok = self.syntactic.check(plate_numbers) for char in plate_numbers: if ok == 2: number = number + self.class_names[char] numbers.append(number) cv2.rectangle(frame, (xy_candidates[i][1]+int(self.x*(frame.shape[1]/630)), xy_candidates[i][0]+int(self.y*(frame.shape[0]/400))), (xy_candidates[i][3]+int(self.x*(frame.shape[1]/630)), xy_candidates[i][2]+int(self.y*(frame.shape[0]/400))), (0, 255, 0), 2) obiekt, text, rect,missing = self.tracker.update(tablice,numbers) szukaj = [] miss = [] for im in missing: if isinstance(im[0], list): mis = self.last_frame2[(im[0][0] + int(self.y * (frame.shape[0] / 400))) * 2: (im[0][2] + int(self.y * (frame.shape[0] / 400))) * 2,(im[0][1] + int(self.x * (frame.shape[1] / 630))) * 2: (im[0][3] + int(self.x * (frame.shape[1] / 630))) * 2] x0 = (im[0][1] + int(self.x * (frame.shape[1] / 630))) *2 - 20 x1 = (im[0][3] + int(self.x * (frame.shape[1] / 630))) * 2 + 20 y0 = (im[0][0] + int(self.y * (frame.shape[0] / 400))) * 2 - 10 y1 = (im[0][2] + int(self.y * (frame.shape[0] / 400))) * 2 + 10 if x0 < 0: x0 = 0 if x1 > self.last_frame.shape[1]: x1 = self.last_frame.shape[1] if y0 < 0 : y0 = 0 if y1 > self.last_frame.shape[0]: y1 = self.last_frame.shape[0] szukaj.append([self.last_frame[y0:y1,x0: x1],[x0,y0,x1,y1]]) miss.append(mis) else: mis = self.last_frame2[(im[0] + int(self.y * (frame.shape[0] / 400))) * 2: (im[2] + int( self.y * (frame.shape[0] / 400))) * 2, (im[1] + int(self.x * (frame.shape[1] / 630))) * 2: (im[ 3] + int( self.x * (frame.shape[1] / 630))) * 2] miss.append(mis) x0 = (im[1] + int(self.x * (frame.shape[1] / 630))) * 2 - 30 x1 = (im[3] + int(self.x * (frame.shape[1] / 630))) * 2 + 30 y0 = (im[0] + int(self.y * (frame.shape[0] / 400))) * 2 - 15 y1 = (im[2] + int(self.y * (frame.shape[0] / 400))) * 2 + 15 if x0 < 0: x0 = 0 if x1 > self.last_frame.shape[1]: x1 = self.last_frame.shape[1] if y0 < 0 : y0 = 0 if y1 > self.last_frame.shape[0]: y1 = self.last_frame.shape[0] szukaj.append([self.last_frame[y0:y1,x0: x1],[x0,y0,x1,y1]]) #cv2.waitKey(0) finded = [] for mis in range(0,len(miss)): FLANN_INDEX_KDITREE = 0 MIN_MATCH_COUNT = 20 flannParam = dict(algorithm=FLANN_INDEX_KDITREE, tree=5) flann = cv2.FlannBasedMatcher(flannParam, {}) missa = cv2.cvtColor(miss[mis], cv2.COLOR_BGR2GRAY) szukaja = cv2.cvtColor(szukaj[mis][0], cv2.COLOR_BGR2GRAY) trainKP, trainDesc = sift.detectAndCompute(missa, None) queryKP, queryDesc = sift.detectAndCompute(szukaja, None) try: if (type(queryDesc) != 'NoneType') or (type(trainDesc) != 'NoneType') : matches = flann.knnMatch(queryDesc, trainDesc, k=2) goodMatch = [] for m, n in matches: if (m.distance < 0.75 * n.distance): goodMatch.append(m) if (len(goodMatch) > MIN_MATCH_COUNT): tp = [] qp = [] for m in goodMatch: tp.append(trainKP[m.trainIdx].pt) qp.append(queryKP[m.queryIdx].pt) tp, qp = np.float32((tp, qp)) H, status = cv2.findHomography(tp, qp, cv2.RANSAC, 3.0) h, w = missa.shape trainBorder = np.float32([[[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]]) queryBorder = cv2.perspectiveTransform(trainBorder, H) xy = [int(queryBorder[0][0][0]), int(queryBorder[0][0][1]), int(queryBorder[0][2][0]), int(queryBorder[0][2][1])] tabb = [szukaj[mis][1][0]+xy[0],szukaj[mis][1][0]+xy[2],szukaj[mis][1][1]+xy[1],szukaj[mis][1][1]+xy[3]] finded.append(tabb) else: print("Not Enough match found- %d/%d" % (len(goodMatch), MIN_MATCH_COUNT)) except: pass for find in finded: if find[0]<0: find[0] = 0 if find[1]<0: find[1] = 0 if find[2]<0: find[2] = 0 if find[3]<0: find[3] = 0 if find[0]>self.last_frame.shape[1]: find[0] = self.last_frame.shape[1] if find[1]>self.last_frame.shape[1]: find[1] = self.last_frame.shape[1] if find[2]>self.last_frame.shape[0]: find[2] = self.last_frame.shape[0] if find[3]>self.last_frame.shape[0]: find[3] = self.last_frame.shape[0] if find[2]>find[3]: temp = find[2] find[2]=find[3] find[3]=temp if find[0]>find[1]: temp = find[0] find[0]=find[1] find[1]=temp if find[2] == find[3]: find[2]=0 if find[0] == find[1]: find[0]=0 print(find[0]) print(find[1]) print(find[2]) print(find[3]) cand = self.last_frame[find[2] : find[3],find[0]: find[1] ] chars = self.Extractor.segment(cand) plate_numbers = [] number = "" for char in chars: plate_numbers.append(self.predict_character(char)) plate_numbers, ok = self.syntactic.check(plate_numbers) for char in plate_numbers: if ok == 2: number = number + self.class_names[char] if len(number) >= 2: found = 1 numbers.append(number) tablice.append([int((find[2]-int(self.y*(frame.shape[0]/400)))/2),int((find[0]-int(self.x*(frame.shape[1]/630))) / 2),int((find[3]-int(self.y*(frame.shape[0]/400)))/2),int((find[1]-int(self.x*(frame.shape[1]/630))) / 2)]) if found == 1: obiekt, text, rect, missing = self.tracker.update(tablice, numbers) for (objectID, centroid) in obiekt.items(): txt = "{}".format(text.get(objectID)) cv2.putText(frame, txt, (centroid[0]+int(self.x*(frame.shape[1]/630)) - 10, centroid[1]+int(self.y*(frame.shape[0]/400)) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1) rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) h, w, ch = rgbImage.shape bytesPerLine = ch * w p = QtGui.QImage(rgbImage.data, w, h, bytesPerLine, QtGui.QImage.Format_RGB888) p = QPixmap.fromImage(p) pixmap = p.scaled(630, 400) self.pix.emit(pixmap) fps.update() self.last_frame2 = self.last_frame fps.stop() print("[INFO] elasped time: {:.2f}".format(fps.elapsed())) print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
def flipImage(self): transform90 = QTransform().rotate(90) pixmap = QPixmap(self.will_change_img) rotated = pixmap.transformed(transform90, mode=Qt.SmoothTransformation) self.will_change_img = QImage(rotated) self.image_label2.setPixmap(QPixmap.fromImage(self.will_change_img))
def calcHistogram(self): # Calculate histogram, #ÖNCE CDFLER BUL VE LUT YAP HER RENK İCİN resultLabel= QLabel('result') sumOfRedInput =np.sum(self.redArrayInput) self.cdfInputRed = np.cumsum(self.redArrayInput)/sumOfRedInput sumOfGreenInput =np.sum(self.greenArrayInput) self.cdfInputGreen = np.cumsum(self.greenArrayInput)/sumOfGreenInput sumOfBlueInput =np.sum(self.blueArrayInput) self.cdfInputBlue = np.cumsum(self.blueArrayInput)/sumOfBlueInput sumOfRedTarget =np.sum(self.redArrayTarget) self.cdfTargetRed = np.cumsum(self.redArrayTarget)/sumOfRedTarget sumOfGreenTarget =np.sum(self.greenArrayTarget) self.cdfTargetGreen = np.cumsum(self.greenArrayTarget)/sumOfGreenTarget sumOfBlueTarget =np.sum(self.blueArrayTarget) self.cdfTargetBlue = np.cumsum(self.blueArrayTarget)/sumOfBlueTarget self.LUTRed= np.zeros((256,1)) self.LUTGreen= np.zeros((256,1)) self.LUTBlue= np.zeros((256,1)) j=0 for i in range(256): while self.cdfTargetRed[j]<self.cdfInputRed[i] and j<=255: j=j+1 self.LUTRed[i]=j j=0 for i in range(256): while self.cdfTargetGreen[j]<self.cdfInputGreen[i] and j<=255: j=j+1 self.LUTGreen[i]=j j=0 for i in range(256): while self.cdfTargetBlue[j]<self.cdfInputBlue[i] and j<=255: j=j+1 self.LUTBlue[i]=j redHistogram= np.zeros(self.InputRed.shape) resultRed = [0]*256 greenHistogram = np.zeros(redHistogram.shape) resultGreen = [0]*256 blueHistogram = np.zeros(redHistogram.shape) resultBlue = [0]*256 row, column = redHistogram.shape #red for c in range(0,column): for r in range(0,row): redHistogram[r][c]= self.LUTRed[self.InputRed[r][c]] for c in range(0,column): for r in range(0,row): temp =redHistogram[r][c] resultRed[int(temp)]+=1 #greeen for c in range(0,column): for r in range(0,row): greenHistogram[r][c]= self.LUTGreen[self.InputGreen[r][c]] for c in range(0,column): for r in range(0,row): temp =greenHistogram[r][c] resultGreen[int(temp)]+=1 #blue for c in range(0,column): for r in range(0,row): blueHistogram[r][c]= self.LUTBlue[self.InputBlue[r][c]] for c in range(0,column): for r in range(0,row): temp =blueHistogram[r][c] resultBlue[int(temp)]+=1 self.InputImage[:,:,0] = redHistogram self.InputImage[:,:,1] = greenHistogram self.InputImage[:,:,2] = blueHistogram bytesPerLine = 3 * column self.resultImage = QImage(self.InputImage.data,column,row,bytesPerLine,QImage.Format_RGB888) resultLabel = QLabel('result') resultLabel.setPixmap(QPixmap.fromImage(self.resultImage)) resultLabel.setAlignment(Qt.AlignCenter) self.resultGridBox.layout().addWidget(resultLabel) resultPlotRed = self.figureResult.add_subplot(311) resultPlotGreen = self.figureResult.add_subplot(312) resultPlotBlue= self.figureResult.add_subplot(313) resultPlotRed.bar(range(256),resultRed,color = 'red') resultPlotGreen.bar(range(256),resultGreen,color = 'green') resultPlotBlue.bar(range(256),resultBlue,color = 'blue') self.resultGridBox.layout().addWidget(self.canvasResult) return NotImplementedError
def get_change_image(self, image): self.flir_image.setPixmap(QPixmap.fromImage(image))
def run(self): while self.working: if self.mw.AlgIsbasy == False and not (self.mw.limg is None): # 表示成功获取图片 self.mw.AlgIsbasy = True # 开始处理图片 limg = self.mw.limg # 图片赋值 ret = self.mw.TL.NL_TD_InitVarIn(limg) # 调用算法进行处理检测 if ret == 0: ret = self.mw.TL.NL_TD_Process_C( ) # 调用算法sdk的主处理函数 返回值是目标个数 height, width, bytesPerComponent = limg.shape # 照片的三维 像素 bytesPerLine = bytesPerComponent * width # 图像每行锁占用的字节数 rgb = cv2.cvtColor(limg, cv2.COLOR_BGR2RGB) # 颜色空间转换 if ret > 0: # 输出结果 for i in range(self.mw.TL.djTDVarOut.dwObjectSize): outObject = self.mw.TL.djTDVarOut.pdjToyInfors[i] # outObject是 Algorithm.toyDetect.Struct_TD_ObjInfor 类型变量 # print(type(outObject)) # print(outObject.className == "car") if str(outObject.className, "utf-8").replace('\r', '') == "car": self.mw.car1 = ret font = cv2.FONT_HERSHEY_SIMPLEX # 定义字体 # 在图片上,标识类别名称 imgzi = cv2.putText( rgb, str(outObject.className, "utf-8").replace('\r', ''), (int(outObject.dwLeft) + 2, int(outObject.dwBottom) - 2), font, 1.4, (255, 0, 0), 2) """ putText(img, text, org, fontFace, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]]) -> img . @brief Draws a text string. . . The function cv::putText renders the specified text string in the image. Symbols that cannot be rendered . using the specified font are replaced by question marks. See #getTextSize for a text rendering code . example. . . @param img Image. . @param text Text string to be drawn. . @param org Bottom-left corner of the text string in the image. . @param fontFace Font type, see #HersheyFonts. . @param fontScale Font scale factor that is multiplied by the font-specific base size. . @param color Text color. . @param thickness Thickness of the lines used to draw a text. . @param lineType Line type. See #LineTypes . @param bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise, . it is at the top-left corner. """ # 画出物体框 cv2.rectangle(rgb, (int( outObject.dwLeft), int(outObject.dwTop)), (int(outObject.dwRight), int(outObject.dwBottom)), (0, 0, 255), 2) # print('类别名:' + str(outObject.className, "utf-8").replace('\r', '') + ' 置信度: ' + str( # outObject.fscore)) # 打印结果在命令行 """ rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) -> img . @brief Draws a simple, thick, or filled up-right rectangle. . . The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners . are pt1 and pt2. . . @param img Image. . @param pt1 Vertex of the rectangle. . @param pt2 Vertex of the rectangle opposite to pt1 . . @param color Rectangle color or brightness (grayscale image). . @param thickness Thickness of lines that make up the rectangle. Negative values, like #FILLED, . mean that the function has to draw a filled rectangle. . @param lineType Type of the line. See #LineTypes . @param shift Number of fractional bits in the point coordinates. rectangle(img, rec, color[, thickness[, lineType[, shift]]]) -> img . @overload . . use `rec` parameter as alternative specification of the drawn rectangle: `r.tl() and . r.br()-Point(1,1)` are opposite corners """ showImage = QImage(rgb.data, width, height, bytesPerLine, QImage.Format_RGB888) # 将处理过的图片保存用于显示 self.mw.showImage = QPixmap.fromImage(showImage) self.updatedImage.emit( self.mw.frameID) # 触发信号,去执行UI界面的相关函数 self.updatedcar.emit(ret) else: print('Error code1:', ret) time.sleep(100) self.mw.AlgIsbasy = False else: time.sleep(0.001)
def __init__(self, main_window): self.dialog = QDialog(main_window.window) self.ui = qt_appearance.Ui_Dialog() self.ui.setupUi(self.dialog) self.main_window = main_window assets_db_file = Config().read("assets_db") starbound_folder = Config().read("starbound_folder") self.assets = assets.Assets(assets_db_file, starbound_folder) self.species = self.assets.species() # need to think of a new approach here. player rendering on the fly # will not work if we also want to maintain the save/cancel functions # it will probably be easier to ditch that entirely across all dialogs self.player = main_window.player race = main_window.ui.race.currentText() self.player.set_race(race) self.player.set_gender(main_window.get_gender()) # Current player stats race = self.player.get_race() gender = self.player.get_gender() personality = self.player.get_personality() self.colors = { "body": self.player.get_body_directives(), "emote": self.player.get_emote_directives(), "hair": self.player.get_hair_directives(), "facial_hair": self.player.get_facial_hair_directives(), "facial_mask": self.player.get_facial_mask_directives() } color_values = ("body", "hair", "facial_hair", "facial_mask") current_appearance = { "hair": self.player.get_hair(), "facial_hair": self.player.get_facial_hair(), "facial_mask": self.player.get_facial_mask() } appearance_values = ("hair", "facial_hair", "facial_mask") # appearance groups/types for value in appearance_values: group_data = getattr(self.species, "get_%s_groups" % value)(race, gender) type_data = getattr(self.species, "get_%s_types" % value)(race, gender, current_appearance[value][0]) group_widget = getattr(self.ui, value+"_group") for option in group_data: group_widget.addItem(option) group_widget.setCurrentText(current_appearance[value][0]) if len(group_data) < 2: group_widget.setEnabled(False) type_widget = getattr(self.ui, value+"_type") for option in type_data: type_widget.addItem(option) type_widget.setCurrentText(current_appearance[value][1]) if len(type_data) < 2: type_widget.setEnabled(False) group_widget.currentTextChanged.connect(self.write_appearance_values) type_widget.currentTextChanged.connect(self.write_appearance_values) # personality for option in self.species.get_personality(): self.ui.personality.addItem(option[0]) self.ui.personality.setCurrentText(personality) # set up color picker buttons for value in color_values: getattr(self.ui, value+"_color").clicked.connect(getattr(self, "new_%s_color_edit" % value)) if len(self.colors[value]) == 0: getattr(self.ui, value+"_color").setEnabled(False) # player image image = self.assets.species().render_player(self.player) pixmap = QPixmap.fromImage(ImageQt(image)).scaled(86, 86) self.ui.player_preview.setPixmap(pixmap)
def theLastModification(self): try: img = copy.deepcopy(myImage) compareImg = copy.deepcopy(myImage) numPix = int(self.ui.TextBoxPixel.toPlainText()) if 64 % numPix != 0: QMessageBox.question(self, 'Error', "number of pixels must be factor of 64", QMessageBox.Ok) return except: self.ui.btnStart.setEnabled(True) self.ui.btnPause.setEnabled(False) self.ui.btnBrowse.setEnabled(True) return for i in range(0, 64, numPix): self.progressBarValue = i self.progressSignal.emit() try: self.ui.btnPause.setEnabled(True) numPix = int(self.ui.TextBoxPixel.toPlainText()) except: self.ui.btnStart.setEnabled(True) self.ui.btnBrowse.setEnabled(True) return try: if i == 0: imgFft = numpy.fft.fft2(img) imgFftShift = numpy.fft.fftshift(imgFft) with errstate(divide='ignore'): magspec = 20 * numpy.log(numpy.abs(imgFftShift)) #magspec = numpy.asarray(magspec, dtype=numpy.uint8) qImg = qimage2ndarray.array2qimage(magspec) self.ui.lblImgFft.setPixmap(QPixmap.fromImage(qImg)) self.ui.lblImgFft.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) try: for r in range(numPix): for c in range(128): magspec[r + i, c] = 0 imgFftShift[r + i, c] = 0 for r in range(128 - numPix, 128): for c in range(128): magspec[128 - i - numPix - r, c] = 0 imgFftShift[128 - i - numPix - r, c] = 0 for r in range(128): for c in range(numPix): magspec[r, c + i] = 0 imgFftShift[r, c + i] = 0 for r in range(128): for c in range(numPix): magspec[r, 128 - i - numPix + c] = 0 imgFftShift[r, 128 - i - numPix + c] = 0 q1img = qimage2ndarray.array2qimage(magspec) self.ui.lblImgFft.setPixmap(QPixmap.fromImage(q1img)) imgtry = numpy.fft.ifftshift(imgFftShift) imgtry = numpy.fft.ifft2(imgtry) #imagspec = numpy.asarray(imgtry, dtype=numpy.uint8) q2img = qimage2ndarray.array2qimage(imgtry) time.sleep(0.1) self.ui.lblImg.setPixmap(QPixmap.fromImage(q2img)) self.ui.lblImg.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) except: img = copy.deepcopy(myImage) i = 0 self.ui.btnStart.setEnabled(True) return except: self.ui.btnStart.setEnabled(True) return try: if myImage.all() == compareImg.all(): self.theLastModification2() else: self.ui.btnStart.setEnabled(True) return except: self.ui.btnStart.setEnabled(True) return
def mirrorImg(self): mirror = QTransform().scale(-1, 1) pixmap = QPixmap(self.will_change_img) mirrored = pixmap.transformed(mirror) self.will_change_img = QImage(mirrored) self.image_label2.setPixmap(QPixmap.fromImage(self.will_change_img))
def hair_icon(self, species, hair_type, hair_group): image_data = self.assets.species().get_hair_image(species, hair_type, hair_group) return QPixmap.fromImage(ImageQt(image_data))