def on_pushButton_calibrate_clicked(self): self._widget.pushButton_calibrate.setEnabled(False) status_icon = QIcon.fromTheme('stock_no') # Fill request information request = self._selected_service['service_class']._request_class() request.target_hue.data = self._widget.spinBox_hue.value() request.mult_diffs.data = self._widget.spinBox_diff.value() request.mult_sat.data = self._widget.spinBox_sat.value() try: # Call service response = self._selected_service['service_proxy'](request) except rospy.ServiceException as e: qWarning('on_pushButton_calibrate_clicked(): error calling service "%s":\n%s' % (self._selected_service['service_name'], e)) else: # Get debug image and show img = response.image_debug qImage = QImage(img.data, img.width, img.height, img.step, QImage.Format_RGB888) qPixmap = QPixmap() qPixmap.convertFromImage(qImage) pixmapItem = QGraphicsPixmapItem(qPixmap) self._qGraphicsScene.clear() self._qGraphicsScene.addItem(pixmapItem) self._widget.graphicsView.fitInView(QRectF(qPixmap.rect()), Qt.KeepAspectRatio) if response.success.data == True: status_icon = QIcon.fromTheme('stock_yes') self._widget.label_status.setPixmap(status_icon.pixmap(status_icon.actualSize(QSize(24, 24)))) self._widget.pushButton_calibrate.setEnabled(True)
def handle_signal(self, image, qPixmapItem, qGraphicsView): qImage = QImage(image.data, image.width, image.height, image.step, QImage.Format_RGB888) qPixmap = QPixmap() qPixmap.convertFromImage(qImage) qPixmapItem.setPixmap(qPixmap) qGraphicsView.fitInView(qPixmapItem, Qt.KeepAspectRatio)
def rocon_icon_to_qicon(icon): """ :param rocon_std_msgs.Icon icon: icon to use for the pixmap """ pixmap = QPixmap() pixmap.loadFromData(icon.data, format=icon.format) return QIcon(pixmap)
def __init__(self, img): splash_pix = QPixmap(img) self.splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) self.splash.setMask(splash_pix.mask()) self.splash.show() for i in range(100): time.sleep(0.01) QApplication.processEvents()
def update(self): """ Updates the widget. """ if not self.__deleted: if self.__selected_item is not None: data_dict = self.__selected_item.get_latest_data() self.__state = data_dict["state"] self.host_node_label.setText( self.tr(self.__selected_item.get_seuid())) if self.__previous_state is not self.__state: self.__previous_state = self.__state if self.__state == "ok": self.current_status_label.setText(self.tr("ok")) #self.host_node_label.setText(self.tr("Current Status: Ok")) pixmap = QPixmap( os.path.join( self.rp.get_path('rqt_arni_gui_detail'), 'resources/graphics', 'block_green.png')) elif self.__state == "warning": self.current_status_label.setText(self.tr("warning")) #self.host_node_label.setText(self.tr("Current Status: Warning")) pixmap = QPixmap( os.path.join( self.rp.get_path('rqt_arni_gui_detail'), 'resources/graphics', 'block_orange.png')) elif self.__state == "unknown": self.current_status_label.setText(self.tr("unkown")) #self.host_node_label.setText(self.tr("Current Status: Unkown")) pixmap = QPixmap( os.path.join( self.rp.get_path('rqt_arni_gui_detail'), 'resources/graphics', 'block_grey.png')) else: # error or offline self.current_status_label.setText(self.tr( self.__state)) pixmap = QPixmap( os.path.join( self.rp.get_path('rqt_arni_gui_detail'), 'resources/graphics', 'block_red.png')) self.status_light_label.setPixmap(pixmap) content = self.__selected_item.get_detailed_data() scroll_value = self.information_tab_text_browser.verticalScrollBar( ).value() self.information_tab_text_browser.setHtml(content) self.information_tab_text_browser.verticalScrollBar( ).setSliderPosition(scroll_value) else: self.host_node_label.setText(self.tr("No item selected")) self.current_status_label.setText(self.tr("Offline")) self.information_tab_text_browser.setText( self. tr("Please select an item in the TreeView to get more information" " about it"))
def __init__(self, context): """ Constructor """ super(CarlaControlPlugin, self).__init__(context) self.setObjectName('CARLA Control') self._widget = QWidget() self._node = CompatibleNode('rqt_carla_control_node') package_share_dir = roscomp.get_package_share_directory( 'rqt_carla_control') ui_file = os.path.join(package_share_dir, 'resource', 'CarlaControl.ui') loadUi(ui_file, self._widget) self._widget.setObjectName('CarlaControl') if context.serial_number() > 1: self._widget.setWindowTitle(self._widget.windowTitle() + (' (%d)' % context.serial_number())) self.pause_icon = QIcon( QPixmap(os.path.join(package_share_dir, 'resource', 'pause.png'))) self.play_icon = QIcon( QPixmap(os.path.join(package_share_dir, 'resource', 'play.png'))) self._widget.pushButtonStepOnce.setIcon( QIcon( QPixmap( os.path.join(package_share_dir, 'resource', 'step_once.png')))) self.carla_status = None self.carla_status_subscriber = self._node.new_subscription( CarlaStatus, "/carla/status", self.carla_status_changed, qos_profile=10) self.carla_control_publisher = self._node.new_publisher( CarlaControl, "/carla/control", qos_profile=10) self._widget.pushButtonPlayPause.setDisabled(True) self._widget.pushButtonStepOnce.setDisabled(True) self._widget.pushButtonPlayPause.setIcon(self.play_icon) self._widget.pushButtonPlayPause.clicked.connect( self.toggle_play_pause) self._widget.pushButtonStepOnce.clicked.connect(self.step_once) context.add_widget(self._widget) if roscomp.get_ros_version() == 2: spin_thread = threading.Thread(target=self._node.spin, daemon=True) spin_thread.start()
def redraw(self): with self.lock: if self.cv_image != None: size = self.cv_image.shape img = QImage(self.cv_image.data, size[1], size[0], size[2] * size[1], QImage.Format_RGB888) # convert to QPixmap self.pixmap = QPixmap(size[1], size[0]) self.pixmap.convertFromImage(img) self.label.setPixmap( self.pixmap.scaled(self.label.width(), self.label.height(), QtCore.Qt.KeepAspectRatio))
def image_callback(self, ros_data): np_arr = np.fromstring(ros_data.data, np.uint8) image = cv.imdecode(np_arr, cv.IMREAD_COLOR) height, width, _ = image.shape bytes_per_line = 3 * width qImage = QImage(image.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped() pix = QPixmap(qImage) h_label = self._widget.videoDisplay.height() w_label = self._widget.videoDisplay.width() self._widget.videoDisplay.setPixmap( pix.scaled(w_label, h_label, Qt.KeepAspectRatio))
def mouseMoveEvent(self, event): ''' Determine if the current movement is a drag. If it is, convert it into a QDrag. If the drag ends inside the tab bar, emit an move_tab_signal. If the drag ends outside the tab bar, emit an detach_tab_signal. ''' # Determine if the current movement is detected as a drag if not self.drag_start_pos.isNull() and ((event.pos() - self.drag_start_pos).manhattanLength() > QApplication.startDragDistance()): self.drag_initiated = True # If the current movement is a drag initiated by the left button if ((event.buttons() & Qt.LeftButton)) and self.drag_initiated: # Stop the move event finishMoveEvent = QMouseEvent(QEvent.MouseMove, event.pos(), Qt.NoButton, Qt.NoButton, Qt.NoModifier) QTabBar.mouseMoveEvent(self, finishMoveEvent) # Convert the move event into a drag drag = QDrag(self) mime_data = QMimeData() mime_data.setData('action', b'application/tab-detach') drag.setMimeData(mime_data) # Create the appearance of dragging the tab content # tab_index = self.tabAt(self.drag_start_pos) pixmap = self.parentWidget().grab() targetPixmap = QPixmap(pixmap.size()) targetPixmap.fill(Qt.transparent) painter = QPainter(targetPixmap) painter.setOpacity(0.85) painter.drawPixmap(0, 0, pixmap) painter.end() drag.setPixmap(targetPixmap) # Initiate the drag dropAction = drag.exec_(Qt.MoveAction | Qt.CopyAction) # If the drag completed outside of the tab bar, detach the tab and move # the content to the current cursor position if dropAction == Qt.IgnoreAction: event.accept() self.detach_tab_signal.emit(self.tabAt(self.drag_start_pos), self.mouse_cursor.pos(), False) elif dropAction == Qt.MoveAction: # else if the drag completed inside the tab bar, move the selected tab to the new position if not self.drag_droped_pos.isNull(): self.move_tab_signal.emit(self.tabAt(self.drag_start_pos), self.tabAt(self.drag_droped_pos)) else: # else if the drag completed inside the tab bar new TabBar, move the selected tab to the new TabBar self.detach_tab_signal.emit(self.tabAt(self.drag_start_pos), self.mouse_cursor.pos(), False) event.accept() else: QTabBar.mouseMoveEvent(self, event)
def on_compressed_image_received(self, image): ''' :param sensor_msgs.CompressedImage image: convert and display this in the QGraphicsView. ''' if len(self.scene.items()) > 1: self.scene.removeItem(self.scene.items()[0]) pixmap = QPixmap() pixmap.loadFromData(image.data, format=image.format) self.scene.addPixmap(pixmap) self.scene.update() # setting fitInvView seems sensitive to here or prior to scene update self.fitInView(QRectF(0, 0, self.scene.width(), self.scene.height()), Qt.KeepAspectRatio)
def __init__(self, parent=None, info=False): QFrame.__init__(self, parent=parent) self.setObjectName('MessageFrame') self.questionid = self.TYPE_INVALID self.text = "" self.data = MessageData(None) self.IMAGES = {1: QPixmap(), 2: QPixmap(':/icons/crystal_clear_question.png').scaled(self.ICON_SIZE, self.ICON_SIZE, Qt.IgnoreAspectRatio, Qt.SmoothTransformation), 3: QPixmap(':/icons/crystal_clear_launch_file.png').scaled(self.ICON_SIZE, self.ICON_SIZE, Qt.IgnoreAspectRatio, Qt.SmoothTransformation), 4: QPixmap(":/icons/default_cfg.png").scaled(self.ICON_SIZE, self.ICON_SIZE, Qt.IgnoreAspectRatio, Qt.SmoothTransformation), 5: QPixmap(":/icons/crystal_clear_nodelet_q.png").scaled(self.ICON_SIZE, self.ICON_SIZE, Qt.IgnoreAspectRatio, Qt.SmoothTransformation), 6: QPixmap(":/icons/crystal_clear_launch_file_transfer.png").scaled(self.ICON_SIZE, self.ICON_SIZE, Qt.IgnoreAspectRatio, Qt.SmoothTransformation), 7: QPixmap(":/icons/crystal_clear_question.png").scaled(self.ICON_SIZE, self.ICON_SIZE, Qt.IgnoreAspectRatio, Qt.SmoothTransformation), 8: QPixmap(":/icons/crystal_clear_no_io.png").scaled(self.ICON_SIZE, self.ICON_SIZE, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) } self._new_request = False self.frameui = QFrame() ui_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'MessageFrame.ui') loadUi(ui_file, self.frameui) color = QColor(255, 207, 121) self.frameui.setVisible(False) self.frameui.listLabel.setVisible(False) self.frameui.questionOkButton.clicked.connect(self._on_question_ok) self.frameui.questionCancelButton.clicked.connect(self._on_question_cancel) self.frameui.checkBox_dnaa.stateChanged.connect(self._on_checkbox_state_changed) self._ask = 'ask' if info: color = QColor(232, 104, 80) self.frameui.questionCancelButton.setVisible(False) self._ask = 'show' bg_style = "QFrame#questionFame { background-color: %s;}" % color.name() self.frameui.setStyleSheet("%s" % (bg_style)) self._queue = MessageQueue() self._do_not_ask = {}
def __init__(self, context): super(SpeechStatusPlugin, self).__init__(context) self.setObjectName('SpeechStatusPlugin') self._widget = QWidget() if context.serial_number() > 1: self._widget.setWindowTitle(self._widget.windowTitle() + (' (%d)' % context.serial_number())) ui_file = os.path.join(rospkg.RosPack().get_path('rqt_speech_status'), 'resource', 'speech_widget.ui') loadUi(ui_file, self._widget) context.add_widget(self._widget) file_live = os.path.join( rospkg.RosPack().get_path('rqt_speech_status'), 'resource', 'microphone.png') file_mute = os.path.join( rospkg.RosPack().get_path('rqt_speech_status'), 'resource', 'muted.png') file_silency = os.path.join( rospkg.RosPack().get_path('rqt_speech_status'), 'resource', 'silence-face.png') file_speech = os.path.join( rospkg.RosPack().get_path('rqt_speech_status'), 'resource', 'surprise-face.png') self.img_mute = QPixmap(file_mute).scaled(160, 160) self.img_live = QPixmap(file_live).scaled(160, 160) self.img_silency = QPixmap(file_silency).scaled(160, 160) self.img_speech = QPixmap(file_speech).scaled(160, 160) self._widget.imgRecognition.setPixmap(self.img_live) self._widget.imgSilency.setPixmap(self.img_silency) self.signal_render_recog_status = SignalRender() self.signal_render_recog_status.renderSignal.connect( self.render_recog_status) self.signal_render_silency_status = SignalRender() self.signal_render_silency_status.renderSignal.connect( self.render_silency_status) rospy.Subscriber('enable_recognition', Bool, self.handle_enable_recognition) rospy.Subscriber('start_of_speech', Empty, self.handle_start_speech) rospy.Subscriber('end_of_speech', Empty, self.handle_end_speech) rospy.Subscriber('silency_detected', Empty, self.handle_silency_detection)
def _show_image(self, bin_, index): target_name = self.bin_contents[bin_][index] target_image_path = os.path.join(self.image_path, target_name, 'image.jpg') target_pixmap = QPixmap(target_image_path).scaled(100, 100) self.bin_dict[bin_]['image'].setPixmap(target_pixmap) self.bin_dict[bin_]['image'].show()
def update(self): if self.mapitem: self.scene.removeItem(self.mapitem) qpix = QPixmap.fromImage(self.map) self.mapitem = self.scene.addPixmap(qpix) self.mirror(self.mapitem) self.show()
def update_description(self, index, cfg, name, displayed_name, robot_type, description, images): ''' Sets the values of an existing item to the given items only if the current value is empty. ''' if index < len(self._data): obj = self._data[index] if cfg not in obj['cfgs']: obj['cfgs'].append(cfg) if not obj['name']: obj['name'] = name if not obj['displayed_name']: obj['displayed_name'] = displayed_name if not obj['type']: obj['type'] = robot_type if not obj['description']: obj['description'] = replace_paths(description) if not obj['images']: for image_path in images: img = interpret_path(image_path) if img and img[0] != os.path.sep: img = os.path.join(nm.settings().PACKAGE_DIR, image_path) if os.path.isfile(img): obj['images'].append(QPixmap(img))
def _setup_tab_view_page(self, sid, mid): tabContent = InnerWidget(mid, sid) tabContent.mesaurementLabel.setText( "<html><head/><body><p><span style=\" font-size:14pt; " "font-weight:600;\">Measurement {}</span></p></body></html>". format(mid + 1)) measurement = self.last_site_data.sites[sid].measurements[ mid] # type: rover_science.msg.Measurement tabContent.latitudeLabel.setText("Latitude: {}".format( measurement.location.latitude)) tabContent.longitudeLabel.setText("Longitude: {}".format( measurement.location.longitude)) tabContent.altitudeLabel.setText("Altitude: {}".format( measurement.location.altitude)) site = self.last_site_data.sites[sid] if site.has_pano & site.HAS_PANO == site.HAS_PANO: pmap = QPixmap(site.pano_location) tabContent.panorama.clear() tabContent.panorama.setPixmap(pmap) tabContent.panorama.setMaximumSize(500, 350) if measurement.data_completeness & measurement.HAS_PH == measurement.HAS_PH: tabContent.phLabel.setText("PH: {}".format(measurement.ph)) if measurement.data_completeness & measurement.HAS_TEMP == measurement.HAS_TEMP: tabContent.tempLabel.setText("Temperature: {}".format( measurement.temp)) if measurement.data_completeness & measurement.HAS_HUMIDITY == measurement.HAS_HUMIDITY: tabContent.humidityLabel.setText("Humidity: {}".format( measurement.humidity)) tabContent.retake.connect(self.retake_measurement_clicked) self.tabWidget.addTab(tabContent, "Measurement {}".format(mid + 1))
def __init__(self, context): """ Constructor """ super(CarlaControlPlugin, self).__init__(context) self.setObjectName('CARLA Control') self._widget = QWidget() ui_file = os.path.join(rospkg.RosPack().get_path('rqt_carla_control'), 'resource', 'CarlaControl.ui') loadUi(ui_file, self._widget) self._widget.setObjectName('CarlaControl') if context.serial_number() > 1: self._widget.setWindowTitle(self._widget.windowTitle() + (' (%d)' % context.serial_number())) self.pause_icon = QIcon( QPixmap( os.path.join(rospkg.RosPack().get_path('rqt_carla_control'), 'resource', 'pause.png'))) self.play_icon = QIcon( QPixmap( os.path.join(rospkg.RosPack().get_path('rqt_carla_control'), 'resource', 'play.png'))) self._widget.pushButtonStepOnce.setIcon( QIcon( QPixmap( os.path.join( rospkg.RosPack().get_path('rqt_carla_control'), 'resource', 'step_once.png')))) self.carla_status = None self.carla_status_subscriber = rospy.Subscriber( "/carla/status", CarlaStatus, self.carla_status_changed) self.carla_control_publisher = rospy.Publisher("/carla/control", CarlaControl, queue_size=10) self._widget.pushButtonPlayPause.setDisabled(True) self._widget.pushButtonStepOnce.setDisabled(True) self._widget.pushButtonPlayPause.setIcon(self.play_icon) self._widget.pushButtonPlayPause.clicked.connect( self.toggle_play_pause) self._widget.pushButtonStepOnce.clicked.connect(self.step_once) context.add_widget(self._widget)
def put_image_into_scene(self): if self._image: resized_image = self._image.resize((self._image_view.size().width() - 2, self._image_view.size().height() - 2), self.quality) QtImage = ImageQt(resized_image) pixmap = QPixmap.fromImage(QtImage) self._scene.clear() self._scene.addPixmap(pixmap)
def put_image_into_scene(self): if self._image: if self.capture is None: resized_image = self._image.resize( (self._image_view.size().width() - 2, self._image_view.size().height() - 2, self.quality)) QtImage = ImageQt(resized_image) pixmap = QPixmap.fromImage(QtImage) self._scene.clear() self._scene.addPixmap(pixmap) else: QtImage = ImageQt(self._image) pixmap = QPixmap.fromImage(QtImage) self.label = CaptureImage(self._timeline, self._topic, self._image_msg, self.capture) self.label.setPixmap(pixmap) self._scene.addWidget(self.label)
def __init__(self, context): super(MasterInfo, self).__init__(context) self.initialised = False self.setObjectName('MasterInfo') self._current_dotcode = None self._master_info = rocon_master_info.get_master_info(0.5) # at worst a small timeout here, but perhaps should be run in a thread. self._widget = QWidget() self._widget.setObjectName('RoconMasterInfoUi') rospack = rospkg.RosPack() ui_file = os.path.join(rospack.get_path('rocon_qt_master_info'), 'ui', 'master_info.ui') loadUi(ui_file, self._widget) if context.serial_number() > 1: self._widget.setWindowTitle(self._widget.windowTitle() + (' (%d)' % context.serial_number())) pixmap = QPixmap() pixmap.loadFromData(self._master_info.icon.data, format=self._master_info.icon.format) self._widget.icon_label.setPixmap(pixmap) self._widget.icon_label.resize(pixmap.width(), pixmap.height()) self._widget.info_label.resize(200, pixmap.height()) self._widget.info_label.setText("<b>Name:</b> %s<br/><b>Rocon Version:</b> %s<br/><b>Description:</b> %s" % (self._master_info.name, self._master_info.version, self._master_info.description)) self._widget.adjustSize() context.add_widget(self._widget)
def make_icon(self, image_list, mode=QIcon.Normal, state=QIcon.On): """ Helper function to create QIcons from lists of image files Warning: svg files interleaved with other files will not render correctly :param image_list: list of image paths to layer into an icon. :type image: list of str :param mode: The mode of the QIcon to be created. :type mode: int :param state: the state of the QIcon to be created. :type state: int """ if type(image_list) is not list: image_list = [image_list] if len(image_list) <= 0: raise TypeError('The list of images is empty.') num_svg = 0 for item in image_list: if item[-4:].lower() == '.svg': num_svg = num_svg + 1 if num_svg != len(image_list): # Legacy support for non-svg images icon_pixmap = QPixmap() icon_pixmap.load(image_list[0]) painter = QPainter(icon_pixmap) for item in image_list[1:]: painter.drawPixmap(0, 0, QPixmap(item)) icon = QIcon() icon.addPixmap(icon_pixmap, mode, state) painter.end() return icon else: # rendering SVG files into a QImage renderer = QSvgRenderer(image_list[0]) icon_image = QImage(renderer.defaultSize(), QImage.Format_ARGB32) icon_image.fill(0) painter = QPainter(icon_image) renderer.render(painter) if len(image_list) > 1: for item in image_list[1:]: renderer.load(item) renderer.render(painter) painter.end() # Convert QImage into a pixmap to create the icon icon_pixmap = QPixmap() icon_pixmap.convertFromImage(icon_image) icon = QIcon(icon_pixmap) return icon
def _load_default_image(self): joystick_icon = os.path.join( rospkg.RosPack().get_path('rocon_bubble_icons'), 'icons', 'joystick.png') pixmap = QPixmap(joystick_icon, format="png") self.scene.addPixmap(pixmap) self.scene.update() self.fitInView(QRectF(0, 0, self.scene.width(), self.scene.height()), Qt.KeepAspectRatio)
def _update(self): if self._map_item: self._scene.removeItem(self._map_item) pixmap = QPixmap.fromImage(self._map) self._map_item = self._scene.addPixmap(pixmap) self.centerOn(self._map_item) self.show()
def load_map(self, scenario): self.scenario = scenario map_yaml = os.path.join(rospkg.RosPack().get_path('rqt_simulation'), 'scenarios', scenario, 'map.yaml') self.loadConfig(map_yaml) map = 'map.png' map_file = os.path.join(rospkg.RosPack().get_path('rqt_simulation'), 'scenarios', scenario, map) pixmap = QPixmap(map_file) self.mapSize = pixmap.size() self.addPixmap(pixmap) # Add world origin self.worldOrigin = QPointF( -self.map_origin[0] / self.map_resolution, self.map_origin[1] / self.map_resolution + self.mapSize.height()) self.addCoordinateSystem(self.worldOrigin, 0.0)
class ScaledLabel(QLabel): def __init__(self, *args, **kwargs): QLabel.__init__(self) self._pixmap = QPixmap(self.pixmap()) def resizeEvent(self, event): self.setPixmap( self._pixmap.scaled(self.width(), self.height(), QtCore.Qt.KeepAspectRatio))
def getRobotLabel(self, colorStr): """ initiates the robot label :param colorStr: color as string :return: """ ls = self.pool.get(colorStr) if ls == []: pxmap = QPixmap(self._getRobFile(colorStr)) rob = QLabel(parent=self.frame) rob.setPixmap(pxmap) rob.originalPixmap = QPixmap(pxmap) rob.setScaledContents(True) rob.setFixedSize(self.size, self.size) rob.show() return rob else: rob = ls.pop() rob.show() return rob
def _update(self): if self._map_item: self._scene.removeItem(self._map_item) pixmap = QPixmap.fromImage(self._map) self._map_item = self._scene.addPixmap(pixmap) # Everything must be mirrored self._mirror(self._map_item) self.centerOn(self._map_item) self.show()
def _set_icon(self): pixmap = QPixmap() pixmap.loadFromData( self.qt_rapp_manager_info._get_icon().data, format=self.qt_rapp_manager_info._get_icon().format) self._widget.icon_label.setPixmap(pixmap) self._widget.icon_label.resize(pixmap.width(), pixmap.height())
def fome_raw(self, data): try: cvImage = self.bridge.imgmsg_to_cv2(data, "bgr8") except CvBridgeError as e: print(e) height, width, byteValue = cvImage.shape byteValue = byteValue * width cv2.cvtColor(cvImage, cv2.COLOR_BGR2RGB, cvImage) r_image = QImage(cvImage, width, height, byteValue, QImage.Format_RGB888) r_image = QPixmap.fromImage(r_image) r_image = r_image.scaledToHeight(300) self.r_label.setPixmap(r_image)
def redraw(self): with self.lock: if self.cv_image != None: size = self.cv_image.shape img = QImage(self.cv_image.data, size[1], size[0], size[2] * size[1], QImage.Format_RGB888) # convert to QPixmap self.pixmap = QPixmap(size[1], size[0]) self.pixmap.convertFromImage(img) self.label.setPixmap(self.pixmap.scaled( self.label.width(), self.label.height(), QtCore.Qt.KeepAspectRatio))
def msg_to_pixmap(self, msg): cv_img = self.bridge.imgmsg_to_cv2(msg) shape = cv_img.shape if len(shape) == 3 and shape[2] == 3: # RGB888 h, w, _ = shape bytesPerLine = 3 * w img_format = QImage.Format_RGB888 else: # Grayscale8 h, w = shape[0], shape[1] bytesPerLine = 1 * w img_format = QImage.Format_Grayscale8 q_img = QImage(cv_img.data, w, h, bytesPerLine, img_format) return QPixmap.fromImage(q_img).scaled(320, 240)
def updateCupMask(self, img): try: image = self.__cvBridge.imgmsg_to_cv2(img) # Convert ROS' sensor_msgs/Image to cv2 image image = cv2.merge((image, image, image)) # QImage only supports colour images or 1-bit mono (which opencv does not) height, width = image.shape[:2] frame = QImage(image.data, width, height, QImage.Format_RGB888) self.__cupImageScene.clear() self.__cupImageScene.addPixmap(QPixmap.fromImage(frame)) self.__cupImageScene.update() self._widget.cupGraphicsView.setScene(self.__cupImageScene) self._widget.cupGraphicsView.ensureVisible(self.__cupImageScene.sceneRect()); self._widget.cupGraphicsView.fitInView(self.__cupImageScene.sceneRect(), Qt.KeepAspectRatio); except Exception as e: rospy.logerr("update updatecupMask: %s", e)
def update(self): """ Updates the Plugin and draws the graphs if draw_graphs is true. """ data_dict = self.__model.get_root_item().get_latest_data("state") self.__state = data_dict["state"] if self.__previous_state is not self.__state: self.__previous_state = self.__state if self.__state == "ok": self.status_text_line_edit.setText( self.tr("Current status: Ok")) pixmap = QPixmap( os.path.join(self.rp.get_path('rqt_arni_gui_overview'), 'resources/graphics', 'light_green.png')) elif self.__state == "warning": self.status_text_line_edit.setText( self.tr("Current status: Warning")) pixmap = QPixmap( os.path.join(self.rp.get_path('rqt_arni_gui_overview'), 'resources/graphics', 'light_orange.png')) else: self.status_text_line_edit.setText( self.tr("Current status: Error")) pixmap = QPixmap( os.path.join(self.rp.get_path('rqt_arni_gui_overview'), 'resources/graphics', 'light_red.png')) self.status_light_label.setPixmap(pixmap) if self.information_tab_text_browser: scroll_value = self.information_tab_text_browser.verticalScrollBar( ).value() self.information_tab_text_browser.setHtml( self.__model.get_overview_text()) self.information_tab_text_browser.verticalScrollBar( ).setSliderPosition(scroll_value)
def _update(self): if self._map_item: self._scene.removeItem(self._map_item) pixmap = QPixmap.fromImage(self._map) self._map_item = self._scene.addPixmap(pixmap) # Everything must be mirrored self._mirror(self._map_item) # Add drag and drop functionality self.add_dragdrop(self._map_item) self.centerOn(self._map_item) self.show()
def updateImage(self, img): try: img.encoding = "bgr8" # no, it's not but cv_bridge can't handle hsv image = self.__cvBridge.imgmsg_to_cv2(img) # Convert ROS' sensor_msgs/Image to cv2 image self.__lastHSVimage = image.copy() image = cv2.cvtColor(image, cv2.COLOR_HSV2RGB) height, width = image.shape[:2] frame = QImage(image.data, width, height, QImage.Format_RGB888) self.__colorImageScene.clear() self.__colorImageScene.addPixmap(QPixmap.fromImage(frame)) self.__colorImageScene.update() self._widget.lightCorrectedGraphicsView.setScene(self.__colorImageScene) self._widget.lightCorrectedGraphicsView.ensureVisible(self.__colorImageScene.sceneRect()); self._widget.lightCorrectedGraphicsView.fitInView(self.__colorImageScene.sceneRect(), Qt.KeepAspectRatio); except Exception as e: rospy.logerr("update image: %s", e)
def __init__(self, img): splash_pix = QPixmap(img) self.splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) self.splash.setMask(splash_pix.mask()) self.splash.show() QApplication.processEvents()
class ImageView2Widget(QWidget): """ Qt widget to communicate with image_view2 """ cv_image = None pixmap = None def __init__(self): super(ImageView2Widget, self).__init__() self.left_button_clicked = False self.lock = Lock() self.event_pub = rospy.Publisher("event", MouseEvent) self.bridge = CvBridge() self.label = ScaledLabel() self.label.setAlignment(Qt.AlignCenter) self.label.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)) #self.label.installEventFilter(self) hbox = QtGui.QHBoxLayout(self) hbox.addWidget(self.label) self.setLayout(hbox) self.image_sub = rospy.Subscriber("image_marked", Image, self.imageCallback) self._update_plot_timer = QTimer(self) self._update_plot_timer.timeout.connect(self.redraw) self._update_plot_timer.start(40) self.setMouseTracking(True) self.show() def imageCallback(self, msg): with self.lock: cv_image = self.bridge.imgmsg_to_cv2(msg, msg.encoding) if msg.encoding == "bgr8": self.cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB) elif msg.encoding == "rgb8": self.cv_image = cv_image self.numpy_image = np.asarray(self.cv_image) def redraw(self): with self.lock: if self.cv_image != None: size = self.cv_image.shape img = QImage(self.cv_image.data, size[1], size[0], size[2] * size[1], QImage.Format_RGB888) # convert to QPixmap self.pixmap = QPixmap(size[1], size[0]) self.pixmap.convertFromImage(img) self.label.setPixmap(self.pixmap.scaled( self.label.width(), self.label.height(), QtCore.Qt.KeepAspectRatio)) #self.label.setPixmap(self.pixmap) def mousePosition(self, e): label_x = self.label.x() label_y = self.label.y() label_width = self.label.width() label_height = self.label.height() pixmap_width = self.label.pixmap().width() pixmap_height = self.label.pixmap().height() x_offset = (label_width - pixmap_width) / 2.0 + label_x y_offset = (label_height - pixmap_height) / 2.0 + label_y return (e.x() - x_offset, e.y()- y_offset) def mouseMoveEvent(self, e): if self.left_button_clicked: msg = MouseEvent() msg.header.stamp = rospy.Time.now() msg.type = MouseEvent.MOUSE_MOVE msg.x, msg.y = self.mousePosition(e) msg.width = self.label.pixmap().width() msg.height = self.label.pixmap().height() self.event_pub.publish(msg) def mousePressEvent(self, e): msg = MouseEvent() msg.header.stamp = rospy.Time.now() if e.button() == Qt.LeftButton: msg.type = MouseEvent.MOUSE_LEFT_DOWN self.left_button_clicked = True elif msg.type == Qt.RightButton: msg.type = MouseEvent.MOUSE_RIGHT_DOWN msg.width = self.label.pixmap().width() msg.height = self.label.pixmap().height() msg.x, msg.y = self.mousePosition(e) self.event_pub.publish(msg) def mouseReleaseEvent(self, e): if e.button() == Qt.LeftButton: self.left_button_clicked = False msg = MouseEvent() msg.header.stamp = rospy.Time.now() msg.width = self.label.pixmap().width() msg.height = self.label.pixmap().height() msg.type = MouseEvent.MOUSE_LEFT_UP msg.x, msg.y = self.mousePosition(e) self.event_pub.publish(msg) def eventFilter(self, widget, event): if not self.pixmap: return QtGui.QMainWindow.eventFilter(self, widget, event) if (event.type() == QtCore.QEvent.Resize and widget is self.label): self.label.setPixmap(self.pixmap.scaled( self.label.width(), self.label.height(), QtCore.Qt.KeepAspectRatio)) return True return QtGui.QMainWindow.eventFilter(self, widget, event)
def draw_timeline_segment(self, painter, topic, stamp_start, stamp_end, x, y, width, height): """ draws a stream of images for the topic :param painter: painter object, ''QPainter'' :param topic: topic to draw, ''str'' :param stamp_start: stamp to start drawing, ''rospy.Time'' :param stamp_end: stamp to end drawing, ''rospy.Time'' :param x: x to draw images at, ''int'' :param y: y to draw images at, ''int'' :param width: width in pixels of the timeline area, ''int'' :param height: height in pixels of the timeline area, ''int'' """ if x < self.timeline._history_left: width += x - self.timeline._history_left x = self.timeline._history_left max_interval_thumbnail = self.timeline.map_dx_to_dstamp(self.thumbnail_combine_px) max_interval_thumbnail = max(0.1, max_interval_thumbnail) thumbnail_gap = 6 thumbnail_x, thumbnail_y, thumbnail_height = x + 1, y + 1, height - 2 - thumbnail_gap # leave 1px border # set color to white draw rectangle over messages painter.setBrush(QBrush(Qt.white)) painter.drawRect(x, y, width, height - thumbnail_gap) thumbnail_width = None while True: available_width = (x + width) - thumbnail_x # Check for enough remaining to draw thumbnail if width > 1 and available_width < self.min_thumbnail_width: break # Try to display the thumbnail, if its right edge is to the right of the timeline's left side if not thumbnail_width or thumbnail_x + thumbnail_width >= self.timeline._history_left: stamp = self.timeline.map_x_to_stamp(thumbnail_x, clamp_to_visible=False) thumbnail_bitmap = self.thumbnail_cache.get_item(topic, stamp, max_interval_thumbnail) # Cache miss if not thumbnail_bitmap: thumbnail_details = (thumbnail_height,) self.thumbnail_cache.enqueue((topic, stamp, max_interval_thumbnail, thumbnail_details)) if not thumbnail_width: break else: thumbnail_width, _ = thumbnail_bitmap.size if width > 1: if available_width < thumbnail_width: thumbnail_width = available_width - 1 QtImage = ImageQt(thumbnail_bitmap) pixmap = QPixmap.fromImage(QtImage) painter.drawPixmap(thumbnail_x, thumbnail_y, thumbnail_width, thumbnail_height, pixmap) thumbnail_x += thumbnail_width if width == 1: break painter.setPen(QPen(QBrush(Qt.black))) painter.setBrush(QBrush(Qt.transparent)) if width == 1: painter.drawRect(x, y, thumbnail_x - x, height - thumbnail_gap - 1) else: painter.drawRect(x, y, width, height - thumbnail_gap - 1) return True
def mousePressEvent(self, event): thing = QPixmap.grabWidget(self._layoutmanager._view) if thing.save(self.filename, "png", 100): print "Saved image to ", self.filename
class ImageView2Widget(QWidget): """ Qt widget to communicate with image_view2 """ cv_image = None pixmap = None repaint_trigger = pyqtSignal() def __init__(self): super(ImageView2Widget, self).__init__() self.left_button_clicked = False self.repaint_trigger.connect(self.redraw) self.lock = Lock() self.need_to_rewrite = False self.bridge = CvBridge() self.image_sub = None self.event_pub = None self.label = ScaledLabel() self.label.setAlignment(Qt.AlignCenter) self.label.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)) #self.label.installEventFilter(self) vbox = QtGui.QVBoxLayout(self) vbox.addWidget(self.label) self.setLayout(vbox) self._image_topics = [] self._update_topic_thread = Thread(target=self.updateTopics) self._update_topic_thread.start() self._active_topic = None self.setMouseTracking(True) self.label.setMouseTracking(True) self._dialog = ComboBoxDialog() self.show() def trigger_configuration(self): self._dialog.exec_() self.setupSubscriber(self._image_topics[self._dialog.number]) def setupSubscriber(self, topic): if self.image_sub: self.image_sub.unregister() rospy.loginfo("Subscribing %s" % (topic + "/marked")) self.image_sub = rospy.Subscriber(topic + "/marked", Image, self.imageCallback) self.event_pub = rospy.Publisher(topic + "/event", MouseEvent) self._active_topic = topic def onActivated(self, number): self.setupSubscriber(self._image_topics[number]) def imageCallback(self, msg): with self.lock: if msg.width == 0 or msg.height == 0: rospy.logdebug("Looks input images is invalid") return cv_image = self.bridge.imgmsg_to_cv2(msg, msg.encoding) if msg.encoding == "bgr8": self.cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB) elif msg.encoding == "rgb8": self.cv_image = cv_image self.numpy_image = np.asarray(self.cv_image) self.need_to_rewrite = True self.repaint_trigger.emit() def updateTopics(self): need_to_update = False for (topic, topic_type) in rospy.get_published_topics(): if topic_type == "sensor_msgs/Image": with self.lock: if not topic in self._image_topics: self._image_topics.append(topic) need_to_update = True if need_to_update: with self.lock: self._image_topics = sorted(self._image_topics) self._dialog.combo_box.clear() for topic in self._image_topics: self._dialog.combo_box.addItem(topic) if self._active_topic: self._dialog.combo_box.setCurrentIndex(self._image_topics.index(self._active_topic)) time.sleep(1) @pyqtSlot() def redraw(self): with self.lock: if not self.need_to_rewrite: return if self.cv_image != None: size = self.cv_image.shape img = QImage(self.cv_image.data, size[1], size[0], size[2] * size[1], QImage.Format_RGB888) # convert to QPixmap self.pixmap = QPixmap(size[1], size[0]) self.pixmap.convertFromImage(img) self.label.setPixmap(self.pixmap.scaled( self.label.width(), self.label.height(), QtCore.Qt.KeepAspectRatio)) #self.label.setPixmap(self.pixmap) def mousePosition(self, e): label_x = self.label.x() label_y = self.label.y() label_width = self.label.width() label_height = self.label.height() pixmap_width = self.label.pixmap().width() pixmap_height = self.label.pixmap().height() x_offset = (label_width - pixmap_width) / 2.0 + label_x y_offset = (label_height - pixmap_height) / 2.0 + label_y return (e.x() - x_offset, e.y()- y_offset) def mouseMoveEvent(self, e): msg = MouseEvent() msg.header.stamp = rospy.Time.now() msg.type = MouseEvent.MOUSE_MOVE msg.x, msg.y = self.mousePosition(e) msg.width = self.label.pixmap().width() msg.height = self.label.pixmap().height() if self.event_pub: self.event_pub.publish(msg) def mousePressEvent(self, e): msg = MouseEvent() msg.header.stamp = rospy.Time.now() if e.button() == Qt.LeftButton: msg.type = MouseEvent.MOUSE_LEFT_DOWN self.left_button_clicked = True elif e.button() == Qt.RightButton: msg.type = MouseEvent.MOUSE_RIGHT_DOWN msg.width = self.label.pixmap().width() msg.height = self.label.pixmap().height() msg.x, msg.y = self.mousePosition(e) if self.event_pub: self.event_pub.publish(msg) def mouseReleaseEvent(self, e): if e.button() == Qt.LeftButton: self.left_button_clicked = False msg = MouseEvent() msg.header.stamp = rospy.Time.now() msg.width = self.label.pixmap().width() msg.height = self.label.pixmap().height() msg.type = MouseEvent.MOUSE_LEFT_UP msg.x, msg.y = self.mousePosition(e) if self.event_pub: self.event_pub.publish(msg) def save_settings(self, plugin_settings, instance_settings): if self._active_topic: instance_settings.set_value("active_topic", self._active_topic) def restore_settings(self, plugin_settings, instance_settings): if instance_settings.value("active_topic"): topic = instance_settings.value("active_topic") self._dialog.combo_box.addItem(topic) self.setupSubscriber(topic)