Beispiel #1
0
 def convertCvToQImage(self, img, copy=False):
     """
         converts opencv image to QImage. 
         source : Stack Overflow
         Input : img must be in openCV image format (np.uint8)
     """
     if img is None:
         return QImage()
     # if input image format is openCv image format np.uint8
     if img.dtype == np.uint8:
         # grayscale image or images having two dimensions [height, width]
         if len(img.shape) == 2:
             qim = QImage(img.data, img.shape[1], img.shape[0],
                          img.strides[0], QImage.Format_Indexed8)
             qim.setColorTable(gray_color_table)
             return qim.copy() if copy else qim
         # image having three dimansions [height, width, nChannels]
         elif len(img.shape) == 3:
             # if image has three channels
             if img.shape[2] == 3:
                 qim = QImage(img.data, img.shape[1], img.shape[0],
                              img.strides[0], QImage.Format_RGB888)
                 return qim.copy() if copy else qim
             # if image has four channels
             elif img.shape[2] == 4:
                 qim = QImage(img.data, img.shape[1], img.shape[0],
                              img.strides[0], QImage.Format_ARGB32)
                 return qim.copy() if copy else qim
Beispiel #2
0
class View(QWidget):
	def __init__(self, parent):
		super().__init__(parent)
		self.setMouseTracking(True)		
		self.x = 0
		self.y = 0
		self.prevX = 0
		self.prevY = 0
		
		self.viewSize = 512
		self.brushSize = 3
		self.isSmoothDrawing = True

		self.buffer = QImage(self.viewSize, self.viewSize, QImage.Format_ARGB32)		
		self.buffer.fill(Qt.white)
		self.undoBuffer = self.buffer.copy()
		self.guide = self.buffer.copy()
		
		self.setMinimumSize(self.viewSize,self.viewSize)
		self.setMaximumSize(self.viewSize,self.viewSize)
		
	def paintEvent(self, e):
		qp = QPainter()
		qp.begin(self)
		
		qp.setOpacity(1.0)
		qp.drawImage(0,0,self.buffer)

	def mouseMoveEvent(self, e):
		self.x = e.x()
		self.y = e.y()
Beispiel #3
0
    def toQImage(self, im, copy=False):
        if im is None:
            return QImage()

        if im.dtype == np.uint8:
            if len(im.shape) == 2:
                qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0],
                             QImage.Format_Indexed8)
                qim.setColorTable(self.gray_color_table)
                return qim.copy() if copy else qim

        elif len(im.shape) == 3:
            if im.shape[2] == 3:
                qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0],
                             QImage.Format_RGB888)
                return qim.copy() if copy else qim
            elif im.shape[2] == 4:
                qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0],
                             QImage.Format_ARGB32)
                return qim.copy() if copy else qim

        def openImage(self, image=None, fileName=None):
            if image == None:
                image = QImage(fileName)
            if image.isNull():
                QMessageBox.information(self, "Image Viewer",
                                        "Cannot load %s." % fileName)
                return self.imageLabel.setPixmap(QPixmap.fromImage(image))

            self.fitToWindowAct.setEnabled(True)
            self.updateActions()
            if not self.fitToWindowAct.isChecked():
                self.imageLabel.adjustSize()
    def updateTiles(self, filename):

        if filename:

            size = self.LABEL_SIZE

            # RGB tile
            img = QImage(filename)
            img = img.copy(256, 256, 513, 513)
            pxmap = QPixmap.fromImage(img)
            self.QlabelRGB.setPixmap(pxmap.scaled(QSize(size, size)))

            # GT tile
            filename = filename.replace('images', 'labels')
            print(filename)
            img2 = QImage(filename)
            img2 = img2.copy(256, 256, 513, 513)
            pxmapGT = QPixmap.fromImage(img2)
            self.QlabelLB.setPixmap(pxmapGT.scaled(QSize(size, size)))

            # prediction tile
            base_name = os.path.basename(filename)
            newfilename = os.path.join(self.prediction_folder, base_name)
            img3 = QImage(newfilename)
            pxmapPred = QPixmap.fromImage(img3)
            self.QlabelPred.setPixmap(pxmapPred.scaled(QSize(size, size)))
def crop_160x120_thumbnail(thumbnail: QImage, vertical_space: int=8) -> QImage:
    """
    Remove black bands from the top and bottom of thumbnail
    :param thumbnail: thumbnail to crop
    :param vertical_space: how much to remove from the top and bottom
    :return: cropped thumbnail
    """
    if thumbnail.width() == 160 and thumbnail.height() == 120:
        return thumbnail.copy(0, vertical_space, 160, 120 - vertical_space * 2)
    elif thumbnail.width() == 120 and thumbnail.height() == 160:
        return thumbnail.copy(vertical_space, 0, 120 - vertical_space * 2, 160)
    else:
        return thumbnail
