def interpolate_color( start: QColor, end: QColor, percent: int, colorspace: typing.Optional[QColor.Spec] = QColor.Rgb ) -> QColor: """Get an interpolated color value. Args: start: The start color. end: The end color. percent: Which value to get (0 - 100) colorspace: The desired interpolation color system, QColor::{Rgb,Hsv,Hsl} (from QColor::Spec enum) If None, start is used except when percent is 100. Return: The interpolated QColor, with the same spec as the given start color. """ qtutils.ensure_valid(start) qtutils.ensure_valid(end) if colorspace is None: if percent == 100: return QColor(*end.getRgb()) else: return QColor(*start.getRgb()) out = QColor() if colorspace == QColor.Rgb: a_c1, a_c2, a_c3, _alpha = start.getRgb() b_c1, b_c2, b_c3, _alpha = end.getRgb() components = _get_color_percentage(a_c1, a_c2, a_c3, b_c1, b_c2, b_c3, percent) out.setRgb(*components) elif colorspace == QColor.Hsv: a_c1, a_c2, a_c3, _alpha = start.getHsv() b_c1, b_c2, b_c3, _alpha = end.getHsv() components = _get_color_percentage(a_c1, a_c2, a_c3, b_c1, b_c2, b_c3, percent) out.setHsv(*components) elif colorspace == QColor.Hsl: a_c1, a_c2, a_c3, _alpha = start.getHsl() b_c1, b_c2, b_c3, _alpha = end.getHsl() components = _get_color_percentage(a_c1, a_c2, a_c3, b_c1, b_c2, b_c3, percent) out.setHsl(*components) else: raise ValueError("Invalid colorspace!") out = out.convertTo(start.spec()) qtutils.ensure_valid(out) return out
def interpolate_color( start: QColor, end: QColor, percent: int, colorspace: Optional[QColor.Spec] = QColor.Rgb) -> QColor: """Get an interpolated color value. Args: start: The start color. end: The end color. percent: Which value to get (0 - 100) colorspace: The desired interpolation color system, QColor::{Rgb,Hsv,Hsl} (from QColor::Spec enum) If None, start is used except when percent is 100. Return: The interpolated QColor, with the same spec as the given start color. """ ensure_valid(start) ensure_valid(end) if colorspace is None: if percent == 100: return QColor(*end.getRgb()) else: return QColor(*start.getRgb()) out = QColor() if colorspace == QColor.Rgb: r1, g1, b1, a1 = start.getRgb() r2, g2, b2, a2 = end.getRgb() components = _get_color_percentage(r1, g1, b1, a1, r2, g2, b2, a2, percent) out.setRgb(*components) elif colorspace == QColor.Hsv: h1, s1, v1, a1 = start.getHsv() h2, s2, v2, a2 = end.getHsv() components = _get_color_percentage(h1, s1, v1, a1, h2, s2, v2, a2, percent) out.setHsv(*components) elif colorspace == QColor.Hsl: h1, s1, l1, a1 = start.getHsl() h2, s2, l2, a2 = end.getHsl() components = _get_color_percentage(h1, s1, l1, a1, h2, s2, l2, a2, percent) out.setHsl(*components) else: raise ValueError("Invalid colorspace!") out = out.convertTo(start.spec()) ensure_valid(out) return out
def _get_pixel_diff(self, pix_color: QColor, ref_pix_color: QColor) -> (float, (int, int, int, int)): """ Get the difference between two pixels. The returns a pair: first item is the RMS of the differences across all 4 channels of the colors (RGBA); second item is the absolute difference between the pixel channels. """ DIFF_MAX = 255 pix_rgba = pix_color.getRgb() ref_pix_rgba = ref_pix_color.getRgb() diff = [pow((x - y) / DIFF_MAX, 2) for x, y in zip(pix_rgba, ref_pix_rgba)] diff_rms = sqrt(sum(diff) / len(pix_rgba)) diff_color = [abs(x - y) for x, y in zip(pix_rgba, ref_pix_rgba)] return diff_rms, diff_color
def _calculateNewPixelColor(self, x, y): color = QColor(self.pix.pixel(x, y)) inputRed, inputGreen, inputBlue = color.getRgb()[:3] intensity = 0.36 * inputRed + 0.53 * inputGreen + 0.11 * inputBlue return qRgb(intensity, intensity, intensity)
def update_color(self, event: QColor) -> None: """ 更新颜色 两种方式同时 :param event: :return: """ # print(event, type(event)) # print(self.color_dialog.selectedColor(), type(self.color_dialog.selectedColor())) # QPalette.Background 表示设置背景色 # QPalette.WindowText 表示设置文本颜色 self.palette.setColor(QPalette.Background, event) # 给调色板设置颜色 self.palette.setBrush(QPalette.Base, QBrush(QColor(*event.getRgb()))) # self.palette.setColor(QPalette.Background, self.color_dialog.selectedColor()) # 给调色板设置颜色 # 给控件设置颜色 if event.isValid(): # self.main_window.setStyleSheet('QWidget {background-color:%s}' % event.name()) # self.main_window.setPalette(self.palette) self.color_dialog.setStyleSheet('QWidget {background-color:%s}' % event.name()) self.color_dialog.setPalette(self.palette) # 发色信号 communicate.skin_color.emit(event)
def _calculateNewPixelColor(self, x, y): color = QColor(self.pix.pixel(x, y)) result = qRgb(0, 0, 0) if all( c < 127 for c in color.getRgb()[:3]) else qRgb(255, 255, 255) return result
def setAlphaColorStr(self, color="#ffffff", alpha=100): '''通过字符串值设置半透明颜色''' alphaColor = QColor(color) alphaColor.setAlpha(alpha) red, green, blue, alpha = alphaColor.getRgb() self.setRed(red).setGreen(green).setBlue(blue).setAlpha(alpha) del alphaColor
def draw_rgb(painter: QPainter, size: int, color: QColor): r, g, b, _ = color.getRgb() rgb = list(map(str, [r, g, b])) text_color, back_color = Qt.black, Qt.white w_rgb, h_rgb = size // 4, size // 6 font = get_optimal_font(FAMILY_FONT, w_rgb, h_rgb, text='255') font.setWeight(QFont.Bold) y = size - size // 4 indent = (size * 0.25) // 4 radius = 30 for i, value in enumerate(rgb): x = indent + indent * i + w_rgb * i painter.save() painter.setPen(Qt.NoPen) painter.setBrush(back_color) painter.drawRoundedRect(x, y, w_rgb, h_rgb, radius, radius, Qt.RelativeSize) painter.restore() painter.save() painter.setPen(text_color) painter.setFont(font) painter.drawText(x, y, w_rgb, h_rgb, Qt.AlignCenter, value) painter.restore()
def __init__(self, initial_color: QColor, callback, extra_options=0, parent=None, title=None, *args, **kwargs): super().__init__(parent=parent, *args, **kwargs) self.setObjectName("ColorPicker") # Merge any additional user-supplied options with our own options = QColorDialog.DontUseNativeDialog if extra_options > 0: options = options | extra_options # Set up non-modal color dialog (to avoid blocking the eyedropper) log.debug("Loading QColorDialog with start value %s", initial_color.getRgb()) self.dialog = CPDialog(initial_color, parent) self.dialog.setObjectName("CPDialog") if title: self.dialog.setWindowTitle(title) self.dialog.setWindowFlags(Qt.Tool) self.dialog.setOptions(options) # Avoid signal loops self.dialog.blockSignals(True) self.dialog.colorSelected.connect(callback) self.dialog.finished.connect(self.dialog.deleteLater) self.dialog.finished.connect(self.deleteLater) self.dialog.setCurrentColor(initial_color) self.dialog.blockSignals(False) self.dialog.open() # Seems to help if this is done AFTER init() returns QTimer.singleShot(0, self.add_alpha)
class Window(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QWidget.__init__(self) uic.loadUi("window.ui", self) self.scene = Scene(0, 0, 711, 661) self.canvas.setScene(self.scene) self.cutter_color = QColor(Qt.black) self.line_color = QColor(Qt.blue) self.cut_line_color = QColor(Qt.red) self.figure = list() self.lines = list() self.current_line = list() self.full_polygon = False self.isConvex = False self.direction = -1 self.add_line_bt.clicked.connect(lambda: add_line_bt(self)) self.add_cut_bt.clicked.connect(lambda: add_cut_bt(self)) self.del_cut_bt.clicked.connect(lambda: del_cutter(self)) self.close_bt.clicked.connect(lambda: close_cutter()) self.cut_bt.clicked.connect(lambda: cut_line(self)) self.paral_bt.clicked.connect(lambda: add_paral(self)) self.color_cut_line_bt.clicked.connect(lambda: get_cut_line_color(self)) self.clear_bt.clicked.connect(lambda: clear(self)) self.first_color_buttons() def first_color_buttons(self): self.color_cut_line_bt.setStyleSheet("background-color:rgb" \ + color_in_str(self.cut_line_color.getRgb()))
def setAlphaColorStr(self, color = "#ffffff", alpha = 100): '''通过字符串值设置半透明颜色''' alphaColor = QColor(color) alphaColor.setAlpha(alpha) red, green, blue, alpha = alphaColor.getRgb() self.setRed(red).setGreen(green).setBlue(blue).setAlpha(alpha) del alphaColor
class Window(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QWidget.__init__(self) uic.loadUi("window.ui", self) self.scene = Scene(0, 0, 781, 781) self.scene.win = self self.view.setScene(self.scene) self.image = QImage(781, 781, QImage.Format_ARGB32_Premultiplied) self.image.fill(Qt.white) self.line_color = QColor(Qt.blue) self.cut_line_color = QColor(Qt.red) self.bars.clicked.connect(lambda: set_bars(self)) self.clear_bt.clicked.connect(lambda: clean_all(self)) self.paint.clicked.connect(lambda: clipping(self)) self.rect.clicked.connect(lambda: set_rect(self)) self.on_bars.clicked.connect(lambda: add_bars(self)) # self.color_line_bt.clicked.connect(lambda: get_line_color(self)) self.color_algo_bt.clicked.connect(lambda: get_cut_line_color(self)) self.lines = [] self.cur_line = [] self.clip = None self.point_now = None self.input_bars = False self.input_rect = False self.pen = QPen(blue) self.first_color_buttons() def first_color_buttons(self): self.color_algo_bt.setStyleSheet("background-color:rgb" \ + color_in_str(self.cut_line_color.getRgb()))
def get_good_text_foreground_color(color: QColor) -> QColor: _, r, g, b = color.getRgb() if (r * 0.299 + g * 0.587 + b * 0.114) > 186: return QColor(Qt.black) return QColor(Qt.white)
class WindowTransparentConnect(object): def __init__(self): """ 窗口如透明效果,非阻塞 观察者模式 """ self.window_list = [] self.load_window_list = [] # 创建调色板 self.palette = QPalette() # 颜色初始化 # self.color_init = QColor(107, 173, 246) self.color_init = QColor(*settings.SKIN_COLOR) def options(self) -> None: """ 参数设置 :return: """ self.palette.setColor(QPalette.Background, self.color_init) # 给调色板设置颜色 # self.palette.setBrush(QPalette.Base, QBrush(QColor(255, 255, 255, 0))) self.palette.setBrush(QPalette.Base, QBrush(self.color_init)) def set_window_transparent(self, window: QWidget) -> None: """ 设置窗口背景色 :param window: :return: """ # 窗口透明度 # self.main_window.setWindowOpacity(0.5) window.setAutoFillBackground(True) window.setWindowOpacity(0.8) # 0.0-1.0 # 给控件设置颜色 window.setStyleSheet("background-color: rgb{};".format( self.color_init.getRgb()[:3])) window.setPalette(self.palette) def load_window(self, window: object) -> None: """ 加载窗口对象 :return: """ self.window_list.append(window) def show_window(self) -> None: if not settings.LOAD_EFFECT_ON: # 特效模式 return None for window in self.window_list: self.set_window_transparent(window) def setup_ui(self) -> None: self.options() self.show_window() def retranslate_ui(self) -> None: pass
def show_mouse_color(self, x_pos, y_pos): """Show mouse color with RGBA values.""" pixel = self.parent.qimg.pixel(int(x_pos), int(y_pos)) pixel_color = QColor(pixel) self.parent.mouse_color_label.fill(pixel_color) rgba = pixel_color.getRgb() # 8 bit RGBA self.parent.mouse_rgb_label.setText( f' ({rgba[0]:03d}, {rgba[1]:03d}, {rgba[2]:03d}, {rgba[3]:03d})')
def qss_setting(self, Qcolor: QColor): color_rgb = Qcolor.getRgb() color_r = color_rgb[0] color_g = color_rgb[1] color_b = color_rgb[2] string = 'QComboBox{color:rgb(' + str(color_r) + ',' + str( color_g) + ',' + str(color_b) + ');}' print(string) self.setStyleSheet(string)
def _calculateNewPixelColor(self, x, y): color = QColor(self.pix.pixel(x, y)) inputRed, inputGreen, inputBlue = color.getRgb()[:3] COEFF = 50 outputRed = self._clamp(inputRed + COEFF, 0, 255) outputGreen = self._clamp(inputGreen + COEFF, 0, 255) outputBlue = self._clamp(inputBlue + COEFF, 0, 255) return qRgb(outputRed, outputGreen, outputBlue)
class Window(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QWidget.__init__(self) uic.loadUi("interface.ui", self) self.scene = Scene(0, 0, max_size_x, max_size_y) self.canvas.setScene(self.scene) self.cutter_color = QColor(Qt.black) self.polygon_color = QColor(Qt.red) self.cut_polygon_color = QColor(Qt.green) self.cutter = list() self.polygons = list() self.cur_polygon = list() self.full_polygon = False self.isConvex = False self.direction = -1 self.add_polygon_bt.clicked.connect(lambda: add_polygon_sb(self)) self.add_cutter_bt.clicked.connect(lambda: add_cutter_sb(self)) self.del_cutter_bt.clicked.connect(lambda: del_cutter(self)) self.close_bt.clicked.connect(lambda: close_cutter()) self.close_polygon_bt.clicked.connect(lambda: close_polygon()) self.del_polygon_bt.clicked.connect(lambda: del_last_polygon(self)) self.color_polygon_bt.clicked.connect(lambda: get_polygon_color(self)) self.color_cutter_bt.clicked.connect(lambda: get_cutter_color(self)) self.color_cut_polygon_bt.clicked.connect( lambda: get_cut_polygon_color(self)) self.clear_bt.clicked.connect(lambda: clear(self)) self.first_color_buttons() def first_color_buttons(self): self.color_polygon_bt.setStyleSheet("background-color:rgb" \ + color_in_str(self.polygon_color.getRgb())) self.color_cut_polygon_bt.setStyleSheet("background-color:rgb" \ + color_in_str(self.cut_polygon_color.getRgb())) self.color_cutter_bt.setStyleSheet("background-color:rgb" \ + color_in_str(self.cutter_color.getRgb()))
def catch(self): x = QCursor.pos().x() y = QCursor.pos().y() pixmap = QGuiApplication.primaryScreen().grabWindow(QApplication.desktop().winId(), x, y, 1, 1) if not pixmap.isNull(): image = pixmap.toImage() if not image.isNull(): if (image.valid(0, 0)): color = QColor(image.pixel(0, 0)) r, g, b, _ = color.getRgb() self.nowColor = color self.ui.lineEditMove.setText('(%d, %d, %d) %s' % (r, g, b, color.name().upper())) self.ui.lineEditMove.setStyleSheet('QLineEdit{border:2px solid %s;}' % (color.name()))
def _calculateNewPixelColor(self, x, y): color = QColor(self.pix.pixel(x, y)) inputRed, inputGreen, inputBlue = color.getRgb()[:3] intensity = 0.36 * inputRed + 0.53 * inputGreen + 0.11 * inputBlue COEFF = 35 outputRed = self._clamp(intensity + 2 * COEFF, 0, 255) outputGreen = self._clamp(intensity + 0.5 * COEFF, 0, 255) outputBlue = self._clamp(intensity - COEFF, 0, 255) return qRgb(outputRed, outputGreen, outputBlue)
class Window(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QWidget.__init__(self) uic.loadUi("window.ui", self) self.scene = Scene(0, 0, size_x, size_y) self.canvas.setScene(self.scene) self.image = QImage(size_x, size_y, QImage.Format_ARGB32_Premultiplied) self.image.fill(Qt.white) self.pen = QPen(Qt.black) self.end_polygon_bt.clicked.connect(lambda: close_polygon()) self.add_point_bt.clicked.connect(lambda: add_sb_point(self)) self.clear_bt.clicked.connect(lambda: clear(self)) self.add_seed_pix_bt.clicked.connect(lambda: get_seed_pix(self)) self.fill_bt.clicked.connect(lambda: fill_polygon(self)) self.color_bg_bt.clicked.connect(lambda: get_bg_color(self)) self.color_seed_bt.clicked.connect(lambda: get_seed_color(self)) self.color_border_bt.clicked.connect(lambda: get_border_color(self)) self.seed_pix_button_clicked = False self.cur_polygon = list() self.bg_color = QColor(Qt.white) self.border_color = QColor(Qt.black) self.seed_color = QColor(229, 204, 255) self.first_color_buttons() draw_frame(self) def first_color_buttons(self): self.color_bg_bt.setStyleSheet("background-color:rgb" + color_in_str(self.bg_color.getRgb())) self.color_seed_bt.setStyleSheet( "background-color:rgb" + color_in_str(self.seed_color.getRgb())) self.color_border_bt.setStyleSheet( "background-color:rgb" + color_in_str(self.border_color.getRgb()))
class win(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QWidget.__init__(self) uic.loadUi("window.ui", self) self.scene = Scene(0, 0, max_x, max_y) self.canvas.setScene(self.scene) self.image = QImage(max_x, max_y, QImage.Format_ARGB32_Premultiplied) self.image.fill(Qt.white) self.pen = QPen(Qt.black) self.add_point_bt.clicked.connect(lambda: add_dot_call(self)) self.clear_bt.clicked.connect(lambda: clear(self)) self.add_seed_pix_bt.clicked.connect(lambda: get_seed_pixel(self)) self.fill_bt.clicked.connect(lambda: algorithm_seed(self)) self.color_bg_bt.clicked.connect(lambda: get_bg_color(self)) self.color_seed_bt.clicked.connect(lambda: get_seed_color(self)) self.color_line_bt.clicked.connect(lambda: get_line_color(self)) self.seed_pix_button_clicked = False self.now_figure = list() self.bg_color = QColor(Qt.white) self.line_color = QColor(Qt.black) self.paint_color = QColor(Qt.green) self.first_color_buttons() set_window_borders(self) def first_color_buttons(self): self.color_bg_bt.setStyleSheet("background-color:rgb" \ + color_in_string(self.bg_color.getRgb())) self.color_seed_bt.setStyleSheet("background-color:rgb" \ + color_in_string(self.paint_color.getRgb())) self.color_line_bt.setStyleSheet("background-color:rgb" \ + color_in_string(self.line_color.getRgb()))
class ColorController: def __init__(self, win: Ui_MainWindow): self.win = win self.color = QColor() pixmap = QPixmap('window\\resources\\multicolored-circle.png') self.pixmap = pixmap.scaledToHeight(win.l_color_role.height()) win.l_color_role.setPixmap(self.pixmap) win.l_color_role.mousePressEvent = self._get_pixel win.sl_saturation.valueChanged.connect(self._slider_change_event) win.sl_value.valueChanged.connect(self._slider_change_event) self._slider_change_event() self.set_gradient_in_saturation_slider() def _get_pixel(self, event: QMouseEvent): x = event.pos().x() y = event.pos().y() c = self.pixmap.toImage().pixel(x,y) # color code (integer): 3235912 self.color.setRgba(c) # color object self.set_gradient_in_saturation_slider() self._slider_change_event(event) def set_gradient_in_saturation_slider(self): self.win.sl_saturation.setStyleSheet(f'''QSlider::groove:horizontal {{ background:qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #fff, stop:1 rgb{self.color.getRgb()},); height: 10px; }} QSlider::handle::horizontal {{ background: #333; width:8px; margin: -6px 0; }} ''') def _slider_change_event(self, event=None): self.color.setHsv(self.color.getHsv()[0], self.win.sl_saturation.value(), self.win.sl_value.value()) self.win.l_current_color.setText(self.color.name().upper()) text_color = QColor() if np.sum(self.color.getRgb()) > 470: text_color.setNamedColor('#000') else: text_color.setNamedColor('#fff') self.win.l_current_color.setStyleSheet( f'background-color:rgb{self.color.getRgb()}; color : rgb{text_color.getRgb()};')
def draw_hex(painter: QPainter, size: int, color: QColor): r, g, b, _ = color.getRgb() value = ''.join(f'{x:02X}' for x in [r, g, b]) text_color = get_good_text_foreground_color(color) x, y, w_hex, h_hex = size * 0.05, size * 0.1, size * 0.9, size * 0.25 font = get_optimal_font(FAMILY_FONT, w_hex, h_hex, text='FFFFFF') painter.save() painter.setPen(text_color) painter.setFont(font) painter.drawText(x, y, w_hex, h_hex, Qt.AlignCenter, value) painter.restore()
class Color: def __init__(self, name, r, g, b, whitefg=False): self.name = name self.qt = QColor(r, g, b) self.whitefg = whitefg def rgb(self): r, g, b, a = self.qt.getRgb() return (r, g, b) def textcolor(self): if self.whitefg: return QColor(Qt.white) return QColor(Qt.black) def textcolor_rgb(self): r, g, b, a = self.textcolor().getRgb() return (r, g, b)
def GetClosestColor( color: QColor, descriptions: COLOR_DESCRIPTIONS_TYPE) -> Optional[ColorDescription]: r, g, b, _ = color.getRgb() min_diff_squared: int = None closest: ColorDescription = None for color_description in descriptions: _color = color_description.color _r, _g, _b, _ = _color.getRgb() diff_squared = (r - _r)**2 + (g - _g)**2 + (b - _b)**2 if min_diff_squared is None or diff_squared < min_diff_squared: min_diff_squared = diff_squared closest = color_description return closest
class ColorDialog(QPushButton): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setAutoFillBackground(True) self.color = QColor(237, 126, 4) self.updateColor() def _tmp(): self.color = QColorDialog.getColor() self.updateColor() self.showMenu = _tmp self.clicked.connect(_tmp) def updateColor(self): #* StyleSheet method # self.setStyleSheet(f"background-color: rgba{self.color.getRgb()};" # f"selection-background-color: rgba{self.color.getRgb()};" # f"selection-color: rgba{self.color.getRgb()};") #* Palette method pal = QPalette() pal.setColor(QPalette.Highlight, self.color) pal.setColor(QPalette.Button, self.color) pal.setColor(QPalette.ButtonText, self.color) self.setPalette(pal) self.clearFocus() self.update() def getColor(self): return self.color.getRgb() def setColor(self, color): self.color = QColor(*color) self.updateColor()
def catch(self): x = QCursor.pos().x() y = QCursor.pos().y() pixmap = QGuiApplication.primaryScreen().grabWindow( QApplication.desktop().winId(), x, y, 1, 1) if not pixmap.isNull(): image = pixmap.toImage() if not image.isNull(): if image.valid(0, 0): color = QColor(image.pixel(0, 0)) r, g, b, _ = color.getRgb() h, s, v = list( cv2.cvtColor( np.array([[[r, g, b]]]).astype(np.uint8), cv2.COLOR_RGB2HSV).reshape(3)) self.nowColor = color self.ui.lineEditMove.setText( '(%d, %d, %d) %s \n ' 'HSV in cv2 (%d, %d, %d)' % (r, g, b, color.name().upper(), h, s, v)) self.ui.lineEditMove.setStyleSheet('QLineEdit{border:2px ' 'solid %s;}' % (color.name()))
def capture_mouse(self): point = QCursor.pos() self.pix_map = QGuiApplication.primaryScreen().grabWindow( QApplication.desktop().winId(), point.x() - 25, point.y() - 25, 51, 51) if not self.pix_map.isNull(): image = self.pix_map.toImage() if not image.isNull(): color = QColor(image.pixel(25, 25)) r, g, b, _ = color.getRgb() self.current_color = color self.current_point = point self.ui.label_color_value.setText('%s' % color.name().upper()) self.ui.label_absolute_pos_value.setText( '%d, %d' % (point.x(), point.y())) if self.client_rect is not None: relative_x = point.x() - self.client_rect[0] relative_y = point.y() - self.client_rect[1] self.ui.label_relative_pos_value.setText( '%d, %d' % (relative_x, relative_y)) self.ui.label_rgb_value.setText('%d, %d, %d' % (r, g, b)) self.zoom_display()
def __init__(self, image_filename): self.script = None self.index = None self.image_filename = image_filename self.grid = [] self.weapon_name = os.path.split(image_filename)[-1].split('-')[-2] print(self.weapon_name) pixmap = QPixmap(image_filename) image = pixmap.toImage() self.width, self.height = image.width(), image.height() self.colors = [] for x in range(self.width): for y in range(self.height): color = QColor(image.pixel(x, y)) if color not in self.colors: self.colors.append(color) self.grid.append(self.colors.index(color)) for idx, color in enumerate(self.colors): print(idx, color.getRgb()) self.already_reordered = False
class Channel(): def __init__(self, name, tila): self.name = name self.file = None self.signal = None self.length = 0 self.index = 0 self.state = tila # kanava päällä self.ypos = 0 self.voltage = 1 self.scale = 1 self.drawColor = QColor(255, 0, 0) def ReadFile(self, file): """ Lukee annetun tiedoston ja tallentaa signaalin desimaalilukuina listaan. Poikkeustilanteet käsitellään Oskilloskoopin puolella. """ # ei tiedostoa if file == "": return False # WAV if file.split(".")[-1] == "wav": try: data = wave.open(file, 'r') params = data.getparams() # nchannels, samplewidth (bytes), samplerate, nframes, compression, compname #print("Wav file \"{}\"".format(file.split("/")[-1])) #print("Channels: {}, Samplewidth: {}, Samplerate: {}, Frames: {}, Length: {} s\n".format(params[0], params[1], params[2], params[3], float(params[3])/float(params[2]))) if not params[1] == 2: # 16 bit raise SyntaxError if not params[0] == 1: # mono raise NameError if float(params[3])/float(params[2]) < 1.0: # alle 1 sec raise RuntimeError frames = data.readframes(data.getnframes()) # data bitteinä (string of bytes) signaali = struct.unpack("%ih" % params[3], frames) # muunnetaan signed short intiksi (16 bit) signaali = [float(x)/(2**15) for x in signaali] # muunnetaan desimaaliluvuksi -1.0...1.0 # 16 bit int = arvot -32768...32767 (2^15) self.signal = signaali self.length = len(signaali) self.file = file return True finally: if data: data.close() # CSV elif file.split(".")[-1] == "csv": try: data = open(file, 'r') signaali = [float(x.strip()) for x in data] # tallennetaan desimaaliluvuksi if len(signaali) < 48000: # < 1 sec raise RuntimeError self.signal = signaali self.length = len(signaali) self.file = file return True finally: if data: data.close() # Tiedosto jotain muuta tyyppiä else: raise TypeError def PrintInfo(self): print("CHANNEL", self.name) print("state: ", self.state) print("file: ", self.file) print("length: ", self.length) print("ypos: ", self.ypos) print("voltage: ", self.voltage) print("scale: ", self.scale) print("color: ", self.drawColor.getRgb(), "\n")
class AppearanceWindow(QtWidgets.QDialog): def __init__(self, settings, parent=None): super(AppearanceWindow, self).__init__(parent) self.ui = Ui_DialogAppearance() self.ui.setupUi(self) self.settings = settings self.ui.pushButtonChangeDirectColour.clicked.connect( self.choose_new_direct_colour) self.ui.pushButtonChangeIndirectColour.clicked.connect( self.choose_new_indirect_colour) self.ui.pushButtonChangeFont.clicked.connect(self.choose_new_font) self.new_font = self.settings.value('Appearance/new_font') col = self.settings.value('Appearance/directMatchColour') if col is None: self.direct_match_colour = default_direct_match_colour else: self.direct_match_colour = QColor(col) col = self.settings.value('Appearance/indirectMatchColour') if col is None: self.indirect_match_colour = default_indirect_match_colour else: self.indirect_match_colour = QColor(col) if self.new_font is not None: self.ui.labelNormalRow.setFont(self.new_font) self.ui.labelDirectMatchedRow.setFont(self.new_font) self.ui.labelIndirectMatchedRow.setFont(self.new_font) self.ui.labelNormalRow.setStyleSheet( 'QLabel { background-color : white}') r, g, b, _ = self.direct_match_colour.getRgb() self.ui.labelDirectMatchedRow.setStyleSheet( 'QLabel {{ background-color : rgb({},{},{})}}'.format(r, g, b)) r, g, b, _ = self.indirect_match_colour.getRgb() self.ui.labelIndirectMatchedRow.setStyleSheet( 'QLabel {{ background-color : rgb({},{},{})}}'.format(r, g, b)) # TODO: These two functions are almost exactly the same, they should be rolled into one somehow def choose_new_direct_colour(self): new_colour = QColorDialog().getColor(initial=self.direct_match_colour, parent=self) if new_colour.isValid(): r, g, b, _ = new_colour.getRgb() self.direct_match_colour = new_colour self.ui.labelDirectMatchedRow.setStyleSheet( 'QLabel {{ background-color : rgb({},{},{})}}'.format(r, g, b)) def choose_new_indirect_colour(self): new_colour = QColorDialog().getColor( initial=self.indirect_match_colour, parent=self) if new_colour.isValid(): r, g, b, _ = new_colour.getRgb() self.indirect_match_colour = new_colour self.ui.labelIndirectMatchedRow.setStyleSheet( 'QLabel {{ background-color : rgb({},{},{})}}'.format(r, g, b)) def choose_new_font(self): font, ok = QFontDialog.getFont(self.ui.labelNormalRow.font(), self) if ok: self.ui.labelNormalRow.setFont(font) self.ui.labelDirectMatchedRow.setFont(font) self.ui.labelIndirectMatchedRow.setFont(font) self.new_font = font