Beispiel #6
0
class Canvas:
    def __init__(self, cols, rows, color=bg_trans):
        self.image = QImage(8 * cols, 8 * rows,
                            QImage.Format_ARGB32_Premultiplied)
        self.image.fill(color)
        self.painter = QtGui.QPainter(self.image)
        self.max_x = 1
        self.max_y = 1

    def __del__(self):
        del self.painter

    def draw_pixmap(self, col, row, pixmap, h_flip=False, v_flip=False):
        h_s = -1 if h_flip else 1
        v_s = -1 if v_flip else 1
        x = (col + h_flip) * 8 * h_s
        y = (row + v_flip) * 8 * v_s
        self.painter.scale(h_s, v_s)
        self.painter.drawPixmap(x, y, pixmap)
        self.painter.scale(h_s, v_s)  # Invert it again to restore it to normal
        if col > self.max_x:
            self.max_x = col
        if row > self.max_y:
            self.max_y = row

    def pixmap(self, trim=False):
        if trim:
            return QPixmap.fromImage(
                self.image.copy(0, 0, self.max_x * 8 + 8, self.max_y * 8 + 8))
        return QPixmap.fromImage(self.image)
Beispiel #7
0
class Window(QWidget):
    def __init__(self, *args, **kwargs):
        super(Window, self).__init__(*args, **kwargs)
        layout = QVBoxLayout(self)
        self.imgLabel = QLabel(self)
        self.coldSlider = QSlider(Qt.Horizontal, self)
        self.coldSlider.valueChanged.connect(self.doChange)
        self.coldSlider.setRange(0, 255)
        layout.addWidget(self.imgLabel)
        layout.addWidget(self.coldSlider)

        # 加载图片
        self.srcImg = QImage('src.jpg')
        self.imgLabel.setPixmap(
            QPixmap.fromImage(self.srcImg).scaledToWidth(
                800, Qt.SmoothTransformation))
        # DLL库
        self.dll = CDLL('Cold.dll')
        print(self.dll)

    def doChange(self, value):
        t = time()
        img = self.srcImg.copy()  # 复制一份
        # For PyQt5
        self.dll.cold(sip.unwrapinstance(img), value)
        # For PySide2
        # self.dll.cold(shiboken2.getCppPointer(img)[0], value)
        self.imgLabel.setPixmap(
            QPixmap.fromImage(img).scaledToWidth(800, Qt.SmoothTransformation))
        print('use time:', time() - t)
    def get_new_image(self):
        """
        Descript. :
        """
        raw_buffer, width, height = self.get_image()

        if raw_buffer is not None and raw_buffer.any():
            if self.cam_type == "basler":
                raw_buffer = self.decoder(raw_buffer)
                qimage = QImage(
                    raw_buffer, width, height, width * 3, QImage.Format_RGB888
                )
            else:
                qimage = QImage(raw_buffer, width, height, QImage.Format_RGB888)

            if self.cam_mirror is not None:
                qimage = qimage.mirrored(self.cam_mirror[0], self.cam_mirror[1])

            if self.scale != 1:
                dims = self.get_image_dimensions()  # should be already scaled
                qimage = qimage.scaled(QSize(dims[0], dims[1]))

            qpixmap = QPixmap(qimage)
            self.emit("imageReceived", qpixmap)
            return qimage.copy()
class GrayScale(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.sid = QImage("smallsid.jpg")
        self.w = self.sid.width()
        self.h = self.sid.height()
        self.setGeometry(200, 200, 320, 150)
        self.setWindowTitle('Sid')
        self.show()

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        self.drawImages(painter)
        painter.end()

    def grayScale(self, image):
        for i in range(self.w):
            for j in range(self.h):
                c = image.pixel(i, j)
                gray = qGray(c)
                alpha = qAlpha(c)
                image.setPixel(i, j, qRgba(gray, gray, gray, alpha))
        return image

    def drawImages(self, painter):
        painter.drawImage(5, 15, self.sid)
        painter.drawImage(self.w + 10, 15, self.grayScale(self.sid.copy()))
def show_grabcut_info(src_image: QImage, circle_seed_item: CircleSeedItem):
    """
    :param src_image:
    :param circle_seed_item:
    :return:
    """
    seed_path = circle_seed_item.path
    seed_rect = seed_path.boundingRect().toRect()

    seed_image = src_image.copy(seed_rect)
    cv_image = qimage2cvmat(seed_image)  # type: np.ndarray
    cv_image = cv2.cvtColor(cv_image, cv2.COLOR_RGBA2RGB)

    mask = np.zeros(cv_image.shape[:2], np.uint8)
    rect = (1, 1, seed_rect.width() - 1, seed_rect.height() - 1)
    bg_model = np.zeros((1, 65), np.float64)
    fg_model = np.zeros((1, 65), np.float64)

    cv2.grabCut(cv_image, mask, rect, bg_model, fg_model, 5,
                cv2.GC_INIT_WITH_RECT)

    mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype("uint8")
    img = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY) * mask2[:, :np.newaxis]

    # 显示原始图片
    cv2.imshow("origin image", cv_image)
    plt.imshow(img)
    plt.colorbar()
    plt.show()
Beispiel #11
0
    def _splitImage(self):

        # open image
        img = QImage(str(self.baseImgPath))

        width = img.width()
        height = img.height()

        segmentWidth = width / self.cols
        segmentHeight = height / self.rows

        # hold list of image labels
        splitImageList = []
        imageRow = []

        # crop image into AxB
        for row in range(self.rows):
            for col in range(self.cols):

                x = width - (self.cols - col) * segmentWidth
                y = height - (self.rows - row) * segmentHeight

                cropped = img.copy(x, y, segmentWidth, segmentHeight)
                imageRow.append(cropped)

            splitImageList.append(imageRow.copy())
            imageRow.clear()

        return splitImageList
Beispiel #12
0
    def tpQImage(self, im, copy=False):
        if im is None:
            return QImage()

        if im.dtype == np.uint8:
            if len(im.shape) == 2:
                qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8)
                qim.setColorTable(self.gray_color_table)
                return qim.copy() if copy else qim
            elif len(im.shape) == 3:
                if im.shape[2] == 3:
                    qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888)
                    return qim.copy() if copy else qim
                elif im.shape[2] == 4:
                    qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32)
                    return qim.copy() if copy else qim
Beispiel #13
0
    def array_to_qimage(im: np.ndarray, copy=False):
        gray_color_table = [qRgb(i, i, i) for i in range(256)]
        if im is None:
            return QImage()
        if im.dtype == np.uint8:
            if len(im.shape) == 2:
                qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8)
                qim.setColorTable(gray_color_table)
                return qim.copy() if copy else qim

            elif len(im.shape) == 3:
                if im.shape[2] == 3:
                    qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888);
                    return qim.copy() if copy else qim
                elif im.shape[2] == 4:
                    qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32);
                    return qim.copy() if copy else qim
Beispiel #14
0
	def createImageButtons(self,imagePath):
		groupImg = QImage(imagePath)
		width = groupImg.width()
		height = groupImg.height()
		frameSize = width
		for i in range(0,height//width):
			img = groupImg.copy(0,i*frameSize,frameSize,frameSize);
			self.addImageButton(img)
Beispiel #15
0
 def finished(self, yttitle, ytthumbnail):
     self.label_3.setText(yttitle)
     self.textBrowser.append("Response received!")
     image = QImage()
     image.loadFromData(ytthumbnail)
     rect = QRect(0,12,120,66)
     image = image.copy(rect)
     self.label_2.setPixmap(QPixmap(image))
     self.pushButton_2.setEnabled(True)
Beispiel #16
0
 def toQImage(frame, copy=False):
     gray_color_table = [qRgb(i, i, i) for i in range(256)]
     if frame is None:
         return QImage()
 
     im = np.asarray(frame)
     if im.dtype == np.uint8:
         if len(im.shape) == 2:
             qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8)
             qim.setColorTable(gray_color_table)
             return qim.copy() if copy else qim
         elif len(im.shape) == 3:
             if im.shape[2] == 3:
                 qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888)
                 return qim.copy() if copy else qim
             elif im.shape[2] == 4:
                 qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32)
                 return qim.copy() if copy else qim
Beispiel #17
0
 def copyArea(self):  # Функция копирования области
     x = self.get_cord('Координата x',
                       'Координата левого верхнего угла по x', 0,
                       2000)  # Координата левого верхнего угла по x
     y = self.get_cord('Координата по y',
                       'Координата левого верхнего угла по y', 0,
                       2000)  # Координата левого верхнего угла по y
     w = self.get_cord("Ширина", "Ширина", 0, 2000)  # ширина
     h = self.get_cord("Высота", "Высота", 0, 2000)  # высота
     self.copyA = QImage.copy(self.image, x, y, w, h)
Beispiel #18
0
 def copy_image(self):
     image = QImage(2000, 2000, QImage.Format_RGB32)
     painter = QtGui.QPainter(image)
     text_width, text_height = PaintTextbox(painter,0,0,self.textbox_text,colors[self.textbox_color])
     painter.end()
     width = text_width + 32
     height = text_height + 32
     
     image2 = image.copy(0,0,width,height)
     QApplication.clipboard().setImage(image2)
Beispiel #19
0
def toQImage(im, copy=False):
    if im is None:
        return QImage()

    if im.dtype == np.uint8:
        if len(im.shape) == 2:
            qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8)
            qim.setColorTable(gray_color_table)
            return qim.copy() if copy else qim

        elif len(im.shape) == 3:
            if im.shape[2] == 3:
                qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888)
                return qim.copy() if copy else qim
            elif im.shape[2] == 4:
                qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32)
                return qim.copy() if copy else qim
    raise NotImplementedException('no conversion to QImage implemented for given image type (depth: %s, shape: %s)' %
                                  (im.dtype, im.shape))
def toQImage(im, copy=False):
    if im is None:
        return QImage()
    if im.dtype == np.uint8:
        if len(im.shape) == 2:
            qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0],
                         QImage.Format_Indexed8)
            qim.setColorTable(gray_color_table)
            return qim.copy() if copy else qim
        elif len(im.shape) == 3:
            if im.shape[2] == 3:
                qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0],
                             QImage.Format_RGB888)
                return qim.copy() if copy else qim
            elif im.shape[2] == 4:
                qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0],
                             QImage.Format_ARGB32)
                return qim.copy() if copy else qim
    raise RuntimeError('bad image shape: %s' % im.shape)
def toQImage(im, copy=False):
    if im is None:
        return QImage()

    if im.dtype == numpy.uint8:
        if len(im.shape) == 2:
            qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0],
                         QImage.Format_Indexed8)
            qim.setColorTable([qRgb(i, i, i) for i in range(256)])
            return qim.copy() if copy else qim

        elif len(im.shape) == 3:
            if im.shape[2] == 3:
                qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0],
                             QImage.Format_RGB888)
                return qim.copy() if copy else qim
            elif im.shape[2] == 4:
                qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0],
                             QImage.Format_ARGB32)
                return qim.copy() if copy else qim
Beispiel #22
0
def get_grayscale(data, w, h, crop=True):
    table = []
    for i in range(256):
        table.append((255 << 24) | (i << 16) | (i << 8) | i)
    image = QImage(data, w, h, QImage.Format_Indexed8)
    image.setColorTable(table)
    image = image.convertToFormat(QImage.Format_ARGB32)

    if crop:
        image = image.copy(0, 0, w - 2, h - 2)
    return image
Beispiel #23
0
 def upload(self):
     files_types = "JPG (*.jpg);;BMP(*.bmp);;PNG (*.png);;JPEG (*.jpeg)"
     fileName, _ = QFileDialog.getOpenFileName(None, 'Upload Image', './',
                                               files_types)
     self.PATH_IMG = fileName
     if fileName:
         pixmap = QPixmap(fileName)
         self.pixmap = pixmap.scaled(261, 191)
         QImage = self.pixmap.toImage()
         self.image = QImage.copy()
         self.ui.label_6.setPixmap(QPixmap.fromImage(self.image))
Beispiel #24
0
    def finished(self, yttitle,ytthumbnail):
        self.ytitle.setText(yttitle)  # Show the output to the user
        self.console.append("Response received!")
        image = QImage()
        image.loadFromData(ytthumbnail)

        rect = QRect(0,12,120,66)
        image = image.copy(rect)

        self.thumbnail.setPixmap(QPixmap(image))
        self.dwnld.setEnabled(True)
Beispiel #25
0
	def initDefaultFrames(self):
		self.bmpFrames = []
		defaultImage = QImage("..\\resource\\default.bmp")
		imageWidth = defaultImage.width()
		imageHeight = defaultImage.height()
		#判断各幀图片是否是横向排列
		isHorizontal = min(imageWidth,imageHeight) == imageHeight
		#计算幀数
		self.frameCount = imageWidth//frameWidth if isHorizontal else imageHeight//frameHeight
		for i in range(0,self.frameCount):
			pixmap = QPixmap(defaultImage.copy(i*frameWidth if isHorizontal else 0,
				0 if isHorizontal else i*frameHeight,frameWidth,frameHeight))
			eliminateBackgroundColor(pixmap)
			self.bmpFrames.append(pixmap)
Beispiel #26
0
    def font_charBmp(font, char):
        metric = QFontMetrics( font ).boundingRect( char )
        char_rect = QRect( 0, 0, metric.width(), metric.height() )
        chr_img = QImage( char_rect.width()+1, char_rect.height(), QImage.Format_Mono )
        chr_img.fill(0)

        # set img painter and draw char to bmp
        painter = QPainter( chr_img )
        painter.setPen( QPen(Qt.white) )
        painter.setFont( font )
        painter.drawText( char_rect, Qt.AlignJustify, char )
        painter.end()
        del(painter)

        # crop left / right
        x0 = 0
        x1 = char_rect.width()
        while x0 < x1 - 1:
            data_col = 0
            for col in range( char_rect.height() ):
                data_col += chr_img.pixel(x0, col) & 0x00FFFFFF
            if not data_col:
                x0 += 1
            else: break
        char_rect.setX(x0)

        while x1 > x0 + 1:
            x1 -= 1
            data_col = 0
            for col in range( char_rect.height() ):
                data_col += chr_img.pixel(x1, col) & 0x00FFFFFF
            if not data_col:
                char_rect.setWidth(x1 - x0)
            else: break

        # crop bottom
        y1 = char_rect.height()
        while y1 > 1:
            y1 -= 1
            data_row = 0
            for row in range( char_rect.width() ):
                data_row += chr_img.pixel(row, y1) & 0x00FFFFFF
            if not data_row:
                char_rect.setHeight(y1)
            else: break

        chr_img = chr_img.copy( char_rect )
        # chr_img.save( '.\\img\\0%s.bmp' % char, 'bmp' )
        return chr_img
Beispiel #27
0
def cvMatToQImage(cvmat) :
    if cvmat is None :
        return QImage()
    
    if cvmat.dtype == numpy.uint8 :
        if len(cvmat.shape) == 2:
            temp = cv2.cvtColor(cvmat, cv2.COLOR_GRAY2RGB)

        elif len(cvmat.shape) == 3:
            if cvmat.shape[2] == 3:
                temp = cvmat;
                #temp = cv2.cvtColor(cvmat, cv2.COLOR_BGR2RGB)
        qimage = QImage(temp.data, temp.shape[1], temp.shape[0], temp.strides[0], QImage.Format_RGB888);
        return qimage.copy()
    return False;
Beispiel #28
0
	def createDefAnimationView(self,movImags,spcImags):
		if not spcImags or not movImags : return
		spcImg,movImg = QImage(spcImags[0]),QImage(movImags[0])
		spcFrameSize,movFrameSize = spcImg.width(),movImg.width()
		for i in range(0,3):
			firstFrame = QPixmap(movImg.copy(0,(i+6)*movFrameSize,movFrameSize,movFrameSize))
			secondFrame = QPixmap(spcImg.copy(0,i*spcFrameSize,spcFrameSize,spcFrameSize))
			eliminateBackgroundColor(firstFrame)
			eliminateBackgroundColor(secondFrame)
			bmps = [firstFrame,secondFrame]
			self.animationPanel.addAnimationView(AnimationView(bmps))
			if i == 2:
				firstFrame = QPixmap(firstFrame.toImage().mirrored(True,False))
				secondFrame = QPixmap(secondFrame.toImage().mirrored(True,False))
				bmps = [firstFrame,secondFrame]
				self.animationPanel.addAnimationView(AnimationView(bmps))
Beispiel #29
0
class Viewer(QMainWindow):
    # Brightness.
    Gloom, Quarter, Half, ThreeQuarters, Full = range(5)

    # Brightness value map.
    brightnessValueMap = {
        Gloom: 0,
        Quarter: 64,
        Half: 128,
        ThreeQuarters: 191,
        Full: 255,
    }

    def __init__(self):
        """ Constructor initializes a default value for the brightness, creates
            the main menu entries, and constructs a central widget that contains
            enough space for images to be displayed.
        """
        super(Viewer, self).__init__()

        self.scaledImage = QImage()
        self.menuMap = {}
        self.path = ''
        self.brightness = 255

        self.setWindowTitle("QImage Color Separations")

        self.createMenus()
        self.setCentralWidget(self.createCentralWidget())

    def createMenus(self):
        """ Creates a main menu with two entries: a File menu, to allow the image
            to be selected, and a Brightness menu to allow the brightness of the
            separations to be changed.
            Initially, the Brightness menu items are disabled, but the first entry in
            the menu is checked to reflect the default brightness.
        """
        self.fileMenu = QMenu("&File", self)
        self.brightnessMenu = QMenu("&Brightness", self)

        self.openAction = self.fileMenu.addAction("&Open...")
        self.openAction.setShortcut(QKeySequence('Ctrl+O'))
        self.saveAction = self.fileMenu.addAction("&Save...")
        self.saveAction.setShortcut(QKeySequence('Ctrl+S'))
        self.saveAction.setEnabled(False)
        self.quitAction = self.fileMenu.addAction("E&xit")
        self.quitAction.setShortcut(QKeySequence('Ctrl+Q'))

        self.noBrightness = self.brightnessMenu.addAction("&0%")
        self.noBrightness.setCheckable(True)
        self.quarterBrightness = self.brightnessMenu.addAction("&25%")
        self.quarterBrightness.setCheckable(True)
        self.halfBrightness = self.brightnessMenu.addAction("&50%")
        self.halfBrightness.setCheckable(True)
        self.threeQuartersBrightness = self.brightnessMenu.addAction("&75%")
        self.threeQuartersBrightness.setCheckable(True)
        self.fullBrightness = self.brightnessMenu.addAction("&100%")
        self.fullBrightness.setCheckable(True)

        self.menuMap[self.noBrightness] = self.Gloom
        self.menuMap[self.quarterBrightness] = self.Quarter
        self.menuMap[self.halfBrightness] = self.Half
        self.menuMap[self.threeQuartersBrightness] = self.ThreeQuarters
        self.menuMap[self.fullBrightness] = self.Full

        self.currentBrightness = self.fullBrightness
        self.currentBrightness.setChecked(True)
        self.brightnessMenu.setEnabled(False)

        self.menuBar().addMenu(self.fileMenu)
        self.menuBar().addMenu(self.brightnessMenu)

        self.openAction.triggered.connect(self.chooseFile)
        self.saveAction.triggered.connect(self.saveImage)
        self.quitAction.triggered.connect(QApplication.instance().quit)
        self.brightnessMenu.triggered.connect(self.setBrightness)

    def createCentralWidget(self):
        """ Constructs a central widget for the window consisting of a two-by-two
            grid of labels, each of which will contain an image. We restrict the
            size of the labels to 256 pixels, and ensure that the window cannot
            be resized.
        """
        frame = QFrame(self)
        grid = QGridLayout(frame)
        grid.setSpacing(8)
        grid.setContentsMargins(4, 4, 4, 4)

        self.layout().setSizeConstraint(QLayout.SetFixedSize)

        labelSize = QSize(256, 256)

        self.finalWidget = FinalWidget(frame, "Final image", labelSize)

        self.cyanWidget = ScreenWidget(frame, Qt.cyan, "Cyan",
                ScreenWidget.Cyan, labelSize)
        self.magentaWidget = ScreenWidget(frame, Qt.magenta, "Magenta",
                ScreenWidget.Magenta, labelSize)
        self.yellowWidget = ScreenWidget(frame, Qt.yellow, "Yellow",
                ScreenWidget.Yellow, labelSize)

        self.cyanWidget.imageChanged.connect(self.createImage)
        self.magentaWidget.imageChanged.connect(self.createImage)
        self.yellowWidget.imageChanged.connect(self.createImage)

        grid.addWidget(self.finalWidget, 0, 0, Qt.AlignTop | Qt.AlignHCenter)
        grid.addWidget(self.cyanWidget, 0, 1, Qt.AlignTop | Qt.AlignHCenter)
        grid.addWidget(self.magentaWidget, 1, 0, Qt.AlignTop | Qt.AlignHCenter)
        grid.addWidget(self.yellowWidget, 1, 1, Qt.AlignTop | Qt.AlignHCenter)

        return frame

    def chooseFile(self):
        """ Provides a dialog window to allow the user to specify an image file.
            If a file is selected, the appropriate function is called to process
            and display it.
        """
        imageFile, _ = QFileDialog.getOpenFileName(self,
                "Choose an image file to open", self.path, "Images (*.*)")

        if imageFile != '':
            self.openImageFile(imageFile)
            self.path = imageFile

    def setBrightness(self, action):
        """ Changes the value of the brightness according to the entry selected in the
            Brightness menu. The selected entry is checked, and the previously selected
            entry is unchecked.
            The color separations are updated to use the new value for the brightness.
        """
        if action not in self.menuMap or self.scaledImage.isNull():
            return

        self.brightness = self.brightnessValueMap.get(self.menuMap[action])
        if self.brightness is None:
            return

        self.currentBrightness.setChecked(False)
        self.currentBrightness = action
        self.currentBrightness.setChecked(True)

        self.createImage()

    def openImageFile(self, imageFile):
        """ Load the image from the file given, and create four pixmaps based
            on the original image.
            The window caption is set, and the Brightness menu enabled if the image file
            can be loaded.
        """
        originalImage = QImage()

        if originalImage.load(imageFile):
            self.setWindowTitle(imageFile)
            self.saveAction.setEnabled(True)
            self.brightnessMenu.setEnabled(True)

            self.scaledImage = originalImage.scaled(256, 256, Qt.KeepAspectRatio)

            self.cyanWidget.setImage(self.scaledImage)
            self.magentaWidget.setImage(self.scaledImage)
            self.yellowWidget.setImage(self.scaledImage)
            self.createImage()
        else:
            QMessageBox.warning(self, "Cannot open file",
                    "The selected file could not be opened.",
                    QMessageBox.Cancel, QMessageBox.NoButton,
                    QMessageBox.NoButton)

    def createImage(self):
        """ Creates an image by combining the contents of the three screens
            to present a page preview.
            The image associated with each screen is separated into cyan,
            magenta, and yellow components. We add up the values for each
            component from the three screen images, and subtract the totals
            from the maximum value for each corresponding primary color.
        """
        newImage = self.scaledImage.copy()

        image1 = self.cyanWidget.image()
        image2 = self.magentaWidget.image()
        image3 = self.yellowWidget.image()
        darkness = 255 - self.brightness

        for y in range(newImage.height()):
            for x in range(newImage.width()):
                # Create three screens, using the quantities of the source CMY
                # components to determine how much of each of the inks are to
                # be put on each screen.
                p1 = image1.pixel(x, y)
                cyan1 = float(255 - qRed(p1))
                magenta1 = float(255 - qGreen(p1))
                yellow1 = float(255 - qBlue(p1))

                p2 = image2.pixel(x, y)
                cyan2 = float(255 - qRed(p2))
                magenta2 = float(255 - qGreen(p2))
                yellow2 = float(255 - qBlue(p2))

                p3 = image3.pixel(x, y)
                cyan3 = float(255 - qRed(p3))
                magenta3 = float(255 - qGreen(p3))
                yellow3 = float(255 - qBlue(p3))

                newColor = QColor(
                    max(255 - int(cyan1 + cyan2 + cyan3) - darkness, 0),
                    max(255 - int(magenta1 + magenta2 + magenta3) - darkness, 0),
                    max(255 - int(yellow1 + yellow2 + yellow3) - darkness, 0))

                newImage.setPixel(x, y, newColor.rgb())

        self.finalWidget.setPixmap(QPixmap.fromImage(newImage))

    def saveImage(self):
        """ Provides a dialog window to allow the user to save the image file.
        """
        imageFile, _ = QFileDialog.getSaveFileName(self,
                "Choose a filename to save the image", "", "Images (*.png)")

        info = QFileInfo(imageFile)

        if info.baseName() != '':
            newImageFile = QFileInfo(info.absoluteDir(),
                    info.baseName() + '.png').absoluteFilePath()

            if not self.finalWidget.pixmap().save(newImageFile, 'PNG'):
                QMessageBox.warning(self, "Cannot save file",
                        "The file could not be saved.",
                        QMessageBox.Cancel, QMessageBox.NoButton,
                        QMessageBox.NoButton)
        else:
            QMessageBox.warning(self, "Cannot save file",
                    "Please enter a valid filename.", QMessageBox.Cancel,
                    QMessageBox.NoButton, QMessageBox.NoButton)
Beispiel #30
0
class ScreenWidget(QFrame):
    # Separation.
    Cyan, Magenta, Yellow = range(3)

    convertMap = {
        Cyan: qRed,
        Magenta: qGreen,
        Yellow: qBlue,
    }

    imageChanged = pyqtSignal()

    def __init__(self, parent, initialColor, name, mask, labelSize):
        """ Initializes the paint color, the mask color (cyan, magenta, or
        yellow), connects the color selector and invert checkbox to functions,
        and creates a two-by-two grid layout.
        """
        super(ScreenWidget, self).__init__(parent)

        self.originalImage = QImage()
        self.newImage = QImage()

        self.paintColor = initialColor
        self.maskColor = mask
        self.inverted = False

        self.imageLabel = QLabel()
        self.imageLabel.setFrameShadow(QFrame.Sunken)
        self.imageLabel.setFrameShape(QFrame.StyledPanel)
        self.imageLabel.setMinimumSize(labelSize)

        self.nameLabel = QLabel(name)
        self.colorButton = QPushButton("Modify...")
        self.colorButton.setBackgroundRole(QPalette.Button)
        self.colorButton.setMinimumSize(32, 32)

        palette = QPalette(self.colorButton.palette())
        palette.setColor(QPalette.Button, initialColor)
        self.colorButton.setPalette(palette)

        self.invertButton = QPushButton("Invert")
        self.invertButton.setEnabled(False)

        self.colorButton.clicked.connect(self.setColor)
        self.invertButton.clicked.connect(self.invertImage)

        gridLayout = QGridLayout()
        gridLayout.addWidget(self.imageLabel, 0, 0, 1, 2)
        gridLayout.addWidget(self.nameLabel, 1, 0)
        gridLayout.addWidget(self.colorButton, 1, 1)
        gridLayout.addWidget(self.invertButton, 2, 1, 1, 1)
        self.setLayout(gridLayout)

    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 image(self):
        """ Returns a reference to the modified image. """
        return self.newImage

    def invertImage(self):
        """ Sets whether the amount of ink applied to the canvas is to be
            inverted (subtracted from the maximum value) before the ink is
            applied.
        """
        self.inverted = not self.inverted
        self.createImage()
        self.imageChanged.emit()

    def setColor(self):
        """ Separate the current image into cyan, magenta, and yellow
            components.  Create a representation of how each component might
            appear when applied to a blank white piece of paper.
        """
        newColor = QColorDialog.getColor(self.paintColor)

        if newColor.isValid():
            self.paintColor = newColor
            palette = QPalette(self.colorButton.palette())
            palette.setColor(QPalette.Button, self.paintColor)
            self.colorButton.setPalette(palette)
            self.createImage()
            self.imageChanged.emit()

    def setImage(self, image):
        """ Records the original image selected by the user, creates a color
            separation, and enables the invert image checkbox.
        """
        self.originalImage = image
        self.createImage()
        self.invertButton.setEnabled(True)
Beispiel #31
0
class MainWindow(QMainWindow):


    # aspect ratio 16:9
    IMAGE_COLS_MAX=640
    IMAGE_ROWS_MAX=320

    # zoom level for pixel selection
    ZOOM_X = 2

    '''def aboutWindow(self):
        about = QDialog(self)
        about.MinimumSize=(500,400)
        logoLayout = QGridLayout()
        logo = LogoWidget(about)
        text = QLabel("Jderobot 5.5.2")
        logoLayout.addWidget(logo,0,0)
        logoLayout.addWidget(text, 2, 0, Qt.AlignCenter)
        about.setLayout(logoLayout)
        about.exec_()'''

    def aboutWindow(self):
        about = QDialog(self)
        about.setFixedSize(550,350)
        about.setWindowTitle("About JdeRobot")
        logoLayout = QHBoxLayout()
        logo = LogoWidget(about)
        text = QLabel(about)
        str = "<span style='font-size:15pt; font-weight:600;'>Jderobot 5.5.2</span> <br><br>Software suite for robotics and computer vision. <br><br>You can find more info <a href='http://jderobot.org'>here</a><br><br>Github <a href='https://github.com/jderobot/jderobot.git'>repository</a>"
        text.setFixedSize(200, 350)
        text.setWordWrap(True);
        text.setTextFormat(Qt.RichText)
        text.setOpenExternalLinks(True)
        text.setText(str)
        logoLayout.addWidget(logo,1)
        logoLayout.addWidget(text, 0, Qt.AlignTop)
        about.setLayout(logoLayout)
        about.exec_()

    def closeApp(self):
        sys.exit()


    updGUI=pyqtSignal()
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        aboutAction = QAction("&About", self)
        aboutAction.setStatusTip('About JdeRobot')
        aboutAction.triggered.connect(self.aboutWindow)

        closeAction = QAction("&Quit", self)
        closeAction.setShortcut("Ctrl+Q")
        closeAction.setStatusTip('Leave The App')
        closeAction.triggered.connect(self.closeApp)

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(aboutAction)
        fileMenu.addAction(closeAction)

        

        #self.setMaximumSize(800,600)

        centralWidget = QWidget(self)
        mainLayout = QGridLayout()
        centralWidget.setLayout(mainLayout)

        imagesLayout = QVBoxLayout(self)
        controlLayout = QVBoxLayout(self)

        sliders = QGridLayout(self)

        self.image = QImage(":/images/image.png").scaled(self.IMAGE_COLS_MAX, self.IMAGE_ROWS_MAX, Qt.KeepAspectRatio)
        self.sourceImg = MyLabel(self)
        self.sourceImg.setScaledContents(True)
        self.sourceImg.setPixmap(QPixmap.fromImage(self.image))

        sourceGroupBox = QGroupBox("Source image")
        grid1 = QGridLayout()
        grid1.addWidget(self.sourceImg)
        sourceGroupBox.setLayout(grid1)
        self.sourceImg.setFixedSize(self.IMAGE_COLS_MAX, self.IMAGE_ROWS_MAX)


        self.imageF = QImage(":/images/image.png").scaled(self.IMAGE_COLS_MAX, self.IMAGE_ROWS_MAX)
        self.filterImg = QLabel(self)
        self.filterImg.setScaledContents(True)
        self.filterImg.setPixmap(QPixmap.fromImage(self.imageF))

        filterGroupBox = QGroupBox("Filtered image")
        grid2 = QGridLayout()
        grid2.addWidget(self.filterImg)
        filterGroupBox.setLayout(grid2)
        self.filterImg.setFixedSize(self.IMAGE_COLS_MAX, self.IMAGE_ROWS_MAX)


        print "size1 ", self.sourceImg.size()
        print "size2 ", self.filterImg.size()


        zoompixGroupBox = QGroupBox("Zoom x" + str(self.ZOOM_X))
        grid3 = QGridLayout()
        self.crop = MyLabel(self, True)
        self.crop.setFixedSize(200,200)

        self.tootippixel = QLabel(self)
        self.pixel = QLabel(self)
        self.pixel.setFixedSize(75,75)  
        self.rgbVal = QLabel("RGB")

        grid3.addWidget(self.crop,0,0)
        grid3.addWidget(self.rgbVal,1,0)
        grid3.addWidget(self.pixel,1,0, Qt.AlignRight)
        zoompixGroupBox.setLayout(grid3)

        slidersGroupBox = QGroupBox("Filter setup")
        controlWidget = ControlWidget(self)
        grid4 = QGridLayout()
        grid4.addWidget(controlWidget)
        slidersGroupBox.setLayout(grid4)

        imagesLayout.addWidget(sourceGroupBox,0)
        imagesLayout.addWidget(filterGroupBox,1)
        controlLayout.addWidget(zoompixGroupBox,0)
        controlLayout.addStretch(10)
        controlLayout.addWidget(slidersGroupBox,0)
        mainLayout.addLayout(imagesLayout,0,0)
        mainLayout.addLayout(controlLayout,0,1)

        '''
        mainLayout.addWidget(self.crop,0,1)
        mainLayout.addWidget(self.pixel,1,1)
        mainLayout.addWidget(self.rgbVal,1,0,1,1)'''

        self.setCentralWidget(centralWidget)

        self.updGUI.connect(self.updateGUI)

    def updateGUI(self):

        img = self.camera.getOrigImage()
        if img is not None:
            self.image = QImage(img.data, img.shape[1], img.shape[0], img.shape[1] * img.shape[2], QImage.Format_RGB888).scaled(self.IMAGE_COLS_MAX, self.IMAGE_ROWS_MAX)
            self.sourceImg.setPixmap(QPixmap.fromImage(self.image))

        filt = self.getFilterName()
        img = self.camera.getFilteredImage(filt)
        if img is not None:
            self.imageF = QImage(img.data, img.shape[1], img.shape[0], img.shape[1] * img.shape[2], QImage.Format_RGB888).scaled(self.IMAGE_COLS_MAX, self.IMAGE_ROWS_MAX)
            self.filterImg.setPixmap(QPixmap.fromImage(self.imageF))

        #print "update"
        pos = self.sourceImg.getMousePos()
        if pos != None:
            #print pos
            x_ini = (self.sourceImg.width()*self.ZOOM_X*pos.x())/self.sourceImg.width()
            y_ini = (self.sourceImg.height()*self.ZOOM_X*pos.y())/self.sourceImg.height()
            rect = QRect(x_ini-100,y_ini-100,200,200)

            #print 'orig', pos.x(), ",", pos.y(), ",", self.sourceImg.size()
            #print 'scale', x_ini, ",", y_ini

            #self.crop.setPixmap(QPixmap.fromImage(self.image.copy(rect).scaled(1000,1000)))

            #print self.sourceImg.pixmap().size()
            im2 = self.image.copy().scaled(self.sourceImg.width()*self.ZOOM_X,self.sourceImg.height()*self.ZOOM_X)
            self.crop.setPixmap(QPixmap.fromImage(im2.copy(rect)))
            #print self.crop.pixmap().size()
            
            pos = self.sourceImg.getMousePos()
            #print pos
            rgb = QColor(self.image.pixel(pos))
            self.tootippixel.setStyleSheet("background: rgb(" + str(rgb.red()) + "," + str(rgb.green()) + "," + str(rgb.blue()) + "); border: 1px solid;")
            self.tootippixel.setGeometry(pos.x(), pos.y()+52, 20,20)
            self.pixel.setStyleSheet("background: rgb(" + str(rgb.red()) + "," + str(rgb.green()) + "," + str(rgb.blue()) + ");border: 1px solid;")
            text = "XY ["+str(pos.x())+","+str(pos.y())+"]\nrgb(" + str(rgb.red()) + "," + str(rgb.green()) + "," + str(rgb.blue()) + ")"
            self.rgbVal.setText(text)

    def getCamera(self):
        return self.camera

    def setCamera(self,camera):
        print camera
        self.camera = camera

    def getFilterName(self):
        return self.filt

    def setFilterName(self,filt):
        self.filt = filt

    def closeEvent(self, event):
        self.camera.stop()
        event.accept()