Beispiel #1
0
    def on_click_sobel(self):
        self.order.setEnabled(False)
        self.cutFrec.setEnabled(False)
        self.block.setEnabled(False)
        img = cv2.imread(self.sourceImage)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        Vkernel = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
        Hkernel = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
        v, h = sobel(img, Vkernel, Hkernel)

        img_fft = np.fft.fft2(img)
        vfft, hfft = sobelfft(img_fft, Vkernel, Hkernel)

        cv2.imwrite("results/sobelV.jpg", v)
        cv2.imwrite("results/sobelH.jpg", h)
        cv2.imwrite("results/sobelVFFT.jpg", vfft)
        cv2.imwrite("results/sobelHFFT.jpg", hfft)

        pixmap = QPixmap('results/sobelV.jpg')
        pixmap2 = QPixmap('results/sobelH.jpg')
        pixmap3 = QPixmap('results/sobelVFFT.jpg')
        pixmap4 = QPixmap('results/sobelHFFT.jpg')
        pixmap = pixmap.scaled(320, 240, QtCore.Qt.KeepAspectRatio)
        pixmap2 = pixmap2.scaled(320, 240, QtCore.Qt.KeepAspectRatio)
        pixmap3 = pixmap3.scaled(320, 240, QtCore.Qt.KeepAspectRatio)
        pixmap4 = pixmap4.scaled(320, 240, QtCore.Qt.KeepAspectRatio)
        self.imgLabel2.setPixmap(pixmap)
        self.imgText2.setText("Vertical borders image domain")
        self.imgLabel3.setPixmap(pixmap2)
        self.imgText3.setText("Horizontal borders image domain")
        self.imgLabel4.setPixmap(pixmap3)
        self.imgText4.setText("Vertical borders FFT domain")
        self.imgLabel5.setPixmap(pixmap4)
        self.imgText5.setText("Horizontal borders FFT domain")
    def on_item_changed(self, current, previous):
        if not current:
            return
        crc, goodname, path, fname = current.data(Qt.UserRole)

        title = QPixmap(os.path.join(
            self.user_data_path, "title", "%s.png") % crc)
        snapshot = QPixmap(os.path.join(
            self.user_data_path, "snapshot", "%s.png") % crc)

        if title.isNull():
            title = QPixmap(":/title/%s.jpg" % crc)
        if snapshot.isNull():
            snapshot = QPixmap(":/snapshot/%s.jpg" % crc)

        if title.isNull():
            title = QPixmap(":/images/default.png")
        if snapshot.isNull():
            snapshot = QPixmap(":/images/default.png")

        if previous is not None:
            self.titleView.scene().removeItem(self.title_item)
            self.snapshotView.scene().removeItem(self.snapshot_item)

        title_pixmap = title.scaled(
            self.titleView.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
        snapshot_pixmap = snapshot.scaled(
            self.snapshotView.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)

        title_item = QGraphicsPixmapItem(title_pixmap)
        snapshot_item = QGraphicsPixmapItem(snapshot_pixmap)
        self.titleView.scene().addItem(title_item)
        self.snapshotView.scene().addItem(snapshot_item)
        self.title_item = title_item
        self.snapshot_item = snapshot_item
Beispiel #3
0
    def checkText(self):
        img = cv2.imread(self.sourceImage)
        frec = self.cutFrec.text()
        n = self.order.text()
        if frec == "" or n == "":
            None
        else:
            n = int(n)
            frec = int(frec)
            if self.low_pass_radio_button.isChecked():
                result, fft = filter(img, frec, n, 'low')
                self.imgText2.setText("Low Pass Filter")
            else:
                result, fft = filter(img, frec, n)
                self.imgText2.setText("High Pass Filter")
            cv2.imwrite("results/filter.jpg", result.real)
            cv2.imwrite("results/fourier.jpg", fft.real)

            pixmap = QPixmap('results/filter.jpg')
            pixmap2 = QPixmap('results/fourier.jpg')
            pixmap = pixmap.scaled(320, 240, QtCore.Qt.KeepAspectRatio)
            pixmap2 = pixmap2.scaled(320, 240, QtCore.Qt.KeepAspectRatio)
            self.imgLabel2.fileName ='results/filter.jpg'
            self.imgLabel3.fileName = 'results/fourier.jpg'
            self.imgLabel2.setPixmap(pixmap)
            self.imgLabel3.setPixmap(pixmap2)
            self.imgText3.setText("Center FFT")
Beispiel #4
0
def _get_pos_widget(name, backgroundColor, foregroundColor):
    label = QLabel()
    label.setAttribute(Qt.WA_TransparentForMouseEvents, True)

    pixmap = QPixmap(25 * 10, 25 * 10)
    pixmap.fill(backgroundColor)
    painter = QPainter()
    painter.begin(pixmap)
    pen = QPen(foregroundColor)
    painter.setPen(pen)
    painter.setRenderHint(QPainter.Antialiasing)
    font = QFont()
    font.setBold(True)
    font.setPixelSize(25 * 10 - 30)
    path = QPainterPath()
    path.addText(QPointF(50, 25 * 10 - 50), font, name)
    brush = QBrush(foregroundColor)
    painter.setBrush(brush)
    painter.drawPath(path)
    painter.setFont(font)
    painter.end()
    pixmap = pixmap.scaled(QSize(20, 20), Qt.KeepAspectRatio, Qt.SmoothTransformation)
    label.setPixmap(pixmap)

    spinbox = DelayedSpinBox(750)
    spinbox.setAlignment(Qt.AlignCenter)
    spinbox.setToolTip("{0} Spin Box".format(name))
    spinbox.setButtonSymbols(QAbstractSpinBox.NoButtons)
    spinbox.setMaximumHeight(20)
    font = spinbox.font()
    font.setPixelSize(14)
    spinbox.setFont(font)
    sheet = TEMPLATE.format(foregroundColor.name(), backgroundColor.name())
    spinbox.setStyleSheet(sheet)
    return label, spinbox
Beispiel #5
0
 def store_data(self, id, data):
     id = id.replace('/', '_')
     directory = ApplicationData.get('images')
     filename = os.path.join(directory, id + '.png')
     makedirs(directory)
     pixmap = QPixmap()
     if data is not None and pixmap.loadFromData(data):
         image_size = pixmap.size()
         if image_size.width() > self.max_size or image_size.height() > self.max_size:
             pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
         if imghdr.what(None, data) != 'png' or pixmap.size() != image_size:
             buffer = QBuffer()
             pixmap.save(buffer, 'png')
             data = str(buffer.data())
         with open(filename, 'wb') as f:
             f.write(data)
         icon = QIcon(pixmap)
         icon.filename = filename
         icon.content = data
         icon.content_type = 'image/png'
     else:
         unlink(filename)
         icon = None
     self.iconmap[id] = icon
     return icon
Beispiel #6
0
    def __init__(self, path, parent=None):
        super().__init__(parent)

        def commit():
            self.ADD_SIGNAL.emit(path)
            self.close()

        main_layout = QVBoxLayout()
        inner_layout = QHBoxLayout()
        name = os.path.split(path)[1]
        cover = QLabel()
        img = QPixmap(utils.get_gallery_img(path))
        cover.setPixmap(img.scaled(350, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation))
        info_lbl = QLabel("New gallery detected!\n\n{}\n\nDo you want to add it?".format(name))
        info_lbl.setWordWrap(True)
        info_lbl.setAlignment(Qt.AlignCenter)
        inner_layout.addWidget(cover)
        inner_layout.addWidget(info_lbl)
        main_layout.addLayout(inner_layout)
        main_layout.addLayout(self.generic_buttons)
        self.main_widget.setLayout(main_layout)
        self.yes_button.clicked.connect(commit)
        self.no_button.clicked.connect(self.close)
        self.adjustSize()
        self.show()
Beispiel #7
0
class Test(QMainWindow):

    def __init__(self, parent=None):
        super(Test, self).__init__(parent)
        print("I worked")

        self.label = QLabel(self)
        self.label.setText("HELLO WORLD!")

        self.gunPxMap = QPixmap('C:\\Users\\michaelh\\Desktop\\CSC Project\\Server\\src\\resources\\cannon.png')
        self.gunPxMap = self.gunPxMap.scaled(100, 100, Qt.KeepAspectRatio, Qt.SmoothTransformation)

        self.label.setPixmap(self.gunPxMap)

        self.label.setGeometry(200, 200, 150, 150)

        self.setGeometry(100, 100, 700, 700)
        self.show()
        # _thread.start_new_thread(self.rotate, ())
        for x in range (0, 50):
            self.rotate()

    def rotate(self):
        t = QTransform()

        # for x in range (0, 150):
        t.rotate(-1)
        self.label.setPixmap(self.label.pixmap().transformed(t))


        print("FINISHED")
Beispiel #8
0
    def __init__(self, data, **kwargs):
        super().__init__(**kwargs)
        self.setupUi(self)
        filename, type_, links = data

        pixmap = QPixmap()


        LOGGER.debug('load thumbnail from picflash')
        thumbnail = get(links['thumbnail'])
        pixmap.loadFromData(thumbnail.content)

        self.pixmap = pixmap.scaled(150, 150, Qt.KeepAspectRatio)
        self.label_picture.setPixmap(self.pixmap)

        filename = path.split(filename)[1]
        if len(filename) > 50:
            filename = filename[:50] + ' … ' + filename[-4:]
        self.groupBox.setTitle(filename)

        self.lineEdit_sharelink.setText(links['sharelink'])
        self.lineEdit_hotlink.setText(links['hotlink'])
        self.lineEdit_deletelink.setText(links['delete_url'])
        self.lineEdit_preview.setText(links['thumbnail'])
        self.lineEdit_bb_preview.setText(links['bb_thumbnail'])
        self.lineEdit_bb_hotlink.setText(links['bb_hotlink'])

        self.lineEdit_sharelink.setCursorPosition(0)
        self.lineEdit_hotlink.setCursorPosition(0)
        self.lineEdit_deletelink.setCursorPosition(0)
        self.lineEdit_preview.setCursorPosition(0)
        self.lineEdit_bb_hotlink.setCursorPosition(0)
        self.lineEdit_bb_preview.setCursorPosition(0)
Beispiel #9
0
 def store_file(self, id, file):
     id = id.replace('/', '_')
     directory = ApplicationData.get('images')
     filename = os.path.join(directory, id + '.png')
     if filename == os.path.normpath(file):
         return self.iconmap.get(id, None)
     makedirs(directory)
     pixmap = QPixmap()
     if file is not None and pixmap.load(file):
         if pixmap.size().width() > self.max_size or pixmap.size().height() > self.max_size:
             pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
         buffer = QBuffer()
         pixmap.save(buffer, 'png')
         data = str(buffer.data())
         with open(filename, 'wb') as f:
             f.write(data)
         icon = QIcon(pixmap)
         icon.filename = filename
         icon.content = data
         icon.content_type = 'image/png'
     else:
         unlink(filename)
         icon = None
     self.iconmap[id] = icon
     return icon
Beispiel #10
0
    def getMask(self, pixmap, x, y, w, h, shape, overlay,
                bg=QtCore.Qt.transparent, fg=QtCore.Qt.black, progressive=False):
        """Create a shape mask with the same size of pixmap.
        """
        mask = QPixmap(pixmap.width(), pixmap.height())
        mask.fill(bg)
        path = QtGui.QPainterPath()

        if progressive:
            progressive = QPixmap(pixmap.width(), pixmap.height())
            progressive.fill(QtCore.Qt.transparent)
            progressiveMask = QPixmap(self.MASK_PATH)
            progressiveMask = progressiveMask.scaled(w, h, QtCore.Qt.IgnoreAspectRatio)
            progressivePainter = QtGui.QPainter(progressive)
            progressivePainter.drawPixmap(x, y, progressiveMask)
            del progressivePainter
            fg = QtGui.QBrush(progressive)

        painter = QtGui.QPainter(mask)
        if shape == self.SHAPE_ELLIPSE:
            path.addEllipse(x, y, w, h)
            painter.fillPath(path, fg)
        elif shape == self.SHAPE_RECT:
            painter.fillRect(x, y, w, h, fg)

        painter.setCompositionMode(QtGui.QPainter.CompositionMode_SourceAtop)
        if overlay:
            painter.drawPixmap(0, 0, overlay)
        return mask
Beispiel #11
0
class MyLabel(QLabel):
    clickedk = pyqtSignal(int,int)
    def __init__(self, img=None):
        super(MyLabel, self).__init__()
        self.piece=-1 #stores piece number
        self.i=0 #stores x coordinate of this label on grid layout
        self.j=0 #stores y coordinate

        if img is not None:
            self.pixmap = QPixmap(img)
        else:
            self.pixmap = None

    def paintEvent(self, event):
        if self.pixmap is not None:
            size = self.size()
            painter = QtGui.QPainter(self)
            point = QtCore.QPoint(0, 0)
            scaledPix = self.pixmap.scaled(size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation)
            # start painting the label from left upper corner
            point.setX((size.width() - scaledPix.width()) / 2)
            point.setY((size.height() - scaledPix.height()) / 2)
            painter.drawPixmap(point, scaledPix)
        else:
            super(MyLabel, self).paintEvent(event)

    def change_pixmap(self, img):
        self.pixmap = QPixmap(img)
        self.repaint()

    def mousePressEvent(self, QMouseEvent):
        self.clickedk.emit(self.i,self.j)
Beispiel #12
0
class ButtonPixmap(QGraphicsObject):
    clicked = pyqtSignal(str,str)
    def __init__(self, pix,name=None):
        super(ButtonPixmap, self).__init__()
        self.p = QPixmap(pix)
        self.name = name

    def paint(self, painter, option, widget):
        painter.drawPixmap(QPointF(), self.p)

    def boundingRect(self):
        return QRectF(QPointF(0, 0), QSizeF(self.p.size()))

    def mousePressEvent(self, event):
        #print("鼠标按下:::",self.name)
        self.clicked.emit(self.name,"press")
        event.accept()
    def mouseReleaseEvent(self, event):
        #print("鼠标释放:::",self.name)
        self.clicked.emit(self.name,"release")
        event.accept()

    def setGeometry(self, rect):
        super(ButtonPixmap, self).setGeometry(rect)
        if rect.size().width() > self.p.size().width():
            self.p = self.p.scaled(rect.size().toSize())
        else:
            self.p = QPixmap(self.p)
Beispiel #13
0
 def set_labels(self):
     """
         全部的标签组件。
     """
     p = QPixmap()
     p.load('icons/unlogin.png')
     p2 = QPixmap()
     p2.load('icons/titleIcon.png')
     # 头部装饰start。
     self.lbe_pic.setObjectName("headpic")
     self.lbe_pic.setPixmap(p.scaled(40, 40))
     self.header_hr.setObjectName('Headerhr')
     self.header_hr.setText("推荐")
     self.header_icon.setObjectName('HIcon')
     self.header_icon.setPixmap(p2.scaled(50, 50))
     self.header_text.setObjectName('HText')
     self.header_text.setText(" Music")
Beispiel #14
0
    def comboActivated(self, text):

        # 選択した画像を表示する
        filepath = os.path.join(self.image_dir, text)
        if(os.path.isfile(filepath)):
            pixmap = QPixmap(filepath)
            pixmap = pixmap.scaled(IMAGE_WIDTH, IMAGE_HEIGHT, QtCore.Qt.KeepAspectRatio)
            self.imgLabel.setPixmap(pixmap)
Beispiel #15
0
 def set_music_cover_img(cls, res):
     img = QImage()
     img.loadFromData(res.readAll())
     pixmap = QPixmap(img)
     cls.ui.ALBUM_IMG_LABEL.setPixmap(pixmap.scaled(cls.ui.ALBUM_IMG_LABEL.size(),
                                      Qt.IgnoreAspectRatio, Qt.SmoothTransformation))
     QApplication.setWindowIcon(QIcon(pixmap))
     cls.controller.desktop_mini.content.setPixmap(pixmap)
Beispiel #16
0
 def set_labels(self):
     logger.debug("set_labels:begin")
     titlePix = QPixmap()
     titlePix.load('icons/titleIcon.png')
     self.headIcon.setPixmap(titlePix.scaled(40, 40))
     self.headTitle.setText("Wins百宝箱")
     self.topSpace.setText("")
     logger.debug("set_labels:end")
Beispiel #17
0
    def refreshInfo(self):
        #setup avata
        pixmap = QPixmap()
        pixmap.load("res/avata_mask")
        pixmap.scaled(115, 115)
        self.ui.lb_avata.setMask(pixmap.mask())
        pixmap.load(self.settings["avata"])
        self.ui.lb_avata.setPixmap(pixmap)

#        self.ui.lb_avata2.setMask(pixmap.mask())
#        pixmap.load(self.settings["avata"])
#        self.ui.lb_avata2.setPixmap(pixmap)


        #setup the name
        self.ui.lb_welcomname.setText(self.settings["name"])
        self.ui.lb_nick.setText(self.settings["name"])
Beispiel #18
0
    def init_widgets(self):

        layout = QGridLayout()

        # String -> Float
        catScore = float(self.score[0])*100
        dogScore = float(self.score[1])*100

        # Result Labels
        resultLayout = QHBoxLayout()
        resultLabel1 = QLabel('この画像は')
        resultLabel1.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        if( catScore > dogScore ):
            resultLabel2 = QLabel('猫')
        else:
            resultLabel2 = QLabel('犬')
        resultLabel2.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        font = resultLabel2.font()
        font.setPointSize(24)
        resultLabel2.setFont(font)
        resultLabel3 = QLabel('ですね?')
        resultLabel3.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        resultLayout.addWidget(resultLabel1)
        resultLayout.addWidget(resultLabel2)
        resultLayout.addWidget(resultLabel3)
        resultLayout.addStretch(10)
        layout.addLayout(resultLayout, 0, 0)

        # Tipycal Image Label
        tipImgLabel = QLabel()
        if( catScore > dogScore ):
            pixmap = QPixmap(CAT_IMAGE)
        else:
            pixmap = QPixmap(DOG_IMAGE)
        pixmap = pixmap.scaled(IMAGE_WIDTH, IMAGE_HEIGHT, QtCore.Qt.KeepAspectRatio)
        tipImgLabel.setPixmap(pixmap)
        layout.addWidget(tipImgLabel, 1, 0)

        # Score Labels
        scoreLayout = QVBoxLayout()
        dogScoreLabel = QLabel('cat={0:.1f}%'.format(catScore))
        catScoreLabel = QLabel('dog={0:.1f}%'.format(dogScore))
        dogScoreLabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        catScoreLabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        scoreLayout.addWidget(dogScoreLabel)
        scoreLayout.addWidget(catScoreLabel)
        scoreLayout.addStretch(10)
        layout.addLayout(scoreLayout, 1, 1, 1, 1)

        # Close Button
        closeButton = QPushButton('閉じる')
        closeButton.clicked.connect(self.close)
        layout.addWidget(closeButton, 2, 1)

        # Title
        self.setWindowTitle('画像識別')

        self.setLayout(layout)
Beispiel #19
0
	def initUI(self):
		self.btn = []
		self.notif_lbl = []
		self.tag_lbl = []
		self.nFrames =[]
		self.d_ = False

		for i in range(0,len(self.obj.notif)):
			pixmap=QPixmap(self.obj.tagDict[self.obj.notif[i].tag])
			pixmap = pixmap.scaled(45, 45)
			self.tag_lbl.append(QLabel(self))
			self.tag_lbl[i].setPixmap(pixmap)

		for i1 in range(0,len(self.obj.notif)):
			self.notif_lbl.append(QLabel(self))
			self.notif_lbl[i1].setScaledContents(False)
			self.notif_lbl[i1].setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
			self.notif_lbl[i1].setText(self.obj.notif[i1].notif_text)
			self.notif_lbl[i1].setObjectName("nlbl")
			self.btn.append(QPushButton('Get Link'))
			self.btn[i1].setObjectName("btn")

		for i2 in range(0,len(self.obj.notif)):
			self.nFrames.append(notifyFrames(self.notif_lbl[i2],self.tag_lbl[i2],self.btn[i2]))
			tag = self.obj.notif[i2].tag
			if tag ==2 or tag==3 or tag==4:
				self.nFrames[i2].setObjectName('nFrameOdd')
			else:
				self.nFrames[i2].setObjectName('nFrameEven')

		self.widget = QWidget(self)
		self.vbox = QVBoxLayout()

		for index, frame in enumerate(self.nFrames):
			self.vbox.addWidget(frame)

		if len(self.nFrames)<4:
			self.dframe = QFrame()
			self.dframe.setObjectName('nFrameDummy')
			self.vbox.addWidget(self.dframe)
			self.d_ = True

		self.vbox.setContentsMargins(0,0,0,0)
		self.vbox.setSpacing(3)

		self.widget.setLayout(self.vbox)
		self.scroll = QScrollArea(self)
		self.scroll.setWidget(self.widget)
		self.scroll.setWidgetResizable(True)
		self.scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
		self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)

		vbox1 = QVBoxLayout()
		vbox1.setContentsMargins(0,0,0,0)
		vbox1.setSpacing(0)

		vbox1.addWidget(self.scroll)
		self.setLayout(vbox1)
Beispiel #20
0
    def cambiar_imagen(self):
        self.imagen_actual += 1
        if self.imagen_actual >= 12:
            self.imagen_actual = 0
        self.opcion_actual = self.nombres[self.imagen_actual]

        pixmap = QPixmap("Imgs/{0}.png".format(self.opcion_actual))
        pixmap = pixmap.scaled(120, 120)
        self.imagen_principal.setPixmap(pixmap)
Beispiel #21
0
 def set_login_label_avatar(cls, res):
     img = QImage()
     img.loadFromData(res.readAll())
     pixmap = QPixmap(img)
     if cls.controller.state["is_login"]:
         cls.ui.LOGIN_BTN.close()
     cls.ui.AVATAR_LABEL.show()
     width = cls.ui.AVATAR_LABEL.size().width()
     cls.ui.AVATAR_LABEL.setPixmap(pixmap.scaled(width, width, Qt.IgnoreAspectRatio, Qt.SmoothTransformation))
Beispiel #22
0
 def render(self, painter):
     pixmap = QPixmap(self.view.size())
     pixPainter = QPainter()
     pixPainter.begin(pixmap)
     self.view.render(pixPainter)
     pixPainter.end()
     scaledPixmap = pixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
     drawRect = QRect(self.rect.topLeft(), scaledPixmap.size())
     painter.drawPixmap(drawRect, scaledPixmap)
Beispiel #23
0
 def plotsurface(self):
     [zvalue,r,z] =self.getzernikevalue()
     picname = "surface.png"
     Z = opticspy.zernike.Coefficient(zvalue)
     fig = Z.zernikesurface(savefig = True)
     fig.savefig(picname, dpi=60, bbox_inches='tight')
     newsurface = QPixmap(picname)
     newsurface = newsurface.scaled(524,396)
     self.lbl_pixmap1.setPixmap(newsurface)
Beispiel #24
0
 def plotpsf(self):
     [zvalue,r,z] =self.getzernikevalue()
     picname = "psf.png"
     Z = opticspy.zernike.Coefficient(zvalue)
     fig = Z.psf(r=r, z=z)
     fig.savefig(picname, dpi=60, bbox_inches='tight')
     newmap = QPixmap(picname)
     newmap = newmap.scaled(524,396)
     self.lbl_pixmap2.setPixmap(newmap)
Beispiel #25
0
 def plottg(self):
     [zvalue,r,z] =self.getzernikevalue()
     picname = "interferogram.png"
     Z = opticspy.zernike.Coefficient(zvalue)
     fig = Z.twyman_green()
     fig.savefig(picname, dpi=60, bbox_inches='tight')
     newmap = QPixmap(picname)
     newmap = newmap.scaled(524,396)
     self.lbl_pixmap2.setPixmap(newmap)
Beispiel #26
0
 def setImageFileSrc(self, filepath, width=None, height=None):
     pic = QPixmap(filepath)
     self.pixmap = pic
     if width is not None and height is not None:
         pic = pic.scaled(
             width, height, Qt.KeepAspectRatio
         )
     self.setPixmap(pic)
     # 修改鼠标样式
     self.setCursor(Qt.PointingHandCursor)
class ImageWidget(QWidget):
    def __init__(self, imagePath, parent):
        super(ImageWidget, self).__init__(parent)
        self.picture = QPixmap(imagePath)
        size = self.picture.size()
        self.picture = self.picture.scaled(size.width() / 2, size.height() / 2, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(0, 0, self.picture)
Beispiel #28
0
 def __init__(self, parent=None, size=16):
     super(SearchIcon, self).__init__(parent)
     self.setFocusPolicy(Qt.NoFocus)
     self.setVisible(True)
     self.setMinimumSize(size+2, size+2)
     pixmap = QPixmap()
     if pixmap.load(Resources.get("icons/search.svg")):
         self.icon = pixmap.scaled(size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
     else:
         self.icon = None
    def add_image(self, v_box):
        image = QPixmap(Images.rotate.value)
        image = image.scaled(32, 32, Qt.KeepAspectRatio, Qt.SmoothTransformation)
        imageLabel = QLabel()
        imageLabel.setPixmap(image)

        button_shortcuts = QPushButton("teste")
        button_shortcuts.clicked.connect(self.change_button_name)

        v_box.addRow(imageLabel, button_shortcuts)
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        try:
            pixmap = QPixmap(self.path + '\\' + self.listimg[self.flag])
            scaredPixmap = pixmap.scaled(530, 600, aspectRatioMode=Qt.KeepAspectRatio)
            self.img.setPixmap(scaredPixmap)
            self.img.resize(scaredPixmap.width(),scaredPixmap.height())
        except Exception as e:
            self.flag = self.flag + 1
            pixmap = QPixmap(self.path + '\\' + self.listimg[self.flag])
            scaredPixmap = pixmap.scaled(530, 600, aspectRatioMode=Qt.KeepAspectRatio)
            self.img.setPixmap(scaredPixmap)
            self.img.resize(scaredPixmap.width(),scaredPixmap.height())

        self.pos_button.clicked.connect(self.positive_img) # 积极地 1
        self.neg_button.clicked.connect(self.negative_img) # 消极的 -1
        self.mid_button.clicked.connect(self.middle_img) # 中性的 0
        self.unknown_button.clicked.connect(self.unknown_img) # 不会定的 不记录
Beispiel #31
0
class MainWindow(QWidget):
    data = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setStyleSheet(
            "QLabel{color:rgb(100,100,100,250);font-weight:bold;font-family:Roman times;}"
            "QLabel:hover{color:rgb(100,100,100,120);}")
        self.setWindowTitle("2048小游戏")
        self.resize(500, 500)
        self.focusPolicy()
        self.setWindowIcon(QIcon("../res/icon.jpg"))
        self.font = QFont()
        self.fingerEvent = controller.FingerEvent.FingerEvent()
        self.pxmap = QPixmap()
        self.rdfile = RWFile.RWFile()
        self.cachefile = "../cache/2048.2048"
        self.rdfile.cleanfile(self.cachefile)
        self.initUi()
        QMessageBox.about(
            self, "About Py2048",
            "这是一个由Python开发的小程序,作者是张明宝,这个游戏中,请使用上下左右按键来模拟手指的上下左右滑动,键盘的ESC按键可以重新开始游戏,F10按键可依将您本次的游戏记录存档,祝您游戏愉快!"
        )

    def initUi(self):
        mainlayout = QGridLayout()
        self.setLayout(mainlayout)
        self.lbs = []
        pos = [(i, j) for i in range(0, 4) for j in range(0, 4)]
        for position in zip(pos):
            lb = QLabel()
            qf = QFont()
            qf.setPixelSize(50)
            qf.setBold(True)
            lb.setAlignment(Qt.AlignCenter)
            lb.setFont(qf)
            lb.setAutoFillBackground(True)
            qp = QPalette()
            qp.setColor(QPalette.Window, Qt.darkBlue)
            lb.setPalette(qp)
            lb.setMinimumHeight(100)
            lb.setMaximumHeight(100)
            lb.setMaximumWidth(100)
            lb.setMinimumWidth(100)
            self.lbs.append(lb)
            mainlayout.addWidget(lb, *position[0])
        self.setdatasource()

    def keyPressEvent(self, event):
        try:
            if event.key() == Qt.Key_F10:
                self.selectwritefile()
            if event.key() == Qt.Key_Escape:
                self.initdata()
                self.setdatasource()
            if event.key() == Qt.Key_Up:  # up
                self.data = self.fingerEvent.fingerup(self.data)
                self.setdatasource()
                # print(event.key,"up")
            if event.key() == Qt.Key_Down:  # down
                self.data = self.fingerEvent.fingerdown(self.data)
                self.setdatasource()
                # print(event.key, "down")
            if event.key() == Qt.Key_Left:  # left
                self.data = self.fingerEvent.fingerleft(self.data)
                self.setdatasource()
                # print(event.key, "left")
            if event.key() == Qt.Key_Right:  # right
                self.data = self.fingerEvent.fingerright(self.data)
                self.setdatasource()
            del event
            if self.data == self.fingerEvent.fingerup(
                    self.data) and self.data == self.fingerEvent.fingerdown(
                        self.data
                    ) and self.data == self.fingerEvent.fingerleft(
                        self.data
                    ) and self.data == self.fingerEvent.fingerright(self.data):
                print("游戏结束")
                self.showsavemessagebox(
                    "游戏提示框",
                    "<font size='13' color='red' face='隶书'>游戏已结束,是否保存游戏记录?</font>"
                )
        except Exception as e:
            print(e.__str__())

    def showmessagebox(self, title, msg):
        qm = QMessageBox()
        reply = qm.information(self, title, msg,
                               QMessageBox.No | QMessageBox.Yes)
        if reply == QMessageBox.Yes:
            self.initdata()
            self.setdatasource()
        else:
            self.close()

    def showsavemessagebox(self, title, msg):
        qm = QMessageBox()
        reply = qm.information(self, title, msg,
                               QMessageBox.No | QMessageBox.Yes)
        if reply == QMessageBox.Yes:
            self.selectwritefile()
        self.showmessagebox(
            "游戏提示框", "<font size='13' face='微软雅黑'>游戏结束,您要再来一局吗?</font>")

    def initdata(self):
        self.rdfile.cleanfile(self.cachefile)
        self.data = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

    def setdatasource(self):
        self.rdfile.writecachefile(self.cachefile, self.data.__str__())
        pos = 0
        for i in range(0, 4):
            for j in range(0, 4):

                if self.data[i][j] <= 262144:
                    self.pxmap.load("../res/" + str(self.data[i][j]) + ".png")
                    qs = QSize(100, 100)
                    self.lbs[pos].setPixmap(self.pxmap.scaled(qs))
                else:
                    self.showsavemessagebox(
                        "游戏提示框",
                        "<font size='13' color='red' face='隶书'>请收下我的膝盖,\
                                            您的智商已经超出了我的游戏范围!是否保存游戏记录?</font>")

                pos = pos + 1

    def selectreadfile(self):
        file = QFileDialog.getSaveFileName(self, "选取文件", "C:/",
                                           "Text Files(*.2048)")

    def selectwritefile(self):
        try:
            file = QFileDialog.getSaveFileName(self, "选取文件", "C:/",
                                               "Text Files(*.2048)")
            self.rdfile.cleanfile(file[0])
            for line in self.rdfile.readfile(self.cachefile):
                self.rdfile.writefile(file[0], line.__str__().strip("\n"))
        except Exception as e:
            print(e.__str__())
Beispiel #32
0
class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'Make Answer'
        self.left = 200
        self.top = 200
        self.width = 640
        self.height = 480
        self.init_ui()
        self.conn = pymysql.connect(host=HOST,
                                    user='******',
                                    password='',
                                    db='data',
                                    charset='utf8')
        self.curs = self.conn.cursor()

    def init_ui(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # Create widget
        self.label = QLabel(self)
        self.label2 = QLabel(self)

        # Create textbox
        self.textbox = QLineEdit(self)
        self.textbox.resize(280, 40)
        self.textbox.move(
            (self.size().width() - self.textbox.size().width()) // 2, 400)
        self.textbox.returnPressed.connect(self.search_slot)

        self.next_image()
        self.show()

    def next_image(self):
        self.image = next(image_generator)
        self.pixmap = QPixmap('./data/' + self.image)
        self.pixmap = self.pixmap.scaled(self.pixmap.size().width() * 2,
                                         self.pixmap.size().height() * 2)
        self.label.setPixmap(self.pixmap)
        self.label.move(
            (self.size().width() - self.pixmap.size().width()) // 2, 200)

        image = cv2.imread('./data/' + self.image, cv2.IMREAD_UNCHANGED)
        img = alpha_to_gray(image)

        kernel = np.ones((3, 3), np.uint8)
        img = cv2.dilate(img, kernel, iterations=1)
        kernel = np.ones((1, 1), np.uint8)
        img = cv2.dilate(img, kernel, iterations=1)
        img = cv2.medianBlur(img, 3)
        kernel = np.ones((4, 4), np.uint8)
        img = cv2.erode(img, kernel, iterations=1)

        height, width = img.shape
        qImg = QImage(img.data, width, height, width, QImage.Format_Grayscale8)
        self.pixmap2 = QPixmap.fromImage(qImg)
        self.pixmap2 = self.pixmap2.scaled(self.pixmap2.size().width() * 2,
                                           self.pixmap2.size().height() * 2)
        self.label2.setPixmap(self.pixmap2)
        self.label2.move(
            (self.size().width() - self.pixmap2.size().width()) // 2, 50)

        self.textbox.setText(ocr(img))

    @pyqtSlot()
    def search_slot(self):
        text = self.textbox.text()
        text = text.upper()
        if eng.match(text):
            sql = """INSERT INTO data.answer(data_no, answer)
                     VALUES (%s, %s)"""
            self.curs.execute(sql, (self.image.split('.')[0], text))
            self.conn.commit()
            os.remove('./data/' + self.image)
            self.next_image()

    def closeEvent(self, event):
        # do stuff
        self.conn.close()
        event.accept()  # let the window close
Beispiel #33
0
class GUI(QWidget):
	imageW = 800
	imageH = 800
	imageScale = 1.5
	currentPos = QPoint()
	lastPos = QPoint()

	roix1 = 0
	roiy1 = 0
	roix2 = 0
	roiy2 = 0

	showPeople = False
	showCaps = False
	showMotions = False
	showSteam = False

	drawing = False

	def __init__(self):
		super().__init__()
		self.initUI()

	def initUI(self):
		self.lastPoint = QPoint()

		self.redLight = QPixmap("redLight.png")
		self.redLight = self.redLight.scaled(30, 30)
		self.grayLight = QPixmap("grayLight.png")
		self.grayLight = self.grayLight.scaled(30, 30)

		layout = QHBoxLayout(self)

		rightBlockLayout = QVBoxLayout(self)

		self.imageLabel = QLabel()
		self.image = QPixmap("image.png")
		self.currentImage = self.image
		

		indicatorsGroupBox = QGroupBox("Индикация", self)
		indicatorsGroupBox.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Maximum)
		indicatorsGroupBox.setMinimumSize(280, 200)

		indicatorsGroupLayout = QGridLayout(indicatorsGroupBox)

		self.peopleIndicator = QLabel()
		self.peopleIndicator.setPixmap(self.grayLight)
		self.capsIndicator = QLabel()
		self.capsIndicator.setPixmap(self.grayLight)
		self.motionsIndicator = QLabel()
		self.motionsIndicator.setPixmap(self.grayLight)
		self.steamIndicator = QLabel()
		self.steamIndicator.setPixmap(self.grayLight)

		indicatorsGroupLayout.setColumnStretch(0, 2)
		indicatorsGroupLayout.setColumnStretch(1, 1)
		indicatorsGroupLayout.addWidget(QLabel("Обнаружены люди"), 0, 0)
		indicatorsGroupLayout.addWidget(self.peopleIndicator, 0, 1)
		indicatorsGroupLayout.addWidget(QLabel("Сотрудник без каски"), 1, 0)
		indicatorsGroupLayout.addWidget(self.capsIndicator, 1, 1)
		indicatorsGroupLayout.addWidget(QLabel("Обнаружено движения"), 2, 0)
		indicatorsGroupLayout.addWidget(self.motionsIndicator, 2, 1)
		indicatorsGroupLayout.addWidget(QLabel("Обнаружен пар/дым"), 3, 0)
		indicatorsGroupLayout.addWidget(self.steamIndicator, 3, 1)

		indicatorsGroupBox.setLayout(indicatorsGroupLayout)

		buttonsGroupBox = QGroupBox("Настройки", self)
		buttonsGroupBox.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Maximum)
		buttonsGroupBox.setMinimumSize(280, 200)

		buttonsGroupLayout = QVBoxLayout(buttonsGroupBox)

		peopleButton = QPushButton("Детекция людей", self)
		peopleButton.clicked[bool].connect(self.peopleButtonEvent)
		peopleButton.setCheckable(True)
		peopleButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)

		capsButton = QPushButton("Детекция людей без касок", self)
		capsButton.clicked[bool].connect(self.capsButtonEvent)
		capsButton.setCheckable(True)
		capsButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)

		motionsButton = QPushButton("Детекция движения", self)
		motionsButton.clicked[bool].connect(self.motionsButtonEvent)
		motionsButton.setCheckable(True)
		motionsButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)

		steamButton = QPushButton("Детекция пара/дыма", self)
		steamButton.clicked[bool].connect(self.steamButtonEvent)
		steamButton.setCheckable(True)
		steamButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)

		buttonsGroupLayout.addWidget(peopleButton)
		buttonsGroupLayout.addWidget(capsButton)
		buttonsGroupLayout.addWidget(motionsButton)
		buttonsGroupLayout.addWidget(steamButton)

		buttonsGroupBox.setLayout(buttonsGroupLayout)

		rightBlockLayout.addWidget(indicatorsGroupBox)
		rightBlockLayout.addWidget(buttonsGroupBox)
		spacer = QSpacerItem(1, 400)
		rightBlockLayout.addItem(spacer)
		layout.addWidget(self.imageLabel)
		layout.addLayout(rightBlockLayout)

		self.setFixedSize(self.imageW + 300, self.imageH)
		self.setWindowTitle('Помошник оператора')
		self.setLayout(layout)
		self.show()


	def peopleButtonEvent(self, pressed):
		self.showPeople = pressed
		if not pressed:
			self.setPeopleAlert(False)

	def capsButtonEvent(self, pressed):
		self.showCaps = pressed
		if not pressed:
			self.setCapsAlert(False)

	def motionsButtonEvent(self, pressed):
		self.showMotions = pressed
		if pressed == False:
			self.setMotionsAlert(False)

	def steamButtonEvent(self, pressed):
		self.showSteam = pressed
		if not pressed:
			self.setSteamAlert(False)

	def mousePressEvent(self, e):
		if e.buttons() == Qt.LeftButton:
			self.update()
			self.drawing = True
			self.currentPos = e.pos()
			self.lastPos = e.pos()

	def mouseReleaseEvent(self, e):
		self.update()
		self.drawing = False
		self.roix2 = e.pos().x()
		self.roiy2 = e.pos().y()
		self.roix1 = self.lastPos.x()
		self.roiy1 = self.lastPos.y()

	def paintEvent(self, event):
		painter = QPainter() 
		painter.begin(self) 
		painter.drawPixmap(self.imageLabel.rect(), self.currentImage) 
		painter.end() 

	def mouseMoveEvent(self, event):
		if self.drawing: 
			self.currentPos = event.pos()
			self.currentImage = QPixmap(self.image)
			painter = QPainter() 
			painter.begin(self.currentImage) 
			painter.setPen(QPen(Qt.green, 3, Qt.SolidLine)) 
			painter.drawRect(self.lastPos.x() * self.imageScale, self.lastPos.y() * self.imageScale, (event.pos().x() - self.lastPos.x()) * self.imageScale, (event.pos().y() - self.lastPos.y()) * self.imageScale) 
			painter.end()
			self.update()


	#Переключение индикаторов		
	def setPeopleAlert(self, alert):
		if alert:
			self.peopleIndicator.setPixmap(self.redLight)
		else:
			self.peopleIndicator.setPixmap(self.grayLight)

	def setCapsAlert(self, alert):
		if alert:
			self.capsIndicator.setPixmap(self.redLight)
		else:
			self.capsIndicator.setPixmap(self.grayLight)

	def setMotionsAlert(self, alert):
		if alert:
			self.motionsIndicator.setPixmap(self.redLight)
		else:
			self.motionsIndicator.setPixmap(self.grayLight)

	def setSteamAlert(self, alert):
		if alert:
			self.steamIndicator.setPixmap(self.redLight)
		else:
			self.steamIndicator.setPixmap(self.grayLight)	

	#Используется для получения координат области интереса (ROI)		
	def getX1(self):
		return int(self.roix1 * self.imageScale)

	def getY1(self):
		return int(self.roiy1 * self.imageScale)

	def getX2(self):
		return int(self.roix2 * self.imageScale)

	def getY2(self):
		return int(self.roiy2 * self.imageScale)

	#Получение конфигураций	
	def isShowPeople(self):
		return self.showPeople

	def isShowCaps(self):
		return self.showCaps

	def isShowMotions(self):
		return self.showMotions

	def isShowSteam(self):
		return self.showSteam
    
    #Метод для передачи изображения на вывод
	def setImage(self, imageData): 
		image = QImage(imageData, imageData.shape[1], imageData.shape[0], QImage.Format_RGB888) 
		self.image = QPixmap.fromImage(image)
		self.image = self.image.scaled(imageData.shape[1], imageData.shape[0])
		self.currentImage = QPixmap(self.image)
		self.update()
		self.imageW = int(imageData.shape[1] / self.imageScale)
		self.imageH = int(imageData.shape[0] / self.imageScale)
		self.setFixedSize(self.imageW + 300, self.imageH)
		painter = QPainter() 
		painter.begin(self.currentImage) 
		painter.setPen(QPen(Qt.green, 3, Qt.SolidLine)) 
		painter.drawRect(self.lastPos.x() * self.imageScale, self.lastPos.y() * self.imageScale, (self.currentPos.x() - self.lastPos.x()) * self.imageScale, (self.currentPos.y() - self.lastPos.y()) * self.imageScale) 
		painter.end()

	def closeEvent(self, event):

		reply = QMessageBox.question(self, 'Message',
			"Are you sure to quit?", QMessageBox.Yes |
			QMessageBox.No, QMessageBox.No)

		if reply == QMessageBox.Yes:
			event.accept()
		else:
			event.ignore()
Beispiel #34
0
class LogInWidget(QWidget):
    """ QWidget that takes in email, password, and allow user to submit.
	Parameters: Parent Window, Database connection
	Shows email input, password input, and a submit button. When submit is clicked,
	the Widget calls a validator function in parent window of type LogInWindow.
	"""
    def __init__(self, DBconnect, *args, **kwargs):
        """ Initializes object's database connection, email field, password field, and submit connection """
        super().__init__(*args, **kwargs)
        self.DBconnect = DBconnect
        # tried to make custom signal, uneccesary
        #self.submittedSignal = clickSubmit()
        #self.submittedSignal.submitted.connect(self.parentWindow.submitClicked(string, string))

        self.mainLayout = QVBoxLayout(self)
        self.formLayout = QFormLayout()
        self.emailLayout = QHBoxLayout()
        self.passwordLayout = QHBoxLayout()

        self.email = QLineEdit()
        self.password = QLineEdit()
        self.password.setEchoMode(QLineEdit.Password)

        self.submit = QPushButton("Log In")
        self.newuser = QPushButton("New User")
        # SHOULD BE? self.submit.clicked.connect(partial(self.parentWindow.submitClicked, self.email.text(), self.password.text()))

        self.formLayout.addRow("Email", self.email)
        self.formLayout.addRow("Password", self.password)

        widg_width = self.frameGeometry().width()
        pic_width = int((widg_width * .25))

        self.logo_pic = QPixmap('images/house_logo.png')
        self.logo_pic = self.logo_pic.scaled(pic_width, pic_width,
                                             Qt.KeepAspectRatio)
        self.logo = QLabel()
        self.logo.setPixmap(self.logo_pic)

        self.mainLayout.addWidget(self.logo, alignment=Qt.AlignHCenter)
        self.mainLayout.addLayout(self.formLayout)

        self.buttonLayout = QHBoxLayout()  # alligns the buttons horizontally
        self.buttonLayout.addWidget(self.submit)
        self.buttonLayout.addWidget(self.newuser)

        self.mainLayout.addLayout(self.buttonLayout)
        # self.mainLayout.addWidget(self.newuser, alignment=Qt.AlignHCenter)

    def checkEmailValid(self, text):
        """ Checks if given email is valid (not related to DB) through checking
		domain and checking syntax
		Parameters: email (String)
		Output: (True if valid False if invalid (Bool), email if valid and error if not valid (String)) (Tuple)
		"""
        print("Email passed in checkEmailValid: ", text)
        try:
            v = validate_email(text)  # validate and get info
            return (True, v["email"])  # replace with normalized form
        except EmailNotValidError as e:
            # email is not valid, exception message is human-readable
            print(str(e))
            return (False, str(e))

    def logInValid(self, in_email, in_pwd):
        """ Checks with database through the db connection if the email and password exist
		Parameters: email (String) password (String)
		Output: (True if exists False if does not exist (Bool), userId (Int)) (Tuple)

		"""
        email = in_email.text()
        pwd = in_pwd.text()
        print("logInValid email:", email)
        emailValidity = self.checkEmailValid(email)
        if emailValidity[0] == True:
            checkUserInfo = self.DBconnect.checkUser(email, pwd)
            print("Does it exist: ", checkUserInfo)
            if checkUserInfo[0]:
                return (checkUserInfo)
            else:
                self.password.clear()
                self.email.clear()
                self.email.setPlaceholderText("No account found")
                self.password.setPlaceholderText("Try again")
                return ((False, None))

        else:
            self.password.clear()
            self.email.clear()
            self.email.setPlaceholderText("Invalid email")
            print(emailValidity[1])
            return ((False, None))
Beispiel #35
0
    def init_ui(self):
        url = self.video

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        self.videoWidget = QVideoWidget()
        self.videoWidget.setFullScreen(False)
        self.videoWidget.keyPressEvent = self.exitFullScreen

        # self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(url))) # For Local files Only
        self.mediaPlayer.setMedia(QMediaContent(QUrl(url))) # For URLs
        self.mediaPlayer.play()
        self.playState = True

        self.playButton = QPushButton()
        self.playButton.setEnabled(True)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
        self.playButton.clicked.connect(self.play)


        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.setTracking(False)
        print("Tracking: ", self.positionSlider.hasTracking())
        # self.positionSlider.sliderPressed.connect(self.pause)
        self.positionSlider.sliderReleased.connect(self.sliderReleased)
        # self.positionSlider.sliderMoved.connect(self.setPosition)
        self.positionSlider.valueChanged.connect(self.setPosition)

        self.length = QLabel()

        image = QPixmap("./images/fullscreen.png")
        image = image.scaled(30, 30)

        # fullScreen = QLabel()
        # fullScreen.setFixedHeight(image.height())
        # fullScreen.setFixedWidth(image.width())
        # fullScreen.setPixmap(image)
        # # fullScreen.setStyleSheet("border: 1px solid black")
        # fullScreen.mousePressEvent = self.fullscreen

        fullScreen = QPushButton()
        fullScreen.setIcon(QIcon(image))
        fullScreen.setIconSize(QSize(30, 30))
        fullScreen.setFixedWidth(image.width())
        fullScreen.setFixedHeight(image.height())
        fullScreen.setStyleSheet("border: none")
        fullScreen.clicked.connect(self.fullscreen)

        '''
            Error Label not used yet.
        '''
        self.errorLabel = QLabel()
        self.errorLabel.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Maximum)



        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)
        controlLayout.addWidget(self.length)
        controlLayout.addWidget(fullScreen)

        layout = QVBoxLayout()
        layout.addWidget(self.videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.errorLabel)

        wid = QWidget(self)
        self.setCentralWidget(wid)

        wid.setLayout(layout)

        self.setWindowTitle("Video Display from URL")
        self.resize(400, 400)

        self.mediaPlayer.setVideoOutput(self.videoWidget)
        # self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        # self.mediaPlayer.durationChanged.connect(self.durationChanged)
        # self.mediaPlayer.error.connect(self.handleError)
        self.mediaPlayer.mediaStatusChanged.connect(self.mediaStatusChanged)

        self.show()
        self.center()
Beispiel #36
0
class SegmenationTool(QMainWindow):
    #Переопределяем конструктор класса:
    def __init__(self, master=None):
        QMainWindow.__init__(self, master)
        self.flag = False
        self.img0 = []
        self.mask_inv = []
        self.initUI()

    #Создание макета проекта:
    def initUI(self):
        self.file_mk_dir = ""
        self.file_dir = ""
        self.filenames = []
        self.file_index = 0
        self.show_markup = True
        self.condition = False
        self.leftclickedflag = False
        self.rightclickedflag = False

        self.mainwidget = QWidget(self)
        self.setCentralWidget(self.mainwidget)

        #Создание обозначения кнопок:
        self.SelectFileButton = QPushButton("File...")
        self.SelectImDirButton = QPushButton("Image Dir...")
        self.SelectMkDirButton = QPushButton("Markup Dir...")
        self.RecognizeHSVButton = QPushButton("Segment(HSV)")
        #self.RecognizeFCNButton = QPushButton("Segment(FCN)")
        self.FindBlobsButton = QPushButton("Detect")
        #self.CheckPathButton = QPushButton("Check Path")#CheckNumObjectsPath
        self.SaveButton = QPushButton("Save")
        self.GotoButton = QPushButton("Go to image id:")
        self.le_img_id = QLineEdit()

        self.LabelCoef = QLabel('мм in 1 pix:')
        self.le_Scale_Coef = QLineEdit()

        self.LabelRadius = QLabel("Brush radius ('+','-'):")
        self.value_Radius = QLineEdit('10')
        self.radius = int(self.value_Radius.text())

        self.imageLabel = QLabel()

        self.defaultImWidth = 1500
        self.defaultImHeight = 750

        self.imageLabel.setMinimumWidth(self.defaultImWidth)
        self.imageLabel.setMaximumWidth(self.defaultImWidth)
        self.imageLabel.setMinimumHeight(self.defaultImHeight)
        self.imageLabel.setMaximumHeight(self.defaultImHeight)
        #Связь кнопок с методами их исполнения:
        self.RecognizeHSVButton.clicked.connect(self.startHSVButtonClicked)

        self.FindBlobsButton.clicked.connect(self.FindBlobsEasyButtonClicked)
        self.SelectFileButton.clicked.connect(self.selectFileButtonClicked)
        self.SelectImDirButton.clicked.connect(self.selectImDirButtonClicked)
        self.SelectMkDirButton.clicked.connect(self.selectMkDirButtonClicked)
        self.SaveButton.clicked.connect(self.saveButtonClicked)
        self.GotoButton.clicked.connect(self.GotoButtonClicked)

        #self.CheckPathButton.clicked.connect(self.CheckNumObjectsPath)

        self.hbox = QHBoxLayout()

        #Создание формы кнопок:
        self.hbox.addWidget(self.SelectFileButton)
        self.hbox.addWidget(self.SelectImDirButton)
        self.hbox.addWidget(self.SelectMkDirButton)
        self.hbox.addWidget(self.RecognizeHSVButton)
        #self.hbox.addWidget(self.RecognizeFCNButton)
        self.hbox.addWidget(self.FindBlobsButton)
        self.hbox.addWidget(self.SaveButton)
        self.hbox.addWidget(self.GotoButton)
        self.hbox.addWidget(self.le_img_id)

        #self.hbox.addWidget(self.CheckPathButton)

        self.hbox.addWidget(self.LabelCoef)
        self.hbox.addWidget(self.le_Scale_Coef)

        self.vcontrolboxwidget = QGroupBox()

        self.vcontrolbox = QVBoxLayout()

        self.LeftImButton = QPushButton("< Prev ('a')")
        self.RightImButton = QPushButton("> Next ('d')")
        self.SaveImButton = QPushButton(" Save ('s')")
        self.HideButton = QPushButton(" Hide Mkp ('w')")
        self.SLeftImButton = QPushButton("< Save+Prev ('q')")
        self.SRightImButton = QPushButton("> Save+ Next ('e')")

        self.RightImButton.clicked.connect(self.NextButtonClicked)
        self.LeftImButton.clicked.connect(self.PrevButtonClicked)
        self.SaveImButton.clicked.connect(self.saveButtonClicked)
        self.HideButton.clicked.connect(self.HideButtonClicked)
        self.SLeftImButton.clicked.connect(self.SLeftImButtonClicked)
        self.SRightImButton.clicked.connect(self.SRightImButtonClicked)

        self.vcontrolbox.addWidget(self.SRightImButton)
        self.vcontrolbox.addWidget(self.SLeftImButton)
        self.vcontrolbox.addWidget(self.RightImButton)
        self.vcontrolbox.addWidget(self.LeftImButton)
        self.vcontrolbox.addWidget(self.SaveImButton)
        self.vcontrolbox.addWidget(self.HideButton)

        self.vcontrolbox.addWidget(self.LabelRadius)
        self.vcontrolbox.addWidget(self.value_Radius)

        self.brush_group = QGroupBox('Brush type')
        self.vbrushbox = QVBoxLayout()
        #vbrushbox.setMouseTracking(True)
        self.radio_brush_circle = QRadioButton('Circle')
        self.radio_brush_rect = QRadioButton('Rectangle')

        self.vbrushbox.addWidget(self.radio_brush_circle)
        self.vbrushbox.addWidget(self.radio_brush_rect)
        self.radio_brush_circle.toggled.connect(self.rbtnbrush)
        self.radio_brush_rect.toggled.connect(self.rbtnbrush)
        self.radio_brush_circle.setChecked(True)
        self.brush_type = 0
        #vbrushbox.addStretch(1)
        self.brush_group.setLayout(self.vbrushbox)
        self.vcontrolbox.addWidget(self.brush_group)

        self.radio_group = QGroupBox('Objects')
        self.rb_array = []
        index = 0
        self.vgroupbox = QVBoxLayout()
        for name in obj_names:
            self.rb_array.append(QRadioButton(name))
            self.vgroupbox.addWidget(self.rb_array[index])
            self.rb_array[index].toggled.connect(self.rbtnstate)
            index += 1
        self.obj_index = 0  #global object index
        self.rb_array[self.obj_index].setChecked(True)
        self.vgroupbox.addStretch(1)
        self.radio_group.setLayout(self.vgroupbox)
        self.radio_group.setMouseTracking(True)
        #self.vcontrolbox.addLayout(self.vgroupbox)
        self.vcontrolbox.addWidget(self.radio_group)
        #self.vcontrolboxwidget.setLayout(self.vcontrolbox)

        #Создание формы приложения:
        self.pixmap = QPixmap()

        self.mainhbox = QHBoxLayout()

        self.vbox = QVBoxLayout()
        self.vbox.addLayout(self.hbox)
        self.vbox.addWidget(self.imageLabel)
        #Создание начального вида окна приложения:
        self.setGeometry(300, 300, 700, 500)
        self.setWindowTitle('Multiclass segmentation tool v.1.0')

        # Лэйблы с описаниями назначения ползунков
        self.LabelHue = QLabel('Hue (H)')
        self.LabelSaturation = QLabel('Saturation (S)')
        self.LabelValue = QLabel('Value (V)')

        self.Coef = 1
        self.le_Scale_Coef.returnPressed.connect(self.valueChangePress)
        self.le_Scale_Coef.setText(str(self.Coef))

        # Создание строк ввода диапазонов и привязка их к методу
        self.value_line_1 = QLineEdit()
        self.value_line_1.returnPressed.connect(self.valueChangePress)
        self.value_line_2 = QLineEdit()
        self.value_line_2.returnPressed.connect(self.valueChangePress)
        self.value_line_3 = QLineEdit()
        self.value_line_3.returnPressed.connect(self.valueChangePress)
        self.value_line_4 = QLineEdit()
        self.value_line_4.returnPressed.connect(self.valueChangePress)
        self.value_line_5 = QLineEdit()
        self.value_line_5.returnPressed.connect(self.valueChangePress)
        self.value_line_6 = QLineEdit()
        self.value_line_6.returnPressed.connect(self.valueChangePress)

        #Создание ползунков:
        self.slider_HueMin = QSlider(Qt.Horizontal, self)
        self.slider_HueMax = QSlider(Qt.Horizontal, self)
        self.slider_SaturationMin = QSlider(Qt.Horizontal, self)
        self.slider_SaturationMax = QSlider(Qt.Horizontal, self)
        self.slider_ValueMin = QSlider(Qt.Horizontal, self)
        self.slider_ValueMax = QSlider(Qt.Horizontal, self)

        self.h1box = QHBoxLayout()
        self.h1box.addWidget(self.LabelHue)
        self.h1box.addWidget(self.value_line_1)
        #self.vbox.addLayout(self.h1box)
        #Ползунку задаются минимальное и максимальное значения шкалы:
        self.slider_HueMin.setMinimum(0)
        self.slider_HueMin.setMaximum(255)
        #Шаг ползунка:
        self.slider_HueMin.setTickInterval(1)
        #Установка начальной позици ползунка:
        self.HueMin = 0
        self.slider_HueMin.setValue(self.HueMin)
        #Связь ползунка с методом, в котором будет  изменятся  значение, которое  нужно изменять:
        self.slider_HueMin.valueChanged.connect(self.valueChange)
        #Установка длины ползунка:
        self.slider_HueMin.setMinimumWidth(200)
        #self.vbox.addWidget(self.slider_HueMin)
        self.h1box.addWidget(self.slider_HueMin)
        self.value_line_1.setText(str(self.HueMin))
        self.value_line_1.setMinimumWidth(25)

        self.h1box.addWidget(self.value_line_2)

        self.slider_HueMax.setMinimum(0)
        self.slider_HueMax.setMaximum(255)
        self.slider_HueMax.setTickInterval(1)
        self.HueMax = 255
        self.slider_HueMax.setValue(self.HueMax)
        self.slider_HueMax.valueChanged.connect(self.valueChange)
        self.slider_HueMax.setMinimumWidth(200)
        self.h1box.addWidget(self.slider_HueMax)
        self.value_line_2.setText(str(self.HueMax))
        self.value_line_2.setMinimumWidth(25)

        self.vbox.addLayout(self.h1box)

        self.h2box = QHBoxLayout()
        self.h2box.addWidget(self.LabelSaturation)
        self.h2box.addWidget(self.value_line_3)

        self.slider_SaturationMin.setMinimum(0)
        self.slider_SaturationMin.setMaximum(255)
        self.slider_SaturationMin.setTickInterval(1)
        self.SaturationMin = 0
        self.slider_SaturationMin.setValue(self.SaturationMin)
        self.slider_SaturationMin.valueChanged.connect(self.valueChange)
        self.slider_SaturationMin.setMinimumWidth(200)
        self.h2box.addWidget(self.slider_SaturationMin)
        self.value_line_3.setText(str(self.SaturationMin))
        self.value_line_3.setMinimumWidth(25)

        self.h2box.addWidget(self.value_line_4)

        self.slider_SaturationMax.setMinimum(0)
        self.slider_SaturationMax.setMaximum(255)
        self.slider_SaturationMax.setTickInterval(1)
        self.SaturationMax = 40
        self.slider_SaturationMax.setValue(self.SaturationMax)
        self.slider_SaturationMax.valueChanged.connect(self.valueChange)
        self.slider_SaturationMax.setMinimumWidth(200)
        self.h2box.addWidget(self.slider_SaturationMax)
        self.value_line_4.setText(str(self.SaturationMax))
        self.value_line_4.setMinimumWidth(25)

        self.vbox.addLayout(self.h2box)

        self.h3box = QHBoxLayout()
        self.h3box.addWidget(self.LabelValue)
        self.h3box.addWidget(self.value_line_5)

        self.slider_ValueMin.setMinimum(0)
        self.slider_ValueMin.setMaximum(255)
        self.slider_ValueMin.setTickInterval(1)
        self.ValueMin = 5
        self.slider_ValueMin.setValue(self.ValueMin)
        self.slider_ValueMin.valueChanged.connect(self.valueChange)
        self.slider_ValueMin.setMinimumWidth(200)
        self.h3box.addWidget(self.slider_ValueMin)
        self.value_line_5.setText(str(self.ValueMin))
        self.value_line_5.setMinimumWidth(25)

        self.h3box.addWidget(self.value_line_6)

        self.slider_ValueMax.setMinimum(0)
        self.slider_ValueMax.setMaximum(255)
        self.slider_ValueMax.setTickInterval(1)
        self.ValueMax = 140
        self.slider_ValueMax.setValue(self.ValueMax)
        self.slider_ValueMax.valueChanged.connect(self.valueChange)
        self.slider_ValueMax.setMinimumWidth(200)
        self.h3box.addWidget(self.slider_ValueMax)
        self.vbox.setSpacing(10)
        self.value_line_6.setText(str(self.ValueMax))
        self.value_line_6.setMinimumWidth(25)

        self.vbox.addLayout(self.h3box)

        self.mainhbox.addLayout(self.vbox)
        self.mainhbox.addLayout(self.vcontrolbox)

        self.mainwidget.setLayout(self.mainhbox)
        self.setMouseTracking(True)

    def setMouseTracking(self, flag):
        def recursive_set(parent):
            for child in parent.findChildren(QObject):
                try:
                    child.setMouseTracking(flag)
                    #print(str(child))
                except:
                    pass
                recursive_set(child)

        QWidget.setMouseTracking(self, flag)
        recursive_set(self)

    def check_and_repaint_cursor(self, e):
        condition, w, h, sc = self.check_paint_field(e, self.flag, self.img0,
                                                     self.imageLabel)
        self.repaint_cursor(sc)

    def repaint_cursor(self, scale_coef):
        if (not self.condition):
            self.draw_cursor_default()
        else:
            radius = int(int(self.value_Radius.text()) * scale_coef)
            r = obj_palete[self.obj_index][0]
            g = obj_palete[self.obj_index][1]
            b = obj_palete[self.obj_index][2]
            if (self.radio_brush_circle.isChecked()):
                self.draw_cursor_circle(radius, (b, g, r, 128))
            else:
                self.draw_cursor_rectangle(radius, (b, g, r, 128))
        return

    def draw_cursor_circle(self, radius, color):
        diameter = 2 * radius
        self.m_LPixmap = QPixmap(diameter, diameter)
        self.m_LPixmap.fill(Qt.transparent)
        self.painter = QPainter(self.m_LPixmap)
        self.brush_color = QColor(color[0], color[1], color[2], color[3])
        self.painter.setPen(Qt.NoPen)
        self.painter.setBrush(self.brush_color)
        self.painter.drawEllipse(0, 0, diameter, diameter)
        self.m_cursor = QCursor(self.m_LPixmap)
        self.setCursor(self.m_cursor)
        return

    def draw_cursor_rectangle(self, radius, color):
        width = 2 * radius
        self.m_LPixmap = QPixmap(width, width)
        self.m_LPixmap.fill(Qt.transparent)
        self.painter = QPainter(self.m_LPixmap)
        self.brush_color = QColor(color[0], color[1], color[2], color[3])
        self.painter.setPen(Qt.NoPen)
        self.painter.setBrush(self.brush_color)
        self.painter.drawRect(0, 0, width, width)
        self.m_cursor = QCursor(self.m_LPixmap)
        self.setCursor(self.m_cursor)
        return

    def draw_cursor_default(self):
        m_cursor = QCursor()
        self.setCursor(m_cursor)
        return

    def rbtnstate(self):
        radiobutton = self.sender()

        if radiobutton.isChecked():
            index = 0
            for name in obj_names:
                if (radiobutton.text() == name):
                    self.obj_index = index
                index += 1
            self.statusBar().showMessage('Selected index ' +
                                         str(self.obj_index))

    def rbtnbrush(self):
        radiobutton = self.sender()

        if radiobutton.isChecked():
            index = 0
            if (radiobutton.text() == 'Circle'):
                self.brush_type = 0
            elif (radiobutton.text() == 'Rectangle'):
                self.brush_type = 1
            else:
                self.brush_type = 0
            self.statusBar().showMessage('Brush type ' + str(self.brush_type))

        #Метод открытия изображения:
    def selectFileButtonClicked(self):
        self.image_file = QFileDialog.getOpenFileName(
            None, 'Открыть файл',
            'c:/Computer_Vision/MultiClass_Segmentation_Tool/Test_samples',
            'JPG Files(*.jpg);; PNG Files(*.png)')[0]
        if (self.image_file != ''):
            self.load_image_file(self.image_file)

    #Метод выбора папки с изображениями:
    def selectImDirButtonClicked(self):
        self.file_dir = str(
            QFileDialog.getExistingDirectory(
                self, "Select directory with images",
                "D:/Datasets/Students_monitoring"))
        if (self.file_dir != ''):
            self.file_mk_dir = self.file_dir + '/markup'

            self.white_list_formats = {'png', 'jpg', 'jpeg', 'bmp'}
            self.filenames = []

            for filename in sorted(os.listdir(self.file_dir)):
                is_valid = False
                for extension in self.white_list_formats:
                    if filename.lower().endswith('.' + extension):
                        is_valid = True
                        break
                if is_valid:
                    self.filenames.append(filename)

            if (len(self.filenames) == 0):
                return

            self.image_file = self.file_dir + '/' + self.filenames[0]
            self.setWindowTitle('Multiclass segmentation tool v.1.0' +
                                ' | File: ' + self.filenames[0])
            self.le_img_id.setText(str(0))

            self.load_image_file(self.image_file)

            message = "Images directory is successfully selected: " + self.file_dir
            self.statusBar().showMessage(message)

    def selectMkDirButtonClicked(self):
        self.file_mk_dir = str(
            QFileDialog.getExistingDirectory(
                self, "Select Markup Directory",
                "D:/Datasets/Students_monitoring"))
        message = "Markup directory is successfully selected: " + self.file_mk_dir
        self.statusBar().showMessage(message)

    #Метод обработки изображения с помощью HSV:
    def startHSVButtonClicked(self):
        if self.pixmap.isNull() != True:
            self.img0 = cv2.imread(self.image_file, 1)
            self.img = cv2.GaussianBlur(self.img0, (5, 5), 5)
            #Перевод изображения из BGR в цветовую систему HSV:
            self.hsv = cv2.cvtColor(self.img, cv2.COLOR_BGR2HSV)
            #Задание диапозона поиска цветовых пятен:
            self.lower_range = np.array(
                [self.HueMin, self.SaturationMin, self.ValueMin],
                dtype=np.uint8)
            self.upper_range = np.array(
                [self.HueMax, self.SaturationMax, self.ValueMax],
                dtype=np.uint8)
            #Маска изображения, выделяющая пятно:
            self.mask = cv2.inRange(self.hsv, self.lower_range,
                                    self.upper_range)
            #Инверсия полученной маски:
            #self.mask_inv = cv2.bitwise_not(self.mask)
            self.mask_inv = self.binary_to_color_with_pallete(
                self.mask, obj_palete[self.obj_index])

            #Наложение инвертированной маски на изображение:
            self.rez = (self.img0 * (self.mask_inv / 255)).astype(np.uint8)

            self.print_image_on_label(self.rez, self.imageLabel)
            self.flag = True
        else:
            pass

    def CheckNumObjectsPath(self):
        self.file_index = 0
        ind = 0
        output_file = open('statistics\\folder_statistics_ethalon.txt', 'w')
        out_text = "n_obj\tfilename\n"
        output_file.write(out_text)

        for ind in range(len(self.filenames)):
            n_objects = self.FindBlobsEasyButtonClicked()
            out_text = "%d\t%s\n" % (n_objects,
                                     self.filenames[self.file_index])
            output_file.write(out_text)
            self.NextButtonClicked()
        output_file.close()

    def FindBlobsEasyButtonClicked(self):
        if (self.pixmap.isNull() != True and len(self.mask_inv) != 0):

            # Цвет текста координат:
            self.box_color = (0, 255, 0)

            self.Coef = float(self.le_Scale_Coef.text())
            # label image regions
            self.mask = (self.mask_inv == obj_palete[self.obj_index])
            label_image = label(self.mask[:, :, 0])

            self.rez = (self.img0 * (self.mask_inv / 255)).astype(np.uint8)
            n_all_regions = len(regionprops(label_image))
            ind = 1
            im_width = self.rez.shape[0]
            for region in regionprops(label_image):
                # skip small images
                # draw rectangle around segmented coins
                minr, minc, maxr, maxc = region.bbox

                S = (maxc - minc) * (maxr - minr)

                if (S < 200):
                    continue

                cv2.rectangle(self.rez, (minc, minr), (maxc, maxr),
                              self.box_color, 1)
                cv2.putText(
                    self.rez, "%d: %d %d %d" %
                    (ind, S, region.area /
                     (self.Coef * self.Coef), region.perimeter / self.Coef),
                    (int(minc + 3), int(minr + 22)), cv2.FONT_HERSHEY_PLAIN,
                    1.4, self.box_color, 1)

                ind += 1

            self.print_image_on_label(self.rez, self.imageLabel)
            return ind
        else:
            return 0

    # Метод, в котором изменяется значение отдельных ползунков и связывается с цветом со строкой ввода диапазона:
    def valueChange(self):
        self.HueMin = self.slider_HueMin.value()
        self.value_line_1.setText(str(self.HueMin))
        self.HueMax = self.slider_HueMax.value()
        self.value_line_2.setText(str(self.HueMax))
        self.SaturationMin = self.slider_SaturationMin.value()
        self.value_line_3.setText(str(self.SaturationMin))
        self.SaturationMax = self.slider_SaturationMax.value()
        self.value_line_4.setText(str(self.SaturationMax))
        self.ValueMin = self.slider_ValueMin.value()
        self.value_line_5.setText(str(self.ValueMin))
        self.ValueMax = self.slider_ValueMax.value()
        self.value_line_6.setText(str(self.ValueMax))

    def valueChangePress(self):
        #Изменяет значение диапазона цвета на введённое в строку ввода
        old = self.Coef
        # Считывается новое значение
        new = self.le_Scale_Coef.text()
        # Выполняется проверка на корректность введённого значения
        rez = self.chekForSymb(old, new)
        # Присваивается более коректное значение
        self.Coef = rez
        # Выводится значение в строку ввода
        self.le_Scale_Coef.setText(str(rez))

        # Запоминается прежнее значение на случай ввода недопустимого значения
        old = self.HueMin
        # Считывается новое значение
        new = self.value_line_1.text()
        # Выполняется проверка на корректность введённого значения
        rez = self.chekForSymb(old, new)
        # Присваивается более коректное значение
        self.HueMin = rez
        # Ползунок устанавливается на новое или старое значение
        self.slider_HueMin.setValue(rez)
        # Выводится значение в строку ввода
        self.value_line_1.setText(str(rez))

        old = self.HueMax
        new = self.value_line_2.text()
        rez = self.chekForSymb(old, new)
        self.HueMax = rez
        self.slider_HueMax.setValue(rez)
        self.value_line_2.setText(str(rez))

        old = self.SaturationMin
        new = self.value_line_3.text()
        rez = self.chekForSymb(old, new)
        self.SaturationMin = rez
        self.slider_SaturationMin.setValue(rez)
        self.value_line_3.setText(str(rez))

        old = self.SaturationMax
        new = self.value_line_4.text()
        rez = self.chekForSymb(old, new)
        self.SaturationMax = rez
        self.slider_SaturationMax.setValue(rez)
        self.value_line_4.setText(str(rez))

        old = self.ValueMin
        new = self.value_line_5.text()
        rez = self.chekForSymb(old, new)
        self.ValueMin = rez
        self.slider_ValueMin.setValue(rez)
        self.value_line_5.setText(str(rez))

        old = self.ValueMax
        new = self.value_line_6.text()
        rez = self.chekForSymb(old, new)
        self.ValueMax = rez
        self.slider_ValueMax.setValue(rez)
        self.value_line_6.setText(str(rez))

    def chekForSymb(self, old, new):
        #Возвращает число new в случае его корректности или же old в случае некорректности числа new
        # Запускается генератор множества
        consts = {str(i) for i in range(10)}
        # Перебираются все элементы в new
        for el in new:
            # Если число содержит символы, не являющиеся цифрами, завершается проверка числа на корректность
            if el not in consts:
                # На выход функции подаётся прежнее значение, и функция завершается
                return old
                exit()
        if int(new) < 255:
            return int(new)
        else:
            return 255

    #Метод сохранения изображения:
    def saveButtonClicked(self):
        if (self.flag):
            #File = QFileDialog.getSaveFileName(self, 'Сохранить как', '', 'PNG Files(*.png);; JPG Files(*.jpg)')[0]
            #if File != '':
            res_fname, res_extension = os.path.splitext(self.image_file)
            res_fname = os.path.basename(res_fname)
            res_dirname = os.path.dirname(self.image_file)
            os.makedirs(res_dirname + '/masked', exist_ok=True)
            os.makedirs(res_dirname + '/markup', exist_ok=True)
            target_fname_mask = res_dirname + '/masked/' + res_fname + res_extension
            #target_fname_markup = res_dirname + '/markup/' + res_fname + res_extension
            target_fname_markup = self.file_mk_dir + '/' + res_fname + '.bmp'

            #self.mask = cv2.bitwise_not(self.mask_inv)

            cv2.imwrite(target_fname_markup, self.mask_inv)
            cv2.imwrite(target_fname_mask, self.rez)
            message = "Saved files successfully in folders: " + self.file_mk_dir + ' and ' + res_dirname + '/masked'
            self.statusBar().showMessage(message)

    #Метод присвоения левой кнопке мыши метода рисования:
    def mousePressEvent(self, e):
        message = ""
        if e.button() == Qt.LeftButton:
            self.leftclickedflag = True
            self.rightclickedflag = False
            message = "Left click"
        if e.button() == Qt.RightButton:
            self.leftclickedflag = False
            self.rightclickedflag = True
            message = "Right click"
        self.statusBar().showMessage(message)

    def mouseReleaseEvent(self, e):
        message = ""
        if e.button() == Qt.LeftButton:
            self.leftclickedflag = False
            message = "Left click release"
        if e.button() == Qt.RightButton:
            self.rightclickedflag = False
            message = "Right click release"
        self.statusBar().showMessage(message)

    def grayscale_to_color(self, grayscale_im):
        im_reshaped = grayscale_im.reshape(
            (grayscale_im.shape[0], grayscale_im.shape[1], 1))
        im_out = np.append(im_reshaped, im_reshaped, axis=2)
        im_out = np.append(im_out, im_reshaped, axis=2)
        return im_out

    def binary_to_color_with_pallete(self, binary_im, pallete_color):
        im_reshaped = binary_im.reshape(
            (binary_im.shape[0], binary_im.shape[1], 1)) / 255
        im_out = np.append(im_reshaped * (255 - pallete_color[0]),
                           im_reshaped * (255 - pallete_color[1]),
                           axis=2)
        im_out = np.append(im_out,
                           im_reshaped * (255 - pallete_color[2]),
                           axis=2)
        im_out = 255 - im_out
        return im_out

    #Метод рисования дефектов:
    def mouseMoveEvent(self, e):
        coords = e.pos()
        old_condition = self.condition
        self.condition = self.is_in_field(e, self.imageLabel)
        self.statusBar().showMessage(
            str(coords.x()) + ' ' + str(coords.y()) + ' ' +
            str(self.condition))
        if (old_condition != self.condition and self.flag):
            sc = self.calc_scale_coef(self.img0, self.imageLabel)
            self.repaint_cursor(sc)

        if self.leftclickedflag:
            condition, w, h, sc = self.check_paint_field(
                e, self.flag, self.img0, self.imageLabel)
            if (condition):
                self.mask_inv = self.draw_ellipse_on_mask(
                    e, self.mask_inv, w, h, obj_palete[self.obj_index],
                    int(self.value_Radius.text()), self.brush_type)
                self.rez = (self.img0 * (self.mask_inv / 255)).astype(np.uint8)
                #self.rez = cv2.bitwise_and(self.img0, self.img0, mask=self.mask_inv)
                self.print_image_on_label(self.rez, self.imageLabel)
                message = "Left move: True"
            else:
                message = "Left move: False"

            self.statusBar().showMessage(message)

        if self.rightclickedflag:
            condition, w, h, sc = self.check_paint_field(
                e, self.flag, self.img0, self.imageLabel)
            if (condition):
                self.mask_inv = self.draw_ellipse_on_mask(
                    e, self.mask_inv, w, h, (255, 255, 255),
                    int(self.value_Radius.text()), self.brush_type)
                self.rez = (self.img0 * (self.mask_inv / 255)).astype(np.uint8)
                self.print_image_on_label(self.rez, self.imageLabel)
                message = "Right move: True"
            else:
                message = "Right move: False"
            self.statusBar().showMessage(message)

    #Метод создания кисти для рисования:
    def ellips(self, e):
        self.paint = QPainter(self.qimg)
        self.paint.setBrush(QColor('black'))
        coords = e.pos()
        geom = self.imageLabel.geometry()
        coords_ed = coords - QPoint(geom.x(), geom.y())
        self.paint.drawEllipse(coords_ed, 10, 10)
        self.update()

    # Метод создания кисти для рисования:
    def draw_ellipse_on_mask(self, e, mask_img, label_real_w, label_real_h,
                             draw_color, radius, brush_type):
        coords = e.pos()
        geom = self.imageLabel.geometry()
        coords_ed = coords - QPoint(geom.x(), geom.y())

        mask_height = mask_img.shape[0]
        mask_width = mask_img.shape[1]
        pixmap_height = label_real_h
        pixmap_width = label_real_w

        real_x = int(coords_ed.x() * mask_width / pixmap_width)
        real_y = int(coords_ed.y() * mask_height / pixmap_height)
        if (brush_type == 0):
            cv2.circle(mask_img, (real_x, real_y), radius, draw_color, -1)
        else:
            cv2.rectangle(mask_img, (real_x - radius, real_y - radius),
                          (real_x + radius, real_y + radius), draw_color, -1)
        return mask_img

    def print_image_on_label(self, img, label_widget):
        height, width, channel = img.shape
        bytesPerLine = channel * width
        rgb_cvimage = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        q_img = QImage(rgb_cvimage.data, width, height, bytesPerLine,
                       QImage.Format_RGB888)

        self.pixmap = QPixmap(q_img)

        w_p = self.pixmap.width()
        h_p = self.pixmap.height()

        if (w_p > h_p):
            label_new_width = self.defaultImWidth
            label_new_height = h_p * self.defaultImWidth / w_p
        else:
            label_new_width = w_p * self.defaultImHeight / h_p
            label_new_height = self.defaultImHeight

        label_widget.setMinimumWidth(label_new_width)
        label_widget.setMaximumWidth(label_new_width)
        label_widget.setMinimumHeight(label_new_height)
        label_widget.setMaximumHeight(label_new_height)

        # Вычисляем ширину окна изображения
        w = label_widget.width()
        # Вычисляем высоту окна изображения
        h = label_widget.height()
        self.pixmap = self.pixmap.scaled(w, h, Qt.KeepAspectRatio,
                                         Qt.SmoothTransformation)
        label_widget.setPixmap(self.pixmap)

        return True

    def check_paint_field(self, e, rec_flag, img, label_widget):
        if (rec_flag):
            img_height, img_width, img_channel = img.shape
            geom = label_widget.geometry()

            scale_x_w = geom.width()
            scale_y_h = geom.height()

            scale_ratio_img = img_height / img_width
            scale_ratio_label = geom.height() / geom.width()
            if (scale_ratio_img > scale_ratio_label):
                scale_x_w = geom.height() / scale_ratio_img
                scale_coef = geom.height() / img_height
            if (scale_ratio_img <= scale_ratio_label):
                scale_y_h = geom.width() * scale_ratio_img
                scale_coef = geom.width() / img_width
            coords = e.pos()

            x_max = geom.x() + scale_x_w
            y_max = geom.y() + scale_y_h
            condition_label = coords.x() > geom.x() and coords.x(
            ) < x_max and coords.y() > geom.y() and coords.y() < y_max
            if (condition_label):
                return True, scale_x_w, scale_y_h, scale_coef

        return False, 0, 0, 0

    def is_in_field(self, e, label_widget):
        geom = label_widget.geometry()

        coords = e.pos()

        x_max = geom.x() + geom.width()
        y_max = geom.y() + geom.height()
        condition_label = coords.x() > geom.x() and coords.x(
        ) < x_max and coords.y() > geom.y() and coords.y() < y_max
        if (condition_label):
            return True
        return False

    def calc_scale_coef(self, img, label_widget):
        img_height, img_width, img_channel = img.shape
        scale_coef = 1
        geom = label_widget.geometry()

        scale_x_w = geom.width()
        scale_y_h = geom.height()
        if (img_width != 0 and img_height != 0):
            scale_ratio_img = img_height / img_width
            scale_ratio_label = geom.height() / geom.width()
            if (scale_ratio_img > scale_ratio_label):
                scale_coef = geom.height() / img_height
            if (scale_ratio_img <= scale_ratio_label):
                scale_coef = geom.width() / img_width

        return scale_coef

    def NextButtonClicked(self):
        if (len(self.filenames) > self.file_index + 1):
            self.file_index += 1
            self.image_file = self.file_dir + '/' + self.filenames[
                self.file_index]
            self.setWindowTitle('Multiclass segmentation tool v.1.0' +
                                ' | File: ' + self.filenames[self.file_index])
            self.le_img_id.setText(str(self.file_index))
            self.load_image_file(self.image_file)
            self.statusBar().showMessage('> next image')
        else:
            self.statusBar().showMessage('no next image')

    def PrevButtonClicked(self):
        if (self.file_index > 0):
            self.file_index -= 1
            self.image_file = self.file_dir + '/' + self.filenames[
                self.file_index]
            self.setWindowTitle('Multiclass segmentation tool v.1.0' +
                                ' |  File: ' + self.filenames[self.file_index])
            self.le_img_id.setText(str(self.file_index))
            self.load_image_file(self.image_file)
            self.statusBar().showMessage('< previous image')
        else:
            self.statusBar().showMessage('no previous image')

    def GotoButtonClicked(self):
        self.file_index = int(self.le_img_id.text())
        if (self.file_index >= 0 and len(self.filenames) > self.file_index):
            self.image_file = self.file_dir + '/' + self.filenames[
                self.file_index]
            self.setWindowTitle('Multiclass segmentation tool v.1.0' +
                                ' |  File: ' + self.filenames[self.file_index])
            self.le_img_id.setText(str(self.file_index))
            self.load_image_file(self.image_file)
            self.statusBar().showMessage('find image')
        else:
            self.statusBar().showMessage('no image')

    #Загрузка изображения на форму
    def load_image_file(self, file_name):

        self.img0 = cv2.imread(file_name, 1)
        if (type(self.img0) is np.ndarray):
            res_fname, res_extension = os.path.splitext(self.image_file)
            res_fname = os.path.basename(res_fname)
            mask_path = self.file_mk_dir + '/' + res_fname + '.bmp'
            self.mask_inv = cv2.imread(mask_path, 1)
            if (type(self.mask_inv) is np.ndarray):
                self.rez = (self.img0 * (self.mask_inv / 255)).astype(np.uint8)
            else:
                self.rez = self.img0
                self.mask_inv = np.ones(self.img0.shape, dtype='uint8') * 255

            self.flag = True
            # self.rez = cv2.bitwise_and(self.img0, self.img0, mask=self.mask_inv)
            self.print_image_on_label(self.rez, self.imageLabel)
        else:
            self.flag = False

    # Загрузка изображения на форму
    def load_just_image_file(self, file_name):
        self.img0 = cv2.imread(file_name, 1)
        if (type(self.img0) is np.ndarray):
            self.rez = self.img0
            self.print_image_on_label(self.rez, self.imageLabel)
            self.flag = True
        else:
            self.flag = False

    def HideButtonClicked(self):
        if self.show_markup:
            self.show_markup = False
            self.flag = False
            self.load_just_image_file(self.image_file)
        else:
            self.show_markup = True
            self.flag = True
            self.load_image_file(self.image_file)

    def SLeftImButtonClicked(self):
        self.saveButtonClicked()
        self.PrevButtonClicked()

    def SRightImButtonClicked(self):
        self.saveButtonClicked()
        self.NextButtonClicked()

    def IncreaseRadius(self, step):
        if (self.radius < 1000 and self.flag):
            self.radius += step
            self.value_Radius.setText(str(self.radius))
            sc = self.calc_scale_coef(self.img0, self.imageLabel)
            self.repaint_cursor(sc)

    def DerceaseRadius(self, step):
        if (self.radius > step and self.flag):
            self.radius -= step
            self.value_Radius.setText(str(self.radius))
            sc = self.calc_scale_coef(self.img0, self.imageLabel)
            self.repaint_cursor(sc)

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_A:
            self.PrevButtonClicked()
        elif e.key() == Qt.Key_D:
            self.NextButtonClicked()
        elif e.key() == Qt.Key_S:
            self.saveButtonClicked()
        elif e.key() == Qt.Key_W:
            self.HideButtonClicked()
        elif e.key() == Qt.Key_Q:
            self.SLeftImButtonClicked()
        elif e.key() == Qt.Key_E:
            self.SRightImButtonClicked()
        elif e.key() == Qt.Key_Plus:
            self.IncreaseRadius(1)
        elif e.key() == Qt.Key_Minus:
            self.DerceaseRadius(1)

    def wheelEvent(self, event):
        numDegrees = event.angleDelta().y() / 8
        numSteps = numDegrees / 15.0
        if (numSteps > 0):
            self.IncreaseRadius(2)
        elif (numSteps < 0):
            self.DerceaseRadius(2)
Beispiel #37
0
class Ui_MainWindow(object):
    temp = 0

    def setupUi(self, MainWindow, path):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(863, 677)
        MainWindow.setStyleSheet("background-color: rgb(105, 105, 105);")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setStyleSheet("background-color: rgb(255, 170, 0);")
        self.pushButton.setObjectName("pushButton")
        self.gridLayout.addWidget(self.pushButton, 3, 0, 1, 1)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)

        self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 863, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.retranslateUi(MainWindow)

    #l1=[]
    #l2=[]
    opentime = 0
    closedtime = 0
    totaltime = 0

    def timechange(self, t):
        return (str(time.strftime('%H:%M:%S', time.gmtime(t))))

    def stopclicked(self):
        print("stop clicked")
        totaltime = time.time() - self.totaltime
        notdetected = totaltime - self.opentime - self.closedtime
        if notdetected < 5:
            notdetected = 0
        else:
            notdetected -= 5
        print(" open time: ", self.opentime, " alarm time: ", self.closedtime,
              " face not detected: ", notdetected)
        l1 = [self.opentime, self.closedtime, notdetected]
        pclosed = (self.closedtime / totaltime) * 100
        pnotdetected = (notdetected / totaltime) * 100
        popen = (self.opentime / totaltime) * 100

        l2 = [
            " open time: " + str(round(popen, 3)) + " %",
            " alarm time: " + str(round(pclosed, 3)) + " %",
            " face not detected: " + str(round(pnotdetected, 3)) + " %"
        ]
        timestring = "open time: " + self.timechange(round(
            self.opentime, 3)) + "\nalarm time: " + self.timechange(
                round(self.closedtime,
                      3)) + "\nface not detected: " + self.timechange(
                          round(notdetected, 3)) + "\n"
        print(time.ctime(totaltime))

        f = open("Drivertime.txt", "w")
        f.write(timestring)
        f.close()
        print(l1, l2)
        python_pie3D.python_pie3D(l1, l2)
        self.temp = 1
        QtWidgets.qApp.quit()
        call(["python", "last.py"])
        QtWidgets.qApp.quit()

    def retranslateUi(self, MainWindow):

        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

        self.pushButton.setText(_translate("MainWindow", "Stop"))
        self.pushButton.clicked.connect(self.stopclicked)

        #print(self.label.width())#100
        #print(self.label.height())#30

        i = 0
        cnt = 0

        flag = 1

        mixer.init()
        mixer.music.load("alarm1.mp3")
        mixer.music.play()
        mixer.music.pause()

        ptime = 0
        ctime = 0
        self.totaltime = time.time()
        start = self.totaltime

        while self.temp == 0:
            bgrl = []
            bgrr = []

            ret, img = cap.read()
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            i, bgrl, bgrr = ROI_Eye.ROI_Eye(i, gray)
            path = "pie chart.png"
            faces = face_cascade.detectMultiScale(gray, 1.3, 4)
            if len(bgrl) != 0 and len(bgrr) != 0:
                if cnt == 5:
                    #img=cv2.resize(cv2.imread("danger.png"),(863, 677))
                    path = "danger.png"
                    mixer.music.unpause()
                    if flag == 1:
                        self.opentime += time.time() - start
                        flag = 0
                        start = time.time()

                if cnt > 0 and (validate.validate(image_path_l) == 1
                                or validate.validate(image_path_r) == 1):
                    cnt -= 1
                    mixer.music.stop()
                    mixer.music.play()
                    mixer.music.pause()
                    if flag == 0:
                        self.closedtime += time.time() - start
                        flag = 1
                        start = time.time()
                    cv2.imwrite("Buffer/face.png", img)
                    path = "Buffer/face.png"

                if cnt < 5 and validate.validate(
                        image_path_l) == 0 and validate.validate(
                            image_path_r) == 0:
                    cnt += 1
                    cv2.imwrite("Buffer/face.png", img)
                    path = "Buffer/face.png"

                if cnt != 5:
                    for (x, y, w, h) in faces:
                        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0),
                                      2)
                    cv2.imwrite("Buffer/face.png", img)
                    path = "Buffer/face.png"

            else:
                path = "facenotdetected.png"
                mixer.music.stop()
                mixer.music.play()
                mixer.music.pause()
            if cv2.waitKey(1) & 0xFF == ord('s'):

                break
            self.pixmap = QPixmap(path)

            self.pixmap = self.pixmap.scaled(863, 677)

            self.label.setPixmap(self.pixmap)

            ctime = time.time()
            fps = 1 / (ctime - ptime)
            ptime = ctime
            print(int(fps))
            MainWindow.show()
Beispiel #38
0
class SpaceWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.parseData()
        self.layout = QVBoxLayout(self)
        self.initTabs()

    def parseData(self):
        self.weather = getStatus()
        self.launchData = getData()
        parseLocation(self.launchData)
        self.cords = list(self.launchData['Coordinates'])
        self.dates = list(self.launchData['Launch Dates'])
        self.missions = list(self.launchData['Missions'])
        self.infos = list(self.launchData['Info'])
        self.launchSites = list(self.launchData['Launch Sites'])
        self.times = list(self.launchData['Times'])
        self.numOfItem = len(self.launchData)

    def reFreshData(self):
        self.dates.clear()
        self.missions.clear()
        self.infos.clear()
        self.launchSites.clear()
        self.times.clear()
        self.numOfItem = 0
        self.launchData = None
        self.launchData = getData()

    def initTabs(self):
        self.tabs = QTabWidget()
        self.addTab1()
        self.addTab2()
        self.addTab3()
        self.wireTab1()
        self.wireTab2()
        self.wireTab3()
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    def addTab1(self):
        self.tab1 = QScrollArea()
        self.tabs.addTab(self.tab1, "Launches")
        self.addTab1Contents()

    def addTab1Contents(self):
        self.tab1Content = QWidget()
        self.tab1.setWidget(self.tab1Content)
        self.tab1.setWidgetResizable(True)
        self.tab1.layout = self.layout
        self.addAcessBtns()
        self.vl = QVBoxLayout()
        self.vl.addLayout(self.hl)
        self.vl.addWidget(QLabel(""))
        self.addCords()
        self.addInfo()
        self.addStatus()
        self.addFoodBtns()
        self.addCell()
        self.tab1Content.setLayout(self.vl)

    def addFoodBtns(self):
        self.yelpBtns = list()
        self.hlYelp = list()
        for n in range(self.numOfItem):
            self.yelpBtns.append(QPushButton('Yelp', self))
            self.hlYelp.append(QHBoxLayout())
            self.hlYelp[n].addWidget(self.yelpBtns[n])
            self.hlYelp[n].addStretch(50)

    def addAcessBtns(self):
        self.refreshBtn = QPushButton('Refresh')
        self.qBtn = QPushButton(' ? ')
        self.hl = QHBoxLayout()
        self.hl.addStretch(50)
        self.hl.addWidget(self.refreshBtn)
        self.hl.addWidget(self.qBtn)

    def addCell(self):
        self.tables = list()
        for n in range(self.numOfItem):
            self.tables.append(QTableWidget())
            self.tables[n].setRowCount(1)
            self.tables[n].setColumnCount(5)
            self.tables[n].setHorizontalHeaderLabels(
                ['Date', 'Time', 'Launch Site', 'Mission', 'Status'])
            self.tables[n].horizontalHeader().setSectionResizeMode(
                0, QHeaderView.ResizeToContents)
            self.tables[n].horizontalHeader().setSectionResizeMode(
                1, QHeaderView.ResizeToContents)
            self.tables[n].horizontalHeader().setSectionResizeMode(
                2, QHeaderView.Stretch)
            self.tables[n].horizontalHeader().setSectionResizeMode(
                3, QHeaderView.Stretch)
            self.tables[n].horizontalHeader().setSectionResizeMode(
                4, QHeaderView.ResizeToContents)
            self.tables[n].verticalHeader().setSectionResizeMode(
                QHeaderView.Stretch)
            self.tables[n].verticalHeader().setVisible(False)
            self.tables[n].setItem(0, 0, QTableWidgetItem(self.dates[n]))
            self.tables[n].setItem(0, 1, QTableWidgetItem(self.times[n]))
            self.tables[n].setCellWidget(0, 2, self.cordWidgets[n])
            self.tables[n].setCellWidget(0, 3, self.infoWidgets[n])
            self.tables[n].setCellWidget(0, 4, self.statusWidgets[n])
            self.vl.addWidget(self.tables[n])
            self.vl.addLayout(self.hlYelp[n])
            self.vl.addWidget(QLabel("\n"))

    def addCords(self):
        self.cordBtns = list()
        self.cordWidgets = list()
        self.cordLayouts = list()
        self.cordURL = list()
        for n in range(self.numOfItem):
            self.cordURL.append(createMap(self.cords[n]))
            self.cordBtns.append(QPushButton(self.launchSites[n], self))
            self.cordBtns[n].setSizePolicy(QSizePolicy.Expanding,
                                           QSizePolicy.Expanding)
            self.cordWidgets.append(QWidget())
            self.cordLayouts.append(QHBoxLayout(self.cordWidgets[n]))
            self.cordLayouts[n].addWidget(self.cordBtns[n])
            self.cordLayouts[n].setAlignment(Qt.AlignCenter)
            self.cordLayouts[n].setContentsMargins(0, 0, 0, 0)
            self.cordWidgets[n].setLayout(self.cordLayouts[n])

    def addInfo(self):
        self.infoBtns = list()
        self.infoWidgets = list()
        self.infoLayouts = list()
        for n in range(self.numOfItem):
            self.infoBtns.append(QPushButton(self.missions[n], self))
            self.infoBtns[n].setSizePolicy(QSizePolicy.Expanding,
                                           QSizePolicy.Expanding)
            self.infoWidgets.append(QWidget())
            self.infoLayouts.append(QHBoxLayout(self.infoWidgets[n]))
            self.infoLayouts[n].addWidget(self.infoBtns[n])
            self.infoLayouts[n].setAlignment(Qt.AlignCenter)
            self.infoLayouts[n].setContentsMargins(0, 0, 0, 0)
            self.infoWidgets[n].setLayout(self.infoLayouts[n])

    def setStatusColor(self, ind):
        if self.weather[ind][0] == 'Unknown':
            return 'white.png', ''
        elif self.weather[ind][0] == 'Fail':
            return 'yellow.png', self.weather[ind][1]
        else:
            return 'green.png', ''

    def addStatus(self):
        self.statusIcons = list()
        self.statusBtns = list()
        self.statusWidgets = list()
        self.statusLayouts = list()
        self.myStatus = list()
        for n in range(self.numOfItem):
            self.myStatus.append(self.setStatusColor(n))
            self.statusIcons.append(QIcon(self.myStatus[n][0]))
            self.statusBtns.append(QPushButton('', self))
            self.statusBtns[n].setIcon(self.statusIcons[n])
            self.statusBtns[n].setIconSize(QSize(25, 25))
            self.statusWidgets.append(QWidget())
            self.statusLayouts.append(QHBoxLayout(self.statusWidgets[n]))
            self.statusLayouts[n].addWidget(self.statusBtns[n])
            self.statusLayouts[n].setAlignment(Qt.AlignCenter)
            self.statusLayouts[n].setContentsMargins(0, 0, 0, 0)
            self.statusWidgets[n].setLayout(self.statusLayouts[n])

    def wireTab1(self):
        for n in range(self.numOfItem):
            self.infoBtns[n].clicked.connect(partial(self.onClickInfo, n))
            self.statusBtns[n].clicked.connect(partial(self.onClickStatus, n))
            self.cordBtns[n].clicked.connect(partial(self.onClickCord, n))
            self.yelpBtns[n].clicked.connect(partial(self.onClickYelp, n))
        self.refreshBtn.clicked.connect(self.onClickRefresh)
        self.qBtn.clicked.connect(partial(self.onClickQuestionMark, 0))

    def addTab2(self):
        self.tab2 = QWidget()
        self.tabs.addTab(self.tab2, "Mars")
        self.tab2CreateWidgets()
        self.forQBtns.addStretch(50)
        self.forQBtns.addWidget(self.qBtnTab2)
        self.hlBtns.addStretch(15)
        self.hlBtns.addWidget(self.openBtn)
        self.hlBtns.addWidget(self.lsBtn)
        self.hlBtns.addStretch(15)
        self.hlPictureInfo.addWidget(self.showDir)
        self.hlPictureInfo.addWidget(self.imgToDisplay)
        self.vlForTab2.addLayout(self.forQBtns)
        self.vlForTab2.addLayout(self.hlPictureInfo)
        self.vlForTab2.addLayout(self.hlBtns)
        self.tab2.setLayout(self.vlForTab2)

    def tab2CreateWidgets(self):
        self.vlForTab2 = QVBoxLayout()
        self.hlPictureInfo = QHBoxLayout()
        self.qBtnTab2 = QPushButton(' ? ')
        self.lsBtn = QPushButton('Classify')
        self.openBtn = QPushButton('Satellite')
        self.showDir = QTextBrowser()
        self.imgToDisplay = QLabel()
        self.hlBtns = QHBoxLayout()
        self.forQBtns = QHBoxLayout()
        self.displayImage('rocket.png')
        self.path = str()
        self.imgCount = True

    def displayImage(self, path):
        self.mySateliteImg = QPixmap(path)
        self.mySateliteImg = self.mySateliteImg.scaled(450, 350,
                                                       Qt.KeepAspectRatio,
                                                       Qt.FastTransformation)
        self.imgToDisplay.setPixmap(self.mySateliteImg)
        self.imgToDisplay.setAlignment(Qt.AlignCenter)
        self.imgToDisplay.setFixedSize(450, 350)
        self.imgToDisplay.repaint()

    def wireTab2(self):
        self.lsBtn.clicked.connect(self.onClickLs)
        self.openBtn.clicked.connect(self.onClickFindPath)
        self.qBtnTab2.clicked.connect(partial(self.onClickQuestionMark, 1))

    def addTab3(self):
        self.tab3 = QWidget()
        self.tabs.addTab(self.tab3, "About")
        self.tab3CreateWidgets()
        self.tab3Text.setSource(QUrl('aboutpage.html'))
        self.vlForTab3.addWidget(self.tab3Text)
        self.tab3.setLayout(self.vlForTab3)

    def tab3CreateWidgets(self):
        self.vlForTab3 = QVBoxLayout()
        self.tab3Text = QTextBrowser()

    def wireTab3(self):
        pass

    @pyqtSlot()
    def onClickFindPath(self):
        self.imgCount = not self.imgCount
        if self.imgCount:
            self.path = 'DeepModel/tf_files/test/test2.jpg'
        else:
            self.path = 'DeepModel/tf_files/test/test1.jpg'
        self.displayImage(self.path)

    @pyqtSlot()
    def onClickLs(self):
        if self.imgCount:
            os.system('cd DeepModel; python -m scripts.label_image \
                      --graph=tf_files/retrained_graph.pb  \
                      --image=tf_files/test/test2.jpg > ls.txt')
        else:
            os.system('cd DeepModel; python -m scripts.label_image \
                      --graph=tf_files/retrained_graph.pb  \
                      --image=tf_files/test/test1.jpg > ls.txt')
        self.inFile = open('DeepModel/ls.txt', 'r')
        self.lsList = str()
        for line in self.inFile:
            self.lsList += line
        self.inFile.close()
        self.showDir.setText(self.lsList)
        self.showDir.repaint()

    @pyqtSlot()
    def onClickRefresh(self):
        self.reFreshData()
        self.parseData()
        self.tab1.takeWidget()
        self.addTab1Contents()
        self.wireTab1()

    @pyqtSlot()
    def onClickYelp(self, ind):
        self.yelpMB = YelpMessageBox(ind, self.cords[ind])
        self.yelpMB.exec()

    @pyqtSlot()
    def onClickQuestionMark(self, tabNum):
        if not tabNum:
            QMessageBox.about(
                self, 'Launch Commit Criteria',
                'In order for a rocket to be safely launched and accomplish it’s mission, the weather conditions at launch must a strict set of criteria. First of all, if there is any precipitation whatsoever, the launch must be postponed. The windspeed at the launch site must not exceed 33 km/h and the visibility on the ground must be greater than 6.4 km. Due the the sensitivity of the rocket instruments and rocket fuel, the temperature must be within a range of 2℃ - 37℃. Finally if there is a thunderstorm with 63 km, the launch must be cancelled. \nGreen  = On time\nYellow = Delayed\nWhite   = Undetermined date'
            )
        else:
            QMessageBox.about(
                self, 'Satellite',
                'Using satellite imaging, a convolutional neural network was trained in order to detect dust storms. The risk to space missions posed by dust storms on mars has been displayed from The Martian to the recent loss of the opportunity rover that hasn’t been responding since the global  dust storm that consumed the planet this summer. By being able to identify and predict dust storms on Mars before they get too large can save countless dollars and man-hours of labor, not to mention lives of future astronauts on the surface of the planet.'
            )

    @pyqtSlot()
    def onClickInfo(self, n):
        QMessageBox.about(self, 'Detail', self.infos[n])

    @pyqtSlot()
    def onClickStatus(self, n):
        if self.myStatus[n][1]:
            QMessageBox.about(self, 'Reason', self.myStatus[n][1])

    @pyqtSlot()
    def onClickCord(self, n):
        #        self.myURL = QUrl(self.cordURL[n])
        #        QDesktopServices.openUrl(self.myURL)
        self.urlData = urllib.request.urlopen(self.cordURL[n]).read()
        self.urlImg = QPixmap()
        self.urlImg.loadFromData(self.urlData)
        myMBox = QMessageBox()
        myMBox.setIconPixmap(self.urlImg)
        myMBox.setStandardButtons(QMessageBox.Ok)
        myMBox.setDefaultButton(QMessageBox.Ok)
        myMBox.exec()
Beispiel #39
0
 def selecionarImagem(self):
     self.fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Single File', '/home', "PNG (*.png);;JPEG  (*.jpeg);;JPG  (*.jpg)")
     pixmap = QPixmap(self.fileName)
     pixmap1 = pixmap.scaled(161, 201)
     self.tela_cadastro_livro.colocar_imagem.setPixmap(pixmap1)
     self.capaEdited = True
Beispiel #40
0
class SimplePicEditor(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi()
        self.scaleFactor = 0.0

    def setupUi(self):
        """Sets up the GUI's for the application and displays to screen"""
        self.setFixedSize(650, 650)
        self.setWindowTitle('Pic Editor')
        self.centerMainWindow()
        self.createToolsDockWidget()
        self.createMenu()
        # self.createActions()
        self.createToolBar()
        self.photoEditorWidgets()
        self.resize(800, 800)

        self.show()

    def createMenu(self):
        """Generate Menu elements for the editor GUI"""
        # create menu actions for file menu: open, save and print image.
        self.open_action = QAction(QIcon('assets/open.png'), '&Open', self)
        self.open_action.setShortcut('Ctrl+O')
        self.open_action.setStatusTip('Open a new Image')
        self.open_action.triggered.connect(self.open_Image)

        self.save_action = QAction(QIcon('assets/save.png'), 'S&ave', self)
        self.save_action.setShortcut('Ctrl+S')
        self.save_action.setStatusTip('Save Image')
        self.save_action.triggered.connect(self.save_Image)

        self.print_action = QAction(QIcon('assets/print.png'), 'Print', self)
        self.print_action.setShortcut('Ctrl+P')
        self.print_action.setStatusTip('Print Image')
        self.print_action.triggered.connect(self.print_Image)

        self.exit_action = QAction(QIcon('assets/exit.png'), 'Exit', self)
        self.exit_action.setShortcut('Ctrl+Q')
        self.exit_action.setStatusTip('Quit Program')
        self.exit_action.triggered.connect(self.close)

        self.clear_action = QAction(QIcon('assets/clear.png'), 'Clear Image',
                                    self)
        self.clear_action.setShortcut('Ctrl+D')
        self.clear_action.setStatusTip('Clear the current Image')
        self.clear_action.triggered.connect(self.clear_Image)

        # edit menu actions i.e rotating, flipping actions

        self.rotate90_action = QAction('Rotate 90°', self)
        self.rotate90_action.setStatusTip('Rotate image 90° clockwise')
        self.rotate90_action.triggered.connect(self.rotate_image90)

        self.rotate180_action = QAction('Rotate 180°', self)
        self.rotate180_action.setStatusTip('Rotate image 180° clockwise')
        self.rotate180_action.triggered.connect(self.rotate_image180)

        self.hor_flip_action = QAction('Flip Horizontal', self)
        self.hor_flip_action.setStatusTip('Flip Image across Horizontal axis')
        self.hor_flip_action.triggered.connect(self.flip_horizontal)

        self.vert_flip_action = QAction('Flip Vertical', self)
        self.vert_flip_action.setStatusTip('Flip Image across Vertical Axis')
        self.vert_flip_action.triggered.connect(self.flip_vertical)

        self.resize_action = QAction('Resize Half', self)
        self.resize_action.setStatusTip(
            'Resize Image to half the original size')
        self.resize_action.triggered.connect(self.resize_half)

        self.fit_to_window_action = QAction('&Fit to window',
                                            self,
                                            checkable=True)
        self.fit_to_window_action.setEnabled(False)
        self.fit_to_window_action.setShortcut('Ctrl+F')
        self.fit_to_window_action.setStatusTip('Fit image to window size')
        self.fit_to_window_action.triggered.connect(self.fit_to_window)

        self.zoomIn_action = QAction(QIcon('assets/zoomIn.png'),
                                     'Zoom &In (25%)', self)
        self.zoomIn_action.setEnabled(False)
        self.zoomIn_action.setShortcut('Ctrl++')
        self.zoomIn_action.setStatusTip('Zoom in on image')
        self.zoomIn_action.triggered.connect(self.zoomIn)

        self.zoomOut_action = QAction(QIcon('assets/zoomout.png'),
                                      'Zoom &Out (25%)', self)
        self.zoomOut_action.setEnabled(False)
        self.zoomOut_action.setShortcut('Ctrl+-')
        self.zoomOut_action.setStatusTip('Zoom out image')
        self.zoomOut_action.triggered.connect(self.zoomOut)

        self.about_action = QAction('&About', self, triggered=self.about)
        self.aboutQt_action = QAction('About &Qt',
                                      self,
                                      triggered=qApp.aboutQt)

        self.normalSize_action = QAction('&Normal Size',
                                         self,
                                         shortcut="Ctrl+J",
                                         enabled=False,
                                         triggered=self.normalSize)

        # Menu bar for the application
        bar_menu = self.menuBar()
        bar_menu.setNativeMenuBar(False)

        # create file menu and add the actions above
        file_menu = bar_menu.addMenu('File')
        file_menu.addAction(self.open_action)
        file_menu.addAction(self.save_action)
        file_menu.addSeparator()
        file_menu.addAction(self.print_action)
        file_menu.addSeparator()
        file_menu.addAction(self.exit_action)

        # create edit menu and add the actions above
        edit_menu = bar_menu.addMenu('Edit')
        edit_menu.addAction(self.rotate90_action)
        edit_menu.addAction(self.rotate180_action)
        edit_menu.addSeparator()
        edit_menu.addAction(self.hor_flip_action)
        edit_menu.addAction(self.vert_flip_action)
        edit_menu.addSeparator()
        edit_menu.addAction(self.resize_action)
        edit_menu.addSeparator()
        edit_menu.addAction(self.clear_action)

        # Create view menu and add actions
        view_menu = bar_menu.addMenu('View')
        view_menu.addAction(self.zoomIn_action)
        view_menu.addAction(self.zoomOut_action)
        view_menu.addAction(self.normalSize_action)
        view_menu.addSeparator()
        view_menu.addAction(self.fit_to_window_action)
        view_menu.addSeparator()
        view_menu.addAction(self.toggle_dock_tools_act)

        # create help menu and actions
        help_menu = bar_menu.addMenu('&Help')
        help_menu.addAction(self.about_action)
        help_menu.addSeparator()
        help_menu.addAction(self.aboutQt_action)
        # Display info about tools, menu, and view in the status bar
        self.setStatusBar(QStatusBar(self))

    def updateActions(self):
        self.zoomIn_action.setEnabled(
            not self.fit_to_window_action.isChecked())
        self.zoomOut_action.setEnabled(
            not self.fit_to_window_action.isChecked())
        self.normalSize_action.setEnabled(
            not self.fit_to_window_action.isChecked())

    def createToolBar(self):
        """Create toolbar for photo editor GUI"""
        tool_bar = QToolBar("Photo Editor Toolbar")
        tool_bar.setIconSize(QSize(24, 24))
        self.addToolBar(tool_bar)

        # Add actions to toolbar
        tool_bar.addAction(self.open_action)
        tool_bar.addAction(self.save_action)
        tool_bar.addSeparator()
        tool_bar.addAction(self.print_action)
        tool_bar.addAction(self.clear_action)
        tool_bar.addSeparator()
        tool_bar.addAction(self.exit_action)
        tool_bar.addSeparator()
        tool_bar.addAction(self.zoomIn_action)
        tool_bar.addAction(self.zoomOut_action)

    def createToolsDockWidget(self):
        """Use View -> Edit Image Tools menu and click the dock widget on or off.
        Tools dock can be placed on the left or right of the main window.
        """
        # Set up QDockWidget
        self.dock_tools_view = QDockWidget()
        self.dock_tools_view.setWindowTitle("Edit Image Tools")
        self.dock_tools_view.setAllowedAreas(Qt.LeftDockWidgetArea
                                             | Qt.RightDockWidgetArea)
        # Create container QWidget to hold all widgets inside dock widget
        self.tools_contents = QWidget()
        # Create tool push buttons
        self.rotate90_btn = QPushButton("Rotate 90°")
        self.rotate90_btn.setMinimumSize(QSize(130, 40))
        self.rotate90_btn.setStatusTip('Rotate image 90° clockwise')
        self.rotate90_btn.clicked.connect(self.rotate_image90)
        self.rotate180_btn = QPushButton("Rotate 180°")
        self.rotate180_btn.setMinimumSize(QSize(130, 40))
        self.rotate180_btn.setStatusTip('Rotate image 180° clockwise')
        self.rotate180_btn.clicked.connect(self.rotate_image180)
        self.flip_horizontal_btn = QPushButton("Flip Horizontal")
        self.flip_horizontal_btn.setMinimumSize(QSize(130, 40))
        self.flip_horizontal_btn.setStatusTip(
            'Flip image across horizontal axis')
        self.flip_horizontal_btn.clicked.connect(self.flip_horizontal)
        self.flip_vertical_btn = QPushButton("Flip Vertical")
        self.flip_vertical_btn.setMinimumSize(QSize(130, 40))
        self.flip_vertical_btn.setStatusTip('Flip image across vertical axis')
        self.flip_vertical_btn.clicked.connect(self.flip_vertical)
        self.resize_half_btn = QPushButton("Resize Half")
        self.resize_half_btn.setMinimumSize(QSize(130, 40))
        self.resize_half_btn.setStatusTip(
            'Resize image to half the original size')
        self.resize_half_btn.clicked.connect(self.resize_half)
        # Set up vertical layout to contain all the push buttons
        dock_v_box = QVBoxLayout()
        dock_v_box.addWidget(self.rotate90_btn)
        dock_v_box.addWidget(self.rotate180_btn)
        dock_v_box.addStretch(1)
        dock_v_box.addWidget(self.flip_horizontal_btn)
        dock_v_box.addWidget(self.flip_vertical_btn)
        dock_v_box.addStretch(1)
        dock_v_box.addWidget(self.resize_half_btn)
        dock_v_box.addStretch(6)
        # Set the main layout for the QWidget, tools_contents,
        # then set the main widget of the dock widget
        self.tools_contents.setLayout(dock_v_box)
        self.dock_tools_view.setWidget(self.tools_contents)
        # Set initial location of dock widget
        self.addDockWidget(Qt.RightDockWidgetArea, self.dock_tools_view)
        # Handles the visibility of the dock widget 
        self.toggle_dock_tools_act = self.dock_tools_view.toggleViewAction()

    def photoEditorWidgets(self):
        """
        Set up instances of widgets for photo editor GUI
        """
        self.image = QPixmap()
        self.image_label = QLabel()
        self.scrollArea = QScrollArea()
        self.image_label.setAlignment(Qt.AlignCenter)
        # Use setSizePolicy to specify how the widget can be resized,
        # horizontally and vertically. Here, the image will stretch
        # horizontally, but not vertically.
        self.image_label.setBackgroundRole(QPalette.Base)
        self.image_label.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Ignored)
        self.image_label.setScaledContents(True)
        self.scrollArea.setBackgroundRole(QPalette.Dark)
        self.scrollArea.setWidget(self.image_label)
        self.scrollArea.setVisible(False)
        self.setCentralWidget(self.scrollArea)

    def open_Image(self):
        """
        Open an image file and display its contents in label widget.
        Display error message if image can't be opened.
        """
        image_file, _ = QFileDialog.getOpenFileName(
            self, "Open Image", "",
            "JPG Files (*.jpeg *.jpg );;PNG Files (*.png);;Bitmap Files(*.bmp);;\
                GIF Files (*.gif)")
        if image_file:
            self.image = QPixmap(image_file)
            self.image_label.setPixmap(
                self.image.scaled(self.image_label.size(), Qt.KeepAspectRatio,
                                  Qt.SmoothTransformation))
        else:
            QMessageBox.information(self, "Error", "Unable to open image.",
                                    QMessageBox.Ok)
        self.scaleFactor = 1.0
        self.scrollArea.setVisible(True)
        self.fit_to_window_action.setEnabled(True)
        self.print_action.setEnabled(True)

    def save_Image(self):
        """
        Save the image.
        Display error message if image can't be saved.
        """
        image_file, _ = QFileDialog.getSaveFileName(
            self, "Save Image", "",
            "JPG Files (*.jpeg *.jpg );;PNG Files (*.png);;Bitmap Files(*.bmp);;\
            GIF Files (*.gif)")
        if image_file and self.image.isNull() is False:
            self.image.save(image_file)
        else:
            QMessageBox.information(self, "Error", "Unable to save image.",
                                    QMessageBox.Ok)

    def clear_Image(self):
        """
        Clears current image in QLabel widget
        """
        self.image_label.clear()
        self.image = QPixmap()  # reset pixmap so that isNull() = True

    def fit_to_window(self):
        fit_to_window = self.fit_to_window_action.isChecked()
        self.scrollArea.setWidgetResizable(fit_to_window)
        if not fit_to_window:
            self.normalSize()

        self.updateActions()

    def zoomIn(self):
        self.scaleImage(1.25)

    def zoomOut(self):
        self.scaleImage(0.8)

    def normalSize(self):
        self.image_label.adjustSize()
        self.scaleFactor = 1.0

    def about(self):
        QMessageBox.about(
            self, 'About Simple Pic Editor',
            '<p>The <b>Simple Pic</b> Editor shows how to use different'
            'widgets offere in Qt bindings to python to create a simple'
            'image editor and viewer.</p>'
            'QLabel and QScrollArea to display an image. QLabel is '
            'typically used for displaying text, but it can also display'
            'an image. QScrollArea provides a scrolling view around'
            'another widget. If the child widget exceeds the size of the '
            'frame, QScrollArea automatically provides scroll bars.</p>'
            '<p>The example demonstrates how QLabel"s ability to scale '
            'its contents (QLabel.scaledContents), and QScrollArea"s'
            'ability to automatically resize its contents '
            '(QScrollArea.widgetResizable), can be used to implement '
            'zooming and scaling features.</p>'
            '<p>In addition the example shows how to use QPainter to '
            'print an image.</p>')

    def print_Image(self):
        """
        Print image.
        """
        # Create printer object and print output defined by the platform
        # the program is being run on.
        # QPrinter.NativeFormat is the default
        printer = QPrinter()
        printer.setOutputFormat(QPrinter.NativeFormat)
        # Create printer dialog to configure printer
        print_dialog = QPrintDialog(printer)
        # If the dialog is accepted by the user, begin printing
        if (print_dialog.exec_() == QPrintDialog.Accepted):
            # Use QPainter to output a PDF file
            painter = QPainter()
            # Begin painting device
            painter.begin(printer)
            # Set QRect to hold painter's current viewport, which
            # is the image_label
            rect = QRect(painter.viewport())
            # Get the size of image_label and use it to set the size
            # of the viewport
            size = QSize(self.image_label.pixmap().size())
            size.scale(rect.size(), Qt.KeepAspectRatio)
            painter.setViewport(rect.x(), rect.y(), size.width(),
                                size.height())
            painter.setWindow(self.image_label.pixmap().rect())
            # Scale the image_label to fit the rect source (0, 0)
            painter.drawPixmap(0, 0, self.image_label.pixmap())
            # End painting
            painter.end()

    def rotate_image90(self):
        """
        Rotate image 90° clockwise
        """
        if self.image.isNull() is False:
            transform90 = QTransform().rotate(90)
            pixmap = QPixmap(self.image)
            rotated = pixmap.transformed(transform90,
                                         mode=Qt.SmoothTransformation)
            self.image_label.setPixmap(
                rotated.scaled(self.image_label.size(), Qt.KeepAspectRatio,
                               Qt.SmoothTransformation))
            self.image = QPixmap(rotated)
            self.image_label.repaint()  # repaint the child widget
        else:
            # No ima
            pass

    def rotate_image180(self):
        """
        Rotate image 180° clockwise
        """
        if self.image.isNull() is False:
            transform180 = QTransform().rotate(180)
            pixmap = QPixmap(self.image)
            rotated = pixmap.transformed(transform180,
                                         mode=Qt.SmoothTransformation)
            self.image_label.setPixmap(
                rotated.scaled(self.image_label.size(), Qt.KeepAspectRatio,
                               Qt.SmoothTransformation))
            # In order to keep being allowed to rotate the image, set the
            # rotated image as self.image
            self.image = QPixmap(rotated)
            self.image_label.repaint()  # repaint the child widget
        else:
            # No image to rotate
            pass

    def flip_horizontal(self):
        """
        Mirror the image across the horizontal axis
        """
        if not self.image.isNull():
            flip_h = QTransform().scale(-1, 1)
            pixmap = QPixmap(self.image)
            flipped = pixmap.transformed(flip_h)
            self.image_label.setPixmap(
                flipped.scaled(self.image_label.size(), Qt.KeepAspectRatio,
                               Qt.SmoothTransformation))
            self.image = QPixmap(flipped)
            self.image_label.repaint()
        else:
            # no image flip
            pass

    def flip_vertical(self):
        """
        Mirror the image across the Vertical axis
        """
        if not self.image.isNull():
            flip_v = QTransform().scale(1, -1)
            pixmap = QPixmap(self.image)
            flipped = pixmap.transformed(flip_v)
            self.image_label.setPixmap(
                flipped.scaled(self.image_label.size(), Qt.KeepAspectRatio,
                               Qt.SmoothTransformation))
            self.image = QPixmap(flipped)
            self.image_label.repaint()
        else:
            # no image flip
            pass

    def resize_half(self):
        """
        Resize the image to half its current size.
        """
        if not self.image.isNull():
            resize = QTransform().scale(0.5, 0.5)
            pixmap = QPixmap(self.image)
            resized = pixmap.transformed(resize)
            self.image_label.setPixmap(
                resized.scaled(self.image_label.size(), Qt.KeepAspectRatio,
                               Qt.SmoothTransformation))
            self.image = QPixmap(resized)
            self.image_label.repaint()
        else:
            # no image to resize
            pass

    def scaleImage(self, factor):
        self.scaleFactor *= factor
        self.image_label.resize(self.scaleFactor *
                                self.image_label.pixmap().size())

        self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor)
        self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor)

        self.zoomIn_action.setEnabled(self.scaleFactor < 3.0)
        self.zoomOut_action.setEnabled(self.scaleFactor > 0.333)

    def adjustScrollBar(self, scrollBar, factor):
        scrollBar.setValue(
            int(factor * scrollBar.value() +
                ((factor - 1) * scrollBar.pageStep() / 2)))

    def centerMainWindow(self):
        """
        Use QDesktopWidget class to access information about your screen
        and use it to center the application window.
        """
        desktop = QDesktopWidget().screenGeometry()
        screen_width = desktop.width()
        screen_height = desktop.height()
        self.move(math.ceil((screen_width - self.width()) / 2),
                  math.ceil((screen_height - self.height()) / 2))
Beispiel #41
0
class YelpMessageBox(QMessageBox):
    def __init__(self, index, myCords):
        QMessageBox.__init__(self)
        self.setSizeGripEnabled(True)
        self.index = index
        self.setWindowTitle('Yelp')

        self.foods = YelpJSON.request(myCords, 'food')
        self.hotels = YelpJSON.request(myCords, 'hotels')

        self.addTableWidget(self)

        self.setStandardButtons(QMessageBox.Ok)
        self.setDefaultButton(QMessageBox.Ok)

    def addTableCell(self):
        #        print(self.foods)
        self.myLabels = list()
        self.myLinkIcons = list()
        self.myLinkBtns = list()
        self.myLinkWidgets = list()
        self.myLinkLayouts = list()
        for n in range(len(self.foods)):
            self.urlData = urllib.request.urlopen(
                self.foods[n]['picture link']).read()
            self.urlImg = QPixmap()
            self.urlImg.loadFromData(self.urlData)
            self.myLabels.append(QLabel())
            self.urlImg = self.urlImg.scaled(50, 50, Qt.KeepAspectRatio,
                                             Qt.FastTransformation)
            self.myLabels[n].setPixmap(self.urlImg)
            self.myLabels[n].setAlignment(Qt.AlignCenter)
            self.myLabels[n].setFixedSize(50, 50)
            self.myLabels[n].repaint()
            self.tableWidget.setCellWidget(n, 0, self.myLabels[n])
            self.tableWidget.setItem(
                n, 1, QTableWidgetItem(str(self.foods[n]['name'])))
            self.tableWidget.setItem(
                n, 2, QTableWidgetItem(str(self.foods[n]['address'])))
            self.tableWidget.setItem(
                n, 3, QTableWidgetItem(str(self.foods[n]['stars'])))
            self.tableWidget.setItem(
                n, 4, QTableWidgetItem(str(self.foods[n]['price'])))

            self.myLinkIcons.append(QIcon('yelp.png'))
            self.myLinkBtns.append(QPushButton('', self))
            self.myLinkBtns[n].setIcon(self.myLinkIcons[n])
            self.myLinkBtns[n].setIconSize(QSize(50, 50))
            self.myLinkWidgets.append(QWidget())
            self.myLinkLayouts.append(QHBoxLayout(self.myLinkWidgets[n]))
            self.myLinkLayouts[n].addWidget(self.myLinkBtns[n])
            self.myLinkLayouts[n].setAlignment(Qt.AlignCenter)
            self.myLinkLayouts[n].setContentsMargins(0, 0, 0, 0)
            self.myLinkWidgets[n].setLayout(self.myLinkLayouts[n])
            self.tableWidget.setCellWidget(n, 5, self.myLinkBtns[n])
            self.myLinkBtns[n].clicked.connect(partial(self.onClickLink, n))

    def addTableWidget(self, parentItem):
        self.l = QVBoxLayout()
        self.tableWidget = QTableWidget(parentItem)
        self.tableWidget.setObjectName('tableWidget')

        self.tableWidget.setColumnCount(6)
        self.tableWidget.setRowCount(len(self.foods))
        self.tableWidget.setHorizontalHeaderLabels(
            ['', 'Name', 'Address', 'Rating', 'Price', 'Link'])
        self.tableWidget.verticalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        self.tableWidget.verticalHeader().setVisible(False)
        self.tableWidget.horizontalHeader().setSectionResizeMode(
            5, QHeaderView.ResizeToContents)
        self.tableWidget.horizontalHeader().setSectionResizeMode(
            3, QHeaderView.Stretch)
        self.tableWidget.horizontalHeader().setSectionResizeMode(
            2, QHeaderView.ResizeToContents)
        self.tableWidget.horizontalHeader().setSectionResizeMode(
            1, QHeaderView.ResizeToContents)
        self.tableWidget.horizontalHeader().setSectionResizeMode(
            0, QHeaderView.ResizeToContents)
        self.tableWidget.move(30, 80)
        self.tableWidget.resize(1000, 500)

        self.addTableCell()

        self.l.addWidget(self.tableWidget)
        self.setLayout(self.l)

    def event(self, e):
        result = QMessageBox.event(self, e)
        self.setMinimumWidth(0)
        self.setMaximumWidth(16777215)
        self.setMinimumHeight(0)
        self.setMaximumHeight(16777215)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.resize(1000, 600)

        return result

    @pyqtSlot()
    def onClickLink(self, ind):
        self.myURL = QUrl(self.foods[ind]['link'])
        QDesktopServices.openUrl(self.myURL)
Beispiel #42
0
class GuiWritingStats(QDialog):

    C_TIME   = 0
    C_LENGTH = 1
    C_COUNT  = 2
    C_BAR    = 3

    FMT_JSON = 0
    FMT_CSV  = 1

    def __init__(self, theParent, theProject):
        QDialog.__init__(self, theParent)

        logger.debug("Initialising GuiWritingStats ...")
        self.setObjectName("GuiWritingStats")

        self.mainConf   = nw.CONFIG
        self.theParent  = theParent
        self.theProject = theProject
        self.theTheme   = theParent.theTheme
        self.optState   = theProject.optState

        self.logData    = []
        self.filterData = []
        self.timeFilter = 0.0
        self.wordOffset = 0

        self.setWindowTitle("Writing Statistics")
        self.setMinimumWidth(self.mainConf.pxInt(420))
        self.setMinimumHeight(self.mainConf.pxInt(400))
        self.resize(
            self.mainConf.pxInt(self.optState.getInt("GuiWritingStats", "winWidth",  550)),
            self.mainConf.pxInt(self.optState.getInt("GuiWritingStats", "winHeight", 500))
        )

        # List Box
        wCol0 = self.mainConf.pxInt(
            self.optState.getInt("GuiWritingStats", "widthCol0", 180)
        )
        wCol1 = self.mainConf.pxInt(
            self.optState.getInt("GuiWritingStats", "widthCol1", 80)
        )
        wCol2 = self.mainConf.pxInt(
            self.optState.getInt("GuiWritingStats", "widthCol2", 80)
        )

        self.listBox = QTreeWidget()
        self.listBox.setHeaderLabels(["Session Start", "Length", "Words", "Histogram"])
        self.listBox.setIndentation(0)
        self.listBox.setColumnWidth(self.C_TIME, wCol0)
        self.listBox.setColumnWidth(self.C_LENGTH, wCol1)
        self.listBox.setColumnWidth(self.C_COUNT, wCol2)

        hHeader = self.listBox.headerItem()
        hHeader.setTextAlignment(self.C_LENGTH, Qt.AlignRight)
        hHeader.setTextAlignment(self.C_COUNT, Qt.AlignRight)

        sortValid = (Qt.AscendingOrder, Qt.DescendingOrder)
        sortCol = self.optState.validIntRange(
            self.optState.getInt("GuiWritingStats", "sortCol", 0), 0, 2, 0
        )
        sortOrder = self.optState.validIntTuple(
            self.optState.getInt("GuiWritingStats", "sortOrder", Qt.DescendingOrder),
            sortValid, Qt.DescendingOrder
        )
        self.listBox.sortByColumn(sortCol, sortOrder)
        self.listBox.setSortingEnabled(True)

        # Word Bar
        self.barHeight = int(round(0.5*self.theTheme.fontPixelSize))
        self.barWidth = self.mainConf.pxInt(200)
        self.barImage = QPixmap(self.barHeight, self.barHeight)
        self.barImage.fill(self.palette().highlight().color())

        # Session Info
        self.infoBox  = QGroupBox("Sum Totals", self)
        self.infoForm = QGridLayout(self)
        self.infoBox.setLayout(self.infoForm)

        self.labelTotal = QLabel(formatTime(0))
        self.labelTotal.setFont(self.theTheme.guiFontFixed)
        self.labelTotal.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        self.labelFilter = QLabel(formatTime(0))
        self.labelFilter.setFont(self.theTheme.guiFontFixed)
        self.labelFilter.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        self.novelWords = QLabel("0")
        self.novelWords.setFont(self.theTheme.guiFontFixed)
        self.novelWords.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        self.notesWords = QLabel("0")
        self.notesWords.setFont(self.theTheme.guiFontFixed)
        self.notesWords.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        self.totalWords = QLabel("0")
        self.totalWords.setFont(self.theTheme.guiFontFixed)
        self.totalWords.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        self.infoForm.addWidget(QLabel("Total Time:"),       0, 0)
        self.infoForm.addWidget(QLabel("Filtered Time:"),    1, 0)
        self.infoForm.addWidget(QLabel("Novel Word Count:"), 2, 0)
        self.infoForm.addWidget(QLabel("Notes Word Count:"), 3, 0)
        self.infoForm.addWidget(QLabel("Total Word Count:"), 4, 0)
        self.infoForm.addWidget(self.labelTotal,  0, 1)
        self.infoForm.addWidget(self.labelFilter, 1, 1)
        self.infoForm.addWidget(self.novelWords,  2, 1)
        self.infoForm.addWidget(self.notesWords,  3, 1)
        self.infoForm.addWidget(self.totalWords,  4, 1)
        self.infoForm.setRowStretch(5, 1)

        # Filter Options
        sPx = self.theTheme.baseIconSize

        self.filterBox  = QGroupBox("Filters", self)
        self.filterForm = QGridLayout(self)
        self.filterBox.setLayout(self.filterForm)

        self.incNovel = QSwitch(width=2*sPx, height=sPx)
        self.incNovel.setChecked(
            self.optState.getBool("GuiWritingStats", "incNovel", True)
        )
        self.incNovel.clicked.connect(self._updateListBox)

        self.incNotes = QSwitch(width=2*sPx, height=sPx)
        self.incNotes.setChecked(
            self.optState.getBool("GuiWritingStats", "incNotes", True)
        )
        self.incNotes.clicked.connect(self._updateListBox)

        self.hideZeros = QSwitch(width=2*sPx, height=sPx)
        self.hideZeros.setChecked(
            self.optState.getBool("GuiWritingStats", "hideZeros", True)
        )
        self.hideZeros.clicked.connect(self._updateListBox)

        self.hideNegative = QSwitch(width=2*sPx, height=sPx)
        self.hideNegative.setChecked(
            self.optState.getBool("GuiWritingStats", "hideNegative", False)
        )
        self.hideNegative.clicked.connect(self._updateListBox)

        self.groupByDay = QSwitch(width=2*sPx, height=sPx)
        self.groupByDay.setChecked(
            self.optState.getBool("GuiWritingStats", "groupByDay", False)
        )
        self.groupByDay.clicked.connect(self._updateListBox)

        self.filterForm.addWidget(QLabel("Count novel files"),        0, 0)
        self.filterForm.addWidget(QLabel("Count note files"),         1, 0)
        self.filterForm.addWidget(QLabel("Hide zero word count"),     2, 0)
        self.filterForm.addWidget(QLabel("Hide negative word count"), 3, 0)
        self.filterForm.addWidget(QLabel("Group entries by day"),     4, 0)
        self.filterForm.addWidget(self.incNovel,     0, 1)
        self.filterForm.addWidget(self.incNotes,     1, 1)
        self.filterForm.addWidget(self.hideZeros,    2, 1)
        self.filterForm.addWidget(self.hideNegative, 3, 1)
        self.filterForm.addWidget(self.groupByDay,   4, 1)
        self.filterForm.setRowStretch(5, 1)

        # Settings
        self.histMax = QSpinBox(self)
        self.histMax.setMinimum(100)
        self.histMax.setMaximum(100000)
        self.histMax.setSingleStep(100)
        self.histMax.setValue(
            self.optState.getInt("GuiWritingStats", "histMax", 2000)
        )
        self.histMax.valueChanged.connect(self._updateListBox)

        self.optsBox = QHBoxLayout()
        self.optsBox.addStretch(1)
        self.optsBox.addWidget(QLabel("Word count cap for the histogram"), 0)
        self.optsBox.addWidget(self.histMax, 0)

        # Buttons
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.rejected.connect(self._doClose)

        self.btnClose = self.buttonBox.addButton(QDialogButtonBox.Close)
        self.btnClose.setAutoDefault(False)

        self.btnSave = self.buttonBox.addButton("Save As", QDialogButtonBox.ActionRole)
        self.btnSave.setAutoDefault(False)

        self.saveMenu = QMenu(self)
        self.btnSave.setMenu(self.saveMenu)

        self.saveJSON = QAction("JSON Data File (.json)", self)
        self.saveJSON.triggered.connect(lambda: self._saveData(self.FMT_JSON))
        self.saveMenu.addAction(self.saveJSON)

        self.saveCSV = QAction("CSV Data File (.csv)", self)
        self.saveCSV.triggered.connect(lambda: self._saveData(self.FMT_CSV))
        self.saveMenu.addAction(self.saveCSV)

        # Assemble
        self.outerBox = QGridLayout()
        self.outerBox.addWidget(self.listBox,   0, 0, 1, 2)
        self.outerBox.addLayout(self.optsBox,   1, 0, 1, 2)
        self.outerBox.addWidget(self.infoBox,   2, 0)
        self.outerBox.addWidget(self.filterBox, 2, 1)
        self.outerBox.addWidget(self.buttonBox, 3, 0, 1, 2)
        self.outerBox.setRowStretch(0, 1)

        self.setLayout(self.outerBox)

        logger.debug("GuiWritingStats initialisation complete")

        return

    def populateGUI(self):
        """Populate list box with data from the log file.
        """
        qApp.setOverrideCursor(QCursor(Qt.WaitCursor))
        self._loadLogFile()
        self._updateListBox()
        qApp.restoreOverrideCursor()
        return

    ##
    #  Slots
    ##

    def _doClose(self):
        """Save the state of the window, clear cache, end close.
        """
        self.logData = []

        winWidth     = self.mainConf.rpxInt(self.width())
        winHeight    = self.mainConf.rpxInt(self.height())
        widthCol0    = self.mainConf.rpxInt(self.listBox.columnWidth(0))
        widthCol1    = self.mainConf.rpxInt(self.listBox.columnWidth(1))
        widthCol2    = self.mainConf.rpxInt(self.listBox.columnWidth(2))
        sortCol      = self.listBox.sortColumn()
        sortOrder    = self.listBox.header().sortIndicatorOrder()
        incNovel     = self.incNovel.isChecked()
        incNotes     = self.incNotes.isChecked()
        hideZeros    = self.hideZeros.isChecked()
        hideNegative = self.hideNegative.isChecked()
        groupByDay   = self.groupByDay.isChecked()
        histMax      = self.histMax.value()

        self.optState.setValue("GuiWritingStats", "winWidth",     winWidth)
        self.optState.setValue("GuiWritingStats", "winHeight",    winHeight)
        self.optState.setValue("GuiWritingStats", "widthCol0",    widthCol0)
        self.optState.setValue("GuiWritingStats", "widthCol1",    widthCol1)
        self.optState.setValue("GuiWritingStats", "widthCol2",    widthCol2)
        self.optState.setValue("GuiWritingStats", "sortCol",      sortCol)
        self.optState.setValue("GuiWritingStats", "sortOrder",    sortOrder)
        self.optState.setValue("GuiWritingStats", "incNovel",     incNovel)
        self.optState.setValue("GuiWritingStats", "incNotes",     incNotes)
        self.optState.setValue("GuiWritingStats", "hideZeros",    hideZeros)
        self.optState.setValue("GuiWritingStats", "hideNegative", hideNegative)
        self.optState.setValue("GuiWritingStats", "groupByDay",   groupByDay)
        self.optState.setValue("GuiWritingStats", "histMax",      histMax)

        self.optState.saveSettings()
        self.close()

        return

    def _saveData(self, dataFmt):
        """Save the content of the list box to a file.
        """
        fileExt = ""
        textFmt = ""

        if dataFmt == self.FMT_JSON:
            fileExt = "json"
            textFmt = "JSON Data File"

        elif dataFmt == self.FMT_CSV:
            fileExt = "csv"
            textFmt = "CSV Data File"

        else:
            return False

        # Generate the file name
        if fileExt:
            saveDir = self.mainConf.lastPath
            if not os.path.isdir(saveDir):
                saveDir = os.path.expanduser("~")

            fileName = "sessionStats.%s" % fileExt
            savePath = os.path.join(saveDir, fileName)

            dlgOpt  = QFileDialog.Options()
            dlgOpt |= QFileDialog.DontUseNativeDialog
            savePath, _ = QFileDialog.getSaveFileName(
                self, "Save Document As", savePath, options=dlgOpt
            )

            if not savePath:
                return False

            self.mainConf.setLastPath(savePath)

        else:
            return False

        # Do the actual writing
        wSuccess = False
        errMsg = ""

        try:
            with open(savePath, mode="w", encoding="utf8") as outFile:
                if dataFmt == self.FMT_JSON:
                    jsonData = []
                    for _, sD, tT, wD, wA, wB in self.filterData:
                        jsonData.append({
                            "date": sD,
                            "length": tT,
                            "newWords": wD,
                            "novelWords": wA,
                            "noteWords": wB,
                        })
                    json.dump(jsonData, outFile, indent=2)
                    wSuccess = True

                elif dataFmt == self.FMT_CSV:
                    outFile.write(
                        '"Date","Length (sec)","Words Changed","Novel Words","Note Words"\n'
                    )
                    for _, sD, tT, wD, wA, wB in self.filterData:
                        outFile.write(f'"{sD}",{tT:.0f},{wD},{wA},{wB}\n')
                    wSuccess = True

                else:
                    errMsg = "Unknown format"

        except Exception as e:
            errMsg = str(e).replace("\n", "<br>")

        # Report to user
        if wSuccess:
            self.theParent.makeAlert(
                "%s file successfully written to:<br>%s" % (
                    textFmt, savePath
                ), nwAlert.INFO
            )
        else:
            self.theParent.makeAlert(
                "Failed to write %s file.<br>%s" % (
                    textFmt, errMsg
                ), nwAlert.ERROR
            )

        return True

    ##
    #  Internal Functions
    ##

    def _loadLogFile(self):
        """Load the content of the log file into a buffer.
        """
        logger.debug("Loading session log file")

        self.logData = []

        ttNovel = 0
        ttNotes = 0
        ttTime  = 0

        try:
            logFile = os.path.join(self.theProject.projMeta, nwFiles.SESS_STATS)
            with open(logFile, mode="r", encoding="utf8") as inFile:
                for inLine in inFile:
                    if inLine.startswith("#"):
                        if inLine.startswith("# Offset"):
                            self.wordOffset = int(inLine[9:].strip())
                            logger.verbose(
                                "Initial word count when log was started is %d" % self.wordOffset
                            )
                        continue

                    inData = inLine.split()
                    if len(inData) != 6:
                        continue

                    dStart = datetime.strptime(
                        "%s %s" % (inData[0], inData[1]), nwConst.tStampFmt
                    )
                    dEnd = datetime.strptime(
                        "%s %s" % (inData[2], inData[3]), nwConst.tStampFmt
                    )

                    tDiff = dEnd - dStart
                    sDiff = tDiff.total_seconds()
                    ttTime += sDiff

                    wcNovel = int(inData[4])
                    wcNotes = int(inData[5])
                    ttNovel = wcNovel
                    ttNotes = wcNotes

                    self.logData.append((dStart, sDiff, wcNovel, wcNotes))

        except Exception as e:
            self.theParent.makeAlert(
                ["Failed to read session log file.", str(e)], nwAlert.ERROR
            )
            return False

        ttWords = ttNovel + ttNotes
        self.labelTotal.setText(formatTime(round(ttTime)))
        self.novelWords.setText(f"{ttNovel:n}")
        self.notesWords.setText(f"{ttNotes:n}")
        self.totalWords.setText(f"{ttWords:n}")

        return True

    def _updateListBox(self, dummyVar=None):
        """Load/reload the content of the list box. The dummyVar
        variable captures the variable sent from the widgets connecting
        to it and discards it.
        """
        self.listBox.clear()
        self.timeFilter = 0.0

        incNovel     = self.incNovel.isChecked()
        incNotes     = self.incNotes.isChecked()
        hideZeros    = self.hideZeros.isChecked()
        hideNegative = self.hideNegative.isChecked()
        groupByDay   = self.groupByDay.isChecked()
        histMax      = self.histMax.value()

        # Group the data
        if groupByDay:
            tempData = []
            sessDate = None
            sessTime = 0
            lstNovel = 0
            lstNotes = 0

            for n, (dStart, sDiff, wcNovel, wcNotes) in enumerate(self.logData):
                if n == 0:
                    sessDate = dStart.date()
                if sessDate != dStart.date():
                    tempData.append((sessDate, sessTime, lstNovel, lstNotes))
                    sessDate = dStart.date()
                    sessTime = sDiff
                    lstNovel = wcNovel
                    lstNotes = wcNotes
                else:
                    sessTime += sDiff
                    lstNovel = wcNovel
                    lstNotes = wcNotes

            if sessDate is not None:
                tempData.append((sessDate, sessTime, lstNovel, lstNotes))

        else:
            tempData = self.logData

        # Calculate Word Diff
        self.filterData = []
        pcTotal = 0
        listMax = 0
        isFirst = True
        for dStart, sDiff, wcNovel, wcNotes in tempData:

            wcTotal = 0
            if incNovel:
                wcTotal += wcNovel
            if incNotes:
                wcTotal += wcNotes

            dwTotal = wcTotal - pcTotal
            if hideZeros and dwTotal == 0:
                continue
            if hideNegative and dwTotal < 0:
                continue

            if isFirst:
                # Subtract the offset from the first list entry
                dwTotal -= self.wordOffset
                dwTotal = max(dwTotal, 1) # Don't go zero or negative
                isFirst = False

            if groupByDay:
                sStart = dStart.strftime(nwConst.dStampFmt)
            else:
                sStart = dStart.strftime(nwConst.tStampFmt)

            self.filterData.append((dStart, sStart, sDiff, dwTotal, wcNovel, wcNotes))
            listMax = min(max(listMax, dwTotal), histMax)
            pcTotal = wcTotal

        # Populate the list
        for _, sStart, sDiff, nWords, _, _ in self.filterData:

            newItem = QTreeWidgetItem()
            newItem.setText(self.C_TIME, sStart)
            newItem.setText(self.C_LENGTH, formatTime(round(sDiff)))
            newItem.setText(self.C_COUNT, f"{nWords:n}")

            if nWords > 0 and listMax > 0:
                theBar = self.barImage.scaled(
                    int(200*min(nWords, histMax)/listMax),
                    self.barHeight,
                    Qt.IgnoreAspectRatio,
                    Qt.FastTransformation
                )
                newItem.setData(self.C_BAR, Qt.DecorationRole, theBar)

            newItem.setTextAlignment(self.C_LENGTH, Qt.AlignRight)
            newItem.setTextAlignment(self.C_COUNT, Qt.AlignRight)
            newItem.setTextAlignment(self.C_BAR, Qt.AlignLeft | Qt.AlignVCenter)

            newItem.setFont(self.C_TIME, self.theTheme.guiFontFixed)
            newItem.setFont(self.C_LENGTH, self.theTheme.guiFontFixed)
            newItem.setFont(self.C_COUNT, self.theTheme.guiFontFixed)

            self.listBox.addTopLevelItem(newItem)
            self.timeFilter += sDiff

        self.labelFilter.setText(formatTime(round(self.timeFilter)))

        return True
Beispiel #43
0
    def update(self):
        self.clear()

        self.dataset = self.full_dataset[0:self.counter]

        deck_select_button = QPushButton("<<<")
        deck_select_button.clicked.connect(self.selectDeckButtonClicked)

        self.show_all_button = QPushButton("show all")
        self.show_all_button.clicked.connect(self.showAllButtonClicked)
        self.show_all_button_state = "show_all"

        replay_audio_button = QPushButton("replay audio")
        replay_audio_button.setIcon(QIcon.fromTheme('media-playback-start'))
        replay_audio_button.clicked.connect(self.replayAudioClicked)

        select_display_combo_label = QLabel('select display:')
        select_display_combo_label.setAlignment(QtCore.Qt.AlignRight)
        select_display_combo = QComboBox()
        select_display_combo.addItems(DISPLAY_COMBO_ITEMS)
        select_display_combo.setCurrentIndex(
            DISPLAY_COMBO_ITEMS.index(self.test_mode))
        select_display_combo.currentIndexChanged.connect(
            self.selectDisplayCurrentIndexChanged)

        instruction_label = QLabel(
            "[please click the image which you think is assigned to the spoken word!]"
        )

        if not self.layout():
            self.grid = QGridLayout()
            self.grid.setContentsMargins(0, 0, 0, 0)

        self.grid.addWidget(deck_select_button, 0, 0)
        self.grid.addWidget(select_display_combo_label, 0, 1)
        self.grid.addWidget(select_display_combo, 0, 2)
        self.grid.addWidget(replay_audio_button, 0, 3)

        for i, value in enumerate(self.dataset, COLUMNS):
            label = QClickLabel()
            if self.test_mode == 'image':
                preview_pixmap = QPixmap()
                try:
                    preview_pixmap.load(
                        path.join(self.deckpath, value["image"]))
                except (KeyError, TypeError):
                    try:
                        preview_pixmap.load(
                            path.join(self.deckpath, value["svg_filename"]))
                    except (KeyError, TypeError):
                        pass
                scaled_pixmap = preview_pixmap.scaled(
                    QtCore.QSize(200, 200), QtCore.Qt.KeepAspectRatio)
                label.setGeometry(scaled_pixmap.rect())
                label.setPixmap(scaled_pixmap)
            elif self.test_mode == 'name':
                label.setText(value['name'])
            elif self.test_mode == 'word':
                label.setText(value['word'])
            elif self.test_mode == 'translation':
                label.setText(value['translation'])

            self.unicode_fonts.applyFontAndSizeToQWidget(label.text(), label)

            label.setAlignment(QtCore.Qt.AlignCenter)
            label.clicked.connect(
                functools.partial(self.labelClicked, value["rowid"]))

            self.grid.addWidget(label, int(i / COLUMNS), i % COLUMNS)

        self.grid.addWidget(self.show_all_button, len(self.dataset) + 1, 0)
        self.grid.addWidget(instruction_label, len(self.dataset) + 1, 1, 1, 3)

        self.setLayout(self.grid)

        self.playRandomAudio()
Beispiel #44
0
class Screenshot(QWidget):
    def __init__(self):
        super(Screenshot, self).__init__()
        self.setFixedSize(500, 400)
        self.screenshotLabel = QLabel()
        self.screenshotLabel.setSizePolicy(QSizePolicy.Expanding,
                                           QSizePolicy.Expanding)
        self.screenshotLabel.setAlignment(Qt.AlignCenter)
        self.screenshotLabel.setMinimumSize(240, 160)

        self.createOptionsGroupBox()
        self.createButtonsLayout()

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.screenshotLabel)
        mainLayout.addWidget(self.optionsGroupBox)
        mainLayout.addLayout(self.buttonsLayout)
        self.setLayout(mainLayout)

        self.shootScreen()
        self.delaySpinBox.setValue(5)

        self.setWindowTitle("视频截图")
        self.setWindowIcon(qtawesome.icon('fa.car', color='black'))
        self.resize(300, 200)

    def createOptionsGroupBox(self):
        self.optionsGroupBox = QGroupBox("选项")

        self.delaySpinBox = QSpinBox()
        self.delaySpinBox.setSuffix("s")
        self.delaySpinBox.setMaximum(60)
        self.delaySpinBox.valueChanged.connect(self.updateCheckBox)

        self.delaySpinBoxLabel = QLabel("截图延时:")

        self.hideThisWindowCheckBox = QCheckBox("截图窗口隐藏")

        optionsGroupBoxLayout = QGridLayout()
        optionsGroupBoxLayout.addWidget(self.delaySpinBoxLabel, 0, 0)
        optionsGroupBoxLayout.addWidget(self.delaySpinBox, 0, 1)
        optionsGroupBoxLayout.addWidget(self.hideThisWindowCheckBox, 1, 0, 1, 2)
        self.optionsGroupBox.setLayout(optionsGroupBoxLayout)

    def updateCheckBox(self):
        if self.delaySpinBox.value() == 0:
            self.hideThisWindowCheckBox.setDisabled(False)
        else:
            self.hideThisWindowCheckBox.setDisabled(False)

    def createButtonsLayout(self):
        self.newScreenshotButton = self.createButton("再次截图",
                                                     self.newScreenshot)
        self.saveScreenshotButton = self.createButton("保存截图",
                                                      self.saveScreenshot)
        self.quitScreenshotButton = self.createButton("退出截图", self.close)

        self.buttonsLayout = QHBoxLayout()
        self.buttonsLayout.addStretch()
        self.buttonsLayout.addWidget(self.newScreenshotButton)
        self.buttonsLayout.addWidget(self.saveScreenshotButton)
        self.buttonsLayout.addWidget(self.quitScreenshotButton)

    def createButton(self, text, mySlot):
        button = QPushButton(text)
        button.clicked.connect(mySlot)
        return button

    def newScreenshot(self):
        if self.hideThisWindowCheckBox.isChecked():
            self.hide()
        self.newScreenshotButton.setDisabled(True)

        QTimer.singleShot(self.delaySpinBox.value() * 1000,
                          self.shootScreen)

    def shootScreen(self):
        if self.delaySpinBox.value() != 0:
            QApplication.instance().beep()

        screen = QApplication.primaryScreen()
        if screen is not None:
            self.originalPixmap = screen.grabWindow(0)
        else:
            self.originalPixmap = QPixmap()

        self.updateScreenshotLabel()

        self.newScreenshotButton.setDisabled(False)
        if self.hideThisWindowCheckBox.isChecked():
            self.show()

    def updateScreenshotLabel(self):
        self.screenshotLabel.setPixmap(self.originalPixmap.scaled(
            self.screenshotLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))

    def saveScreenshot(self):
        format = 'png'
        initialPath = QDir.currentPath() + "/untitled." + format

        fileName, _ = QFileDialog.getSaveFileName(self, "Save As", initialPath,
                                                  "%s File(*.%s);;All Files(*)" % (format.upper(), format))

        if fileName:
            self.originalPixmap.save(fileName, format)

    def resizeEvent(self, event):
        scaledSize = self.originalPixmap.size()
        scaledSize.scaled(self.screenshotLabel.size(), Qt.KeepAspectRatio)
        if not self.screenshotLabel.pixmap() or scaledSize != self.screenshotLabel.pixmap().size():
            self.updateScreenshotLabel()
Beispiel #45
0
 def loadimage(self, filepath):
     pixmap = QPixmap(filepath)
     self.lblImage.setPixmap(
         pixmap.scaled(self.w, self.h, Qt.KeepAspectRatio,
                       Qt.SmoothTransformation))
Beispiel #46
0
class CAvatar(QWidget):

    Circle = 0  # 圆圈
    Rectangle = 1  # 圆角矩形
    SizeLarge = QSize(128, 128)
    SizeMedium = QSize(64, 64)
    SizeSmall = QSize(32, 32)
    StartAngle = 0  # 起始旋转角度
    EndAngle = 360  # 结束旋转角度

    def __init__(self,
                 *args,
                 shape=0,
                 url='',
                 cacheDir=False,
                 size=QSize(64, 64),
                 animation=False,
                 **kwargs):
        super(CAvatar, self).__init__(*args, **kwargs)
        self.url = ''
        self._angle = 0  # 角度
        self.pradius = 0  # 加载进度条半径
        self.animation = animation  # 是否使用动画
        self._pixmap = QPixmap()  # 图片对象
        self.pixmap = QPixmap()  # 被绘制的对象
        # 进度动画定时器
        self.loadingTimer = QTimer(self, timeout=self.onLoading)
        # 旋转动画
        self.rotateAnimation = QPropertyAnimation(self,
                                                  b'angle',
                                                  self,
                                                  loopCount=1)
        self.setShape(shape)
        self.setCacheDir(cacheDir)
        self.setSize(size)
        self.setUrl(url)

    def paintEvent(self, event):
        super(CAvatar, self).paintEvent(event)
        # 画笔
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setRenderHint(QPainter.HighQualityAntialiasing, True)
        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
        # 绘制
        path = QPainterPath()
        diameter = min(self.width(), self.height())
        if self.shape == self.Circle:
            radius = int(diameter / 2)
        elif self.shape == self.Rectangle:
            radius = 4
        halfW = self.width() / 2
        halfH = self.height() / 2
        painter.translate(halfW, halfH)
        path.addRoundedRect(QRectF(-halfW, -halfH, diameter, diameter), radius,
                            radius)
        painter.setClipPath(path)
        # 如果是动画效果
        if self.rotateAnimation.state() == QPropertyAnimation.Running:
            painter.rotate(self._angle)  # 旋转
            painter.drawPixmap(
                QPointF(-self.pixmap.width() / 2, -self.pixmap.height() / 2),
                self.pixmap)
        else:
            painter.drawPixmap(-int(halfW), -int(halfH), self.pixmap)
        # 如果在加载
        if self.loadingTimer.isActive():
            diameter = 2 * self.pradius
            painter.setBrush(
                QColor(45, 140, 240, (1 - self.pradius / 10) * 255))
            painter.setPen(Qt.NoPen)
            painter.drawRoundedRect(
                QRectF(-self.pradius, -self.pradius, diameter, diameter),
                self.pradius, self.pradius)

    def enterEvent(self, event):
        """鼠标进入动画
        :param event:
        """
        if not self.animation:
            return
        self.rotateAnimation.stop()
        cv = self.rotateAnimation.currentValue() or self.StartAngle
        self.rotateAnimation.setDuration(540 if cv ==
                                         0 else int(cv / self.EndAngle * 540))
        self.rotateAnimation.setStartValue(cv)
        self.rotateAnimation.setEndValue(self.EndAngle)
        self.rotateAnimation.start()

    def leaveEvent(self, event):
        """鼠标离开动画
        :param event:
        """
        if not self.animation:
            return
        self.rotateAnimation.stop()
        cv = self.rotateAnimation.currentValue() or self.EndAngle
        self.rotateAnimation.setDuration(int(cv / self.EndAngle * 540))
        self.rotateAnimation.setStartValue(cv)
        self.rotateAnimation.setEndValue(self.StartAngle)
        self.rotateAnimation.start()

    def onLoading(self):
        """更新进度动画
        """
        if self.loadingTimer.isActive():
            if self.pradius > 9:
                self.pradius = 0
            self.pradius += 1
        else:
            self.pradius = 0
        self.update()

    def onFinished(self):
        """图片下载完成
        """
        self.loadingTimer.stop()
        self.pradius = 0
        reply = self.sender()
        data = reply.readAll().data()
        reply.deleteLater()
        del reply
        self._pixmap.loadFromData(data)
        if self._pixmap.isNull():
            self._pixmap = QPixmap(self.size())
            self._pixmap.fill(QColor(204, 204, 204))
        self._resizePixmap()

    def onError(self, code):
        """下载出错了
        :param code:
        """
        self._pixmap = QPixmap(self.size())
        self._pixmap.fill(QColor(204, 204, 204))
        self._resizePixmap()

    def refresh(self):
        """强制刷新
        """
        self._get(self.url)

    def isLoading(self):
        """判断是否正在加载
        """
        return self.loadingTimer.isActive()

    def setShape(self, shape):
        """设置形状
        :param shape:        0=圆形, 1=圆角矩形
        """
        self.shape = shape

    def setUrl(self, url):
        """设置url,可以是本地路径,也可以是网络地址
        :param url:
        """
        self.url = url
        self._get(url)

    def setCacheDir(self, cacheDir=''):
        """设置本地缓存路径
        :param cacheDir:
        """
        self.cacheDir = cacheDir
        self._initNetWork()

    def setSize(self, size):
        """设置固定尺寸
        :param size:
        """
        if not isinstance(size, QSize):
            size = self.SizeMedium
        self.setMinimumSize(size)
        self.setMaximumSize(size)
        self._resizePixmap()

    @pyqtProperty(int)
    def angle(self):
        return self._angle

    @angle.setter
    def angle(self, value):
        self._angle = value
        self.update()

    def _resizePixmap(self):
        """缩放图片
        """
        if not self._pixmap.isNull():
            self.pixmap = self._pixmap.scaled(self.width(), self.height(),
                                              Qt.IgnoreAspectRatio,
                                              Qt.SmoothTransformation)
        self.update()

    def _initNetWork(self):
        """初始化异步网络库
        """
        if not hasattr(qApp, '_network'):
            network = QNetworkAccessManager(self.window())
            setattr(qApp, '_network', network)
        # 是否需要设置缓存
        if self.cacheDir and not qApp._network.cache():
            cache = QNetworkDiskCache(self.window())
            cache.setCacheDirectory(self.cacheDir)
            qApp._network.setCache(cache)

    def _get(self, url):
        """设置图片或者请求网络图片
        :param url:
        """
        if not url:
            self.onError('')
            return
        if url.startswith('http') and not self.loadingTimer.isActive():
            url = QUrl(url)
            request = QNetworkRequest(url)
            request.setHeader(QNetworkRequest.UserAgentHeader, b'CAvatar')
            request.setRawHeader(b'Author', b'Irony')
            request.setAttribute(QNetworkRequest.FollowRedirectsAttribute,
                                 True)
            if qApp._network.cache():
                request.setAttribute(QNetworkRequest.CacheLoadControlAttribute,
                                     QNetworkRequest.PreferNetwork)
                request.setAttribute(QNetworkRequest.CacheSaveControlAttribute,
                                     True)
            reply = qApp._network.get(request)
            self.pradius = 0
            self.loadingTimer.start(50)  # 显示进度动画
            reply.finished.connect(self.onFinished)
            reply.error.connect(self.onError)
            return
        self.pradius = 0
        if os.path.exists(url) and os.path.isfile(url):
            self._pixmap = QPixmap(url)
            self._resizePixmap()
        else:
            self.onError('')
Beispiel #47
0
class GrGraphicItem(gr.sync_block, QLabel):
    def __init__(self,
                 imageFile,
                 scaleImage=True,
                 fixedSize=False,
                 setWidth=0,
                 setHeight=0):
        gr.sync_block.__init__(self,
                               name="GrGraphicsItem",
                               in_sig=None,
                               out_sig=None)
        QLabel.__init__(self)

        if not os.path.isfile(imageFile):
            print("[GrGraphicsItem] ERROR: Unable to find file " + imageFile)
            sys.exit(1)

        try:
            self.pixmap = QPixmap(imageFile)
            self.originalPixmap = QPixmap(imageFile)
        except OSError as e:
            print("[GrGraphicsItem] ERROR: " + e.strerror)
            sys.exit(1)

        self.imageFile = imageFile
        self.scaleImage = scaleImage
        self.fixedSize = fixedSize
        self.setWidth = setWidth
        self.setHeight = setHeight
        super().setPixmap(self.pixmap)
        super().setMinimumSize(1, 1)
        self.overlays = {}

        self.message_port_register_in(pmt.intern("filename"))
        self.set_msg_handler(pmt.intern("filename"), self.msgHandler)

        self.message_port_register_in(pmt.intern("overlay"))
        self.set_msg_handler(pmt.intern("overlay"), self.overlayHandler)

    def overlayHandler(self, msg):
        try:
            overlayitem = pmt.to_python(pmt.car(msg))
            if overlayitem is None:
                print(
                    "[GrGraphicsItem] ERROR: overlay message contains None in the 'car' portion of the message.  Please pass in a dictionary or list of dictionaries in this portion of the message.  Each dictionary should have the following keys: filename,x,y.  Use x=y=-1 to remove an overlay item."
                )
                return

            if type(overlayitem) is dict:
                itemlist = []
                itemlist.append(overlayitem)
            elif type(overlayitem) is list:
                itemlist = overlayitem
            else:
                print(
                    "[GrGraphicsItem] ERROR: Overlay message type is not correct.  Please pass in a dictionary or list of dictionaries in this portion of the message.  Each dictionary should have the following keys: filename,x,y.  Use x=y=-1 to remove an overlay item."
                )
                return

            # Check each dict item to make sure it's valid.
            for curitem in itemlist:
                if type(curitem) == dict:
                    if 'filename' not in curitem:
                        print(
                            "[GrGraphicsItem] ERROR: Dictionary item did not contain the 'filename' key."
                        )
                        print("Received " + str(curitem))
                        continue

                    if 'x' not in curitem:
                        print(
                            "[GrGraphicsItem] ERROR: The dictionary for filename "
                            + curitem['filename'] +
                            " did not contain an 'x' key.")
                        print("Received " + str(curitem))
                        continue

                    if 'y' not in curitem:
                        print(
                            "[GrGraphicsItem] ERROR: The dictionary for filename "
                            + curitem['filename'] +
                            " did not contain an 'y' key.")
                        print("Received " + str(curitem))
                        continue

                    if not os.path.isfile(curitem['filename']):
                        print(
                            "[GrGraphicsItem] ERROR: Unable to find overlay file "
                            + curitem['filename'])
                        print("Received " + str(curitem))
                        continue

                    # Now either add/update our list or remove the item.
                    if curitem['x'] == -1 and curitem['y'] == -1:
                        try:
                            del self.overlays[
                                curitem['filename']]  # remove item
                        except:
                            pass
                    else:
                        self.overlays[curitem['filename']] = curitem

                self.updateGraphic()
        except Exception as e:
            print(
                "[GrGraphicsItem] Error with overlay message conversion: %s" %
                str(e))

    def updateGraphic(self):
        if (len(self.overlays.keys()) == 0):
            try:
                super().setPixmap(self.pixmap)
            except Exception as e:
                print("[GrGraphicsItem] Error updating graphic: %s" % str(e))
                return
        else:
            # Need to deal with overlays
            tmpPxmap = self.pixmap.copy(self.pixmap.rect())
            painter = QPainter(tmpPxmap)
            for curkey in self.overlays.keys():
                curOverlay = self.overlays[curkey]
                try:
                    newOverlay = QPixmap(curkey)
                    if 'scalefactor' in curOverlay:
                        scale = curOverlay['scalefactor']
                        w = newOverlay.width()
                        h = newOverlay.height()
                        newOverlay = newOverlay.scaled(int(w * scale),
                                                       int(h * scale),
                                                       Qtc.KeepAspectRatio)
                    painter.drawPixmap(curOverlay['x'], curOverlay['y'],
                                       newOverlay)
                except Exception as e:
                    print("[GrGraphicsItem] Error adding overlay: %s" % str(e))
                    return

            painter.end()

            super().setPixmap(tmpPxmap)

    def msgHandler(self, msg):
        try:
            newVal = pmt.to_python(pmt.cdr(msg))
            imageFile = newVal
            if type(newVal) == str:
                if not os.path.isfile(imageFile):
                    print("[GrGraphicsItem] ERROR: Unable to find file " +
                          imageFile)
                    return

                try:
                    self.pixmap = QPixmap(imageFile)
                    self.imageFile = imageFile
                except OSError as e:
                    print("[GrGraphicsItem] ERROR: " + e.strerror)
                    return

                self.updateGraphic()
            else:
                print(
                    "[GrGraphicsItem] Error: Value received was not an int or a bool: %s"
                    % str(e))

        except Exception as e:
            print("[GrGraphicsItem] Error with message conversion: %s" %
                  str(e))

    def minimumSizeHint(self):
        return QSize(self.pixmap.width(), self.pixmap.height())

    def resizeEvent(self, event):
        if self.scaleImage:
            w = super().width()
            h = super().height()

            self.pixmap = self.originalPixmap.scaled(w, h, Qtc.KeepAspectRatio)
        elif self.fixedSize and self.setWidth > 0 and self.setHeight > 0:
            self.pixmap = self.originalPixmap.scaled(self.setWidth,
                                                     self.setHeight,
                                                     Qtc.KeepAspectRatio)

        self.updateGraphic()
Beispiel #48
0
class frmMain(QMainWindow):
    def __init__(self):
        super().__init__()

        uic.loadUi('ui/frmMain.ui', self)  # Грузим интерфейс главной формы
        self.set_window_on_center_screen()  # Центрируем окно
        self.load_config()  # Загрузка конфига из файла

        # Привязываем обработчики
        self.btnOpenDB.clicked.connect(self.onOpenDBClick)
        self.btnNext.clicked.connect(self.onClickNext)
        self.btnBack.clicked.connect(self.onClickBack)

        self.lstSVGFiles.itemClicked.connect(self.onSVGFileClicked)
        self.tabWidget.currentChanged.connect(self.onTabWidgetClick)
        self.btnMake_all_sert.clicked.connect(self.make_all_sert)
        self.lstXLSFiles.itemClicked.connect(self.onXLSFileClicked)

        self.btnOpenResults.clicked.connect(self.onOpenResultClick)
        self.btnOpenTemplatesFolder.clicked.connect(
            self.onOpenTemplatesFolderClick)
        self.btnOpenXLSFolder.clicked.connect(self.onOpenXLSFolderClick)
        self.btnHelp.clicked.connect(self.onHelptClick)

        self.txtInkscape.textChanged.connect(self.onTextChanged)

        # Донастраиваем всякие мелочи
        self.noimage = QPixmap(self.img +
                               "/noimage.png")  # Картинка, если нет картинки
        self.ok_img = QPixmap(self.img +
                              "/check.png")  # Картинка, если нет картинки
        self.no_img = QPixmap(self.img +
                              "/remove.png")  # Картинка, если нет картинки

        self.current_step = 0  # Текущий шаг в мастере
        self.tabWidget.setCurrentIndex(
            self.current_step)  # Выставляем нужную вкладку в мастере
        self.is_table_data_loaded = False

        # Декативируем лишние вкладки
        for i in range(1, self.tabWidget.count()):
            self.tabWidget.setTabEnabled(i, False)

        # Проверяем наоличия конвертера в PDF (для windows)
        if isLinux:
            # Убираем поля связанные с inkscape
            self.txtInkscape.hide()
            self.lblInkscape.hide()
            self.lblInkscapeIcon.hide()
        else:
            if not os.path.exists(self.inkscape):
                self.lblInkscapeIcon.setPixmap(self.no_img)
            else:
                self.lblInkscapeIcon.setPixmap(self.ok_img)

    def onOpenDBClick(
            self):  # Открываем второе окно для просмотра базы и поиска по ней
        self.frmDB = db.frmDB()
        self.frmDB.show()

    def onTextChanged(self):
        self.inkscape = self.txtInkscape.text()
        print(self.inkscape)
        if os.path.exists(self.inkscape):
            self.lblInkscapeIcon.setPixmap(self.ok_img)
        else:
            self.lblInkscapeIcon.setPixmap(self.no_img)
            print("ERROR")

    def load_config(self):  # TODO: сделать загрузку конфига из файла
        self.db = "db.sqlite"
        self.table = "info"
        self.templates = "03.templates"  # Каталог с шаблонами сертификатов
        self.img = "img"  # Каталог с картинками к программе
        self.tmp = "tmp"  # Временные файлы
        self.tabledata = "01.input"  # Каталог с файлами xlx
        self.result = "02.output"  # Каталог для результатов работы программы
        self.help = os.path.abspath(os.curdir + "/04.help/index.html")
        # надо вписать полный путь к исполняемому файлу inkscape
        #
        self.inkscape = self.txtInkscape.text()
        #
        ################################################################

    def set_window_on_center_screen(self):  # Окно в ценрт экрана
        screen_geometry = QApplication.desktop().availableGeometry()
        screen_size = (screen_geometry.width(), screen_geometry.height())
        win_size = (self.frameSize().width(), self.frameSize().height())
        x = screen_size[0] // 2 - win_size[0] // 2
        y = screen_size[1] // 2 - win_size[1] // 2
        self.move(x, y)

    def set_NextBackEnabled(
            self):  # Активируем и деактивируем кнопки Вперёд/назад
        if self.current_step == 0:
            self.btnBack.setEnabled(False)
        else:
            self.btnBack.setEnabled(True)

        if self.current_step == self.tabWidget.count() - 1:
            self.btnNext.setEnabled(False)
        else:
            self.btnNext.setEnabled(True)

    def onClickNext(self):  # Кнопка Вперёд

        if not os.path.exists(self.inkscape):
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("Ошибка")
            msg_text = 'Не установлен Inkscape\n'
            msg_text += 'Приложение использует для преобразования SVG файлов в PDF формат внешний редактор - Inkscape\n'
            msg_text += '(https://inkscape.org)\n'
            msg_text += '\n'
            msg.setInformativeText(msg_text)
            msg.setWindowTitle("Ошибка")
            msg.exec_()
            return

        self.current_step += 1  # Переходим к следуюему шагу мастера
        if self.current_step > self.tabWidget.count() - 1:
            self.current_step = self.tabWidget.count() - 1

        self.set_NextBackEnabled()
        # Активируем нужную вкладку и выводим в заголовок название шага
        self.tabWidget.setCurrentIndex(self.current_step)
        out = "<html><head/><body><h1><span>"
        out += self.tabWidget.tabToolTip(self.current_step)
        out += "</span></h1></body></html>"
        self.lblTitle.setText(out)
        self.tabWidget.setTabEnabled(self.current_step, True)
        # Если на Х шаге,
        if self.current_step == 1:  # то грузим первый в списке SVG файл
            self.render_svg(self.txtFileName.text())
            self.get_svg_files_list(self.templates)
            self.lstSVGFiles.setCurrentRow(0)
        elif self.current_step == 2:  # то грузим первый в списке XLS файл
            if not self.is_table_data_loaded:
                self.get_xls_files()
                self.load_table_data()

    def onClickBack(
            self):  # Кнопка Назад, тут почти тоже что и в кнопке Вперёд
        self.current_step -= 1
        if self.current_step < 0:
            self.current_step = 0

        self.set_NextBackEnabled()

        self.tabWidget.setCurrentIndex(self.current_step)
        out = "<html><head/><body><h1><span>"
        out += self.tabWidget.tabToolTip(self.current_step)
        out += "</span></h1></body></html>"
        self.lblTitle.setText(out)

    def onTabWidgetClick(self, new_index):  # Клики по вкладкам
        self.current_step = new_index
        self.set_NextBackEnabled()

    def onSVGFileClicked(self, item):  # Клик по SVG файлу в списке
        self.txtFileName.setText(item.text())
        self.render_svg(self.txtFileName.text())

    def render_svg(self,
                   filename):  # Делаем превьюшку для SVG и отображаем в окне
        filename = self.templates + "/" + filename
        if os.path.exists(filename):
            self.pixmap = QPixmap(filename)
            self.lblSVG.setPixmap(
                self.pixmap.scaled(self.lblSVG.frameGeometry().width(),
                                   self.lblSVG.frameGeometry().height(), True,
                                   True))
        else:
            self.lblSVG.setPixmap(self.noimage)

    def get_svg_files_list(
            self, path):  # Получаем список SVG файлов из каталога с шаблонами
        if path:
            self.lstSVGFiles.clear()
            files = sorted(os.listdir(path))
            files = list(i for i in files if i[-3:] == "svg")
            if files:
                self.lstSVGFiles.addItems(files)

    def onXLSFileClicked(self, item):  # Клик по XLS файлу в списке
        self.tableWidget.clear()
        self.load_table_data()

    def get_xls_files(self):  # ПОлучаем список всех табличных файлов
        self.lstXLSFiles.clear()
        files = sorted(os.listdir(self.tabledata))
        files = list(i for i in files if i[-3:] == "xls")
        if files:
            self.lstXLSFiles.addItems(files)
        else:
            print('Нет табличных файлов :-(')

    def load_table_data(
            self
    ):  # Загружаем данные из табличного файла, по которому кликнули
        if not self.is_table_data_loaded:
            self.lstXLSFiles.setCurrentRow(0)
        filename = self.tabledata + "/" + self.lstXLSFiles.item(
            self.lstXLSFiles.currentRow()).text()
        book = xlrd.open_workbook(filename)
        sheet = book.sheets()[0]
        headers = [[sheet.cell_value(r, c) for c in range(sheet.ncols)]
                   for r in range(sheet.nrows)]
        self.tableWidget.setColumnCount(len(headers[0]))
        self.tableWidget.setRowCount(len(headers) - 1)
        self.tableWidget.setHorizontalHeaderLabels(headers[0])
        for i in range(1, len(headers)):
            for j in range(len(headers[0])):
                self.tableWidget.setItem(i - 1, j,
                                         QTableWidgetItem(str(headers[i][j])))
        self.is_table_data_loaded = True
        self.headers = headers[
            0]  # сохраняем заголовок таблицы с образцами для замены в SVG

    def load_svg(self, filename):  # Грузим в память весь SVG файл
        filename = self.templates + "/" + filename
        f = open(filename, encoding="utf8")
        data = f.readlines()
        f.close()
        return data

    def get_row(self, row):  # Делаем список из строки таблицы
        r = []
        for col in range(self.tableWidget.columnCount()):
            if self.tableWidget.item(row, col):
                # Костыль для удаления дробной части числа
                r.append(
                    self.tableWidget.item(row, col).text().replace(".0", ""))
        return r

    def create_new_svg(self, original_svg_data,
                       data_to_replace):  # Делаем новый временный SVG файл
        buf = original_svg_data[:]
        for i in range(len(self.headers)):
            for j in range(len(buf)):
                try:
                    if self.headers[i] in buf[j]:
                        buf[j] = buf[j].replace(self.headers[i],
                                                data_to_replace[i])
                except:
                    print("Ошибка")
        f = open(self.tmp + "/tmp.svg", "w", encoding="utf8")
        f.writelines(buf)
        f.close()

    def create_pdf(self, row_data, row_number):
        # Делаем имя файла из пары столбцов в текущей строке (Имя, номер по порядку и серийсный номер)
        if row_data:
            filename = str(row_number) + row_data[0] + row_data[3] + ".pdf"
            # Если линукс, то пользуемся модулем cairosvg
            if isLinux:
                cairosvg.svg2pdf(url=self.tmp + "/tmp.svg",
                                 write_to=self.result + "/" + filename)
            else:
                # print("Это не Linux, нужно установить inkscape")
                command = self.inkscape + ' '
                args = '"' + self.tmp + '/tmp.svg" '
                args += '--export-type="pdf" '
                args += '--export-filename='
                args += '"' + self.result + "/" + filename + '"'
                os.system(command + args)

    def make_all_sert(self, filename):  # Делаем сертификаты
        original_svg_data = self.load_svg(
            self.txtFileName.text())  # Оригинальные текст SVG файла
        self.progressBar.setMaximum(self.tableWidget.rowCount() -
                                    1)  # Выставляем максимум для прогресс-бара
        # Просматриваем построчно таблицу
        self.set_all_disabled()
        self.txtLog.append("Создаём сертификат:")
        for row in range(self.tableWidget.rowCount()):
            self.create_new_svg(original_svg_data,
                                self.get_row(row))  # Делаем временный файл SVG
            self.create_pdf(self.get_row(row),
                            row)  # Делаем из SVG уже готовую PDF-ку
            self.progressBar.setValue(row)  # Сдвигаем полосу прогресса
            self.db_add_new_data(self.get_row(row), self.headers)
            self.txtLog.append(" " * 4 + str(row) + "." + self.get_row(row)[0])
        self.txtLog.append("Работа завершена")
        self.set_all_enabled()

    def set_all_disabled(self):  # Отключение кнопок после запуска генерации
        self.btnMake_all_sert.setEnabled(False)
        self.btnOpenResults.setEnabled(False)
        self.btnBack.setEnabled(False)

    def set_all_enabled(
            self):  # Включение кнопок после завершения процесса генерации
        self.btnMake_all_sert.setEnabled(True)
        self.btnOpenResults.setEnabled(True)
        self.btnBack.setEnabled(True)

    def onOpenResultClick(self):  # Открываем папку с результатом работы
        self.open_dir(self.result)

    def onOpenTemplatesFolderClick(self):  # Открываем папку с шаблонами
        self.open_dir(self.templates)

    def onOpenXLSFolderClick(self):  # Открываем папку с таблиными файлами
        self.open_dir(self.tabledata)

    def open_dir(self, path):  # Открытие папок
        if platform.system() == "Windows":
            os.startfile(path)
        elif platform.system() == "Darwin":
            subprocess.Popen(["open", path])
        else:
            subprocess.Popen(["xdg-open", path])

    def onHelptClick(self):
        url = self.help
        webbrowser.open(url, new=0, autoraise=True)

    def db_add_new_data(
        self, data, headers
    ):  # Добавляем инфу в базу данных о каждом генерируемом сертификате
        try:
            self.con = sqlite3.connect(self.db)
            self.cur = self.con.cursor()
            query = "INSERT INTO info(name,event,date,sn) VALUES "
            query += "('" + data[0] + "','"
            query += data[1] + "','"
            query += data[2] + "','"
            query += data[3]
            query += "')"
            result = self.cur.execute(query).fetchall()
            self.con.commit()
            self.con.close()
        except:
            print("Ошибка: не могу записать данные в базу")
Beispiel #49
0
class Window(QMainWindow):
    """Main Window."""
    def __init__(self, parent=None):
        """Initializer."""
        super().__init__(parent)
        self.setWindowTitle('WallPaperChanger')
        self.setCentralWidget(QLabel("I'm the Central Widget"))
        self._createMenu()
        self._createToolBar()
        self._createStatusBar()

        try:
            os.mkdir('pics')
        except FileExistsError:
            pass

        self.layout = QGridLayout()
        self.window = QWidget()

        self.btn = QPushButton('Change Via Online Pics')
        self.btn.clicked.connect(self.fetch_online_wallpaper)
        self.progress_bar = QProgressBar()
        self.progress_bar.setMaximum(100)
        self.c_status = QLabel('')
        self.connect_label = QLabel()
        has_internet = is_connected()
        if has_internet:
            self.pixmap = QPixmap('ctrl_icons/checked.png')
        else:
            self.pixmap = QPixmap('ctrl_icons/cancel.png')
        self.smaller_pixmap = self.pixmap.scaled(32, 32,
                                                 QtCore.Qt.KeepAspectRatio,
                                                 QtCore.Qt.FastTransformation)
        self.connect_label.setPixmap(self.smaller_pixmap)
        self.stats = QLabel('Internet On: {}<br>Offline Images: {}'.format(
            has_internet, num_files()))

        self.prev_but = QPushButton()
        self.prev_but.clicked.connect(self.prev_pic)
        prev_but_icon = QPixmap("ctrl_icons/previous.png")
        self.prev_but.setIcon(QIcon(prev_but_icon))

        self.next_but = QPushButton()
        self.next_but.clicked.connect(self.next_pic)
        next_but_icon = QPixmap("ctrl_icons/next-1.png")
        self.next_but.setIcon(QIcon(next_but_icon))

        self.rand_but = QPushButton()
        self.rand_but.clicked.connect(self.choose_randpic)
        rand_but_icon = QPixmap("ctrl_icons/refresh-1.png")
        self.rand_but.setIcon(QIcon(rand_but_icon))

        self.delete_img_but = QPushButton()
        self.delete_img_but.clicked.connect(self.confirm_img_deletion)
        delete_img_but_icon = QPixmap("ctrl_icons/cancel.png")
        self.delete_img_but.setIcon(QIcon(delete_img_but_icon))

        self.showofflinepic_label = QLabel()
        self.showofflinepic_label.setAlignment(Qt.AlignCenter)
        self.showofflinepic_label.setFixedSize(300, 300)
        self.choose_randpic()

        self.chooseoffline_but = QPushButton('Change via Offline Pic')
        self.chooseoffline_but.clicked.connect(self.change_offline_pic)

        self.layout.addWidget(self.connect_label, 0, 2)
        self.layout.addWidget(self.stats, 0, 1)
        self.layout.addWidget(self.btn, 1, 1, 1, 2)
        self.layout.addWidget(self.progress_bar, 2, 1, 1, 2)
        self.layout.addWidget(self.c_status, 3, 1, 1, 2)
        self.layout.addWidget(self.prev_but, 4, 0)
        self.layout.addWidget(self.showofflinepic_label, 4, 1, 1, 2)
        self.layout.addWidget(self.next_but, 4, 3)
        self.layout.addWidget(self.rand_but, 5, 1, 1, 2)
        self.layout.addWidget(self.delete_img_but, 6, 1, 1, 2)
        self.layout.addWidget(self.chooseoffline_but, 7, 1, 1, 2)

        self.window.setLayout(self.layout)
        self.setWindowIcon(QIcon('icon.jpg'))
        self.setCentralWidget(self.window)

    def _createMenu(self):
        self.menu = self.menuBar().addMenu("&Menu")
        self.menu.addAction('&Exit', self.close)

    def _createToolBar(self):
        tools = QToolBar()
        self.addToolBar(tools)
        tools.addAction('Exit', self.close)

    def _createStatusBar(self):
        status = QStatusBar()
        status.showMessage("")
        self.setStatusBar(status)

    def fetch_online_wallpaper(self):
        self.c_status.setText('starting ...')
        self.progress_bar.setValue(0)
        self.wallpaper_change()
        self.progress_bar.setValue(100)
        self.c_status.setText('completed!')

    def display_pic(self, pic_name):
        self.showofflinepic_pixmap = QPixmap('pics/{}'.format(pic_name))
        self.smaller_showofflinepic_pixmap = self.showofflinepic_pixmap.scaled(
            300, 300, QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation)
        self.showofflinepic_label.setPixmap(self.smaller_showofflinepic_pixmap)

    def choose_randpic(self):
        self.offline_pics = deque(pic_files())
        if self.offline_pics:
            self.chosen_offlinepic = random.choice(self.offline_pics)
            self.display_pic(self.chosen_offlinepic)

    def prev_pic(self):
        self.offline_pics.rotate(1)
        self.chosen_offlinepic = self.offline_pics[0]
        self.display_pic(self.chosen_offlinepic)

    def next_pic(self):
        self.offline_pics.rotate(-1)
        self.chosen_offlinepic = self.offline_pics[0]
        self.display_pic(self.chosen_offlinepic)

    def change_offline_pic(self):
        self.wallpaper_change(offline_pic=self.chosen_offlinepic)

    def set_step_status(self, text):
        self.c_status.setText(text)
        QApplication.processEvents()

    def confirm_img_deletion(self):
        buttonReply = QMessageBox.question(
            self, 'Delete confirmation',
            "Do you really want to delete this picture?",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if buttonReply == QMessageBox.Yes:
            print('Yes clicked.')
            # remove image
            os.remove('pics/{}'.format(self.chosen_offlinepic))
            # update display
            self.choose_randpic()
        else:
            print('No clicked.')

    def wallpaper_change(self, offline_pic=None):
        try:
            if offline_pic:
                Fpath = os.path.realpath(os.getcwd())
                pic_path = os.path.join(os.sep, Fpath, 'pics',
                                        '{}'.format(offline_pic))
                ctypes.windll.user32.SystemParametersInfoW(20, 0, pic_path, 0)
            else:
                img_urls = []

                headers = {
                    'User-Agent':
                    'Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0',
                    'Accept':
                    'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                    'Accept-Language': 'en-US,en;q=0.5',
                    'Accept-Encoding': 'deflate',
                    'Connection': 'keep-alive',
                    'Upgrade-Insecure-Requests': '1',
                    'Cache-Control': 'max-age=0',
                    'TE': 'Trailers'
                }
                random.shuffle(sub_reddits)

                self.set_step_status('gathering images ...')
                for i, sub_reddit in enumerate(sub_reddits):
                    self.set_step_status('passing over source: {}'.format(i +
                                                                          1))
                    req = requests.get(
                        'https://www.reddit.com/r/{}/.json'.format(sub_reddit),
                        headers=headers)
                    jsondata = req.json()
                    # print(jsondata)
                    posts = jsondata['data']['children']
                    current_urls = [
                        post['data']['url'] for post in posts
                        if (post['data']['url']
                            ).split('.')[-1] in ['jpg', 'jpeg', 'png']
                        and 'imgur' not in post['data']['url']
                    ]
                    img_urls += current_urls
                print('found', img_urls)
                chosen_img = random.choice(img_urls)
                self.progress_bar.setValue(50)
                self.set_step_status('choosing image ...')
                print('choose', chosen_img)
                chosen_img_name = '{}.{}'.format(chosen_img[::-8],
                                                 get_ext(chosen_img))
                chosen_img_path = 'pics/{}'.format(chosen_img_name)

                self.set_progress(75)
                self.set_step_status('fetching image ...')
                download_file(chosen_img, chosen_img_path)

                Fpath = os.path.realpath(os.getcwd())
                pic_path = os.path.join(os.sep, Fpath, 'pics', chosen_img_name)
                self.chosen_offlinepic = chosen_img_name
                self.offline_pics.append(chosen_img_name)
                self.display_pic(self.chosen_offlinepic)
                self.set_progress(90)
                self.set_step_status('setting image ...')
                ctypes.windll.user32.SystemParametersInfoW(20, 0, pic_path, 0)
        except Exception as e:
            print('error', e)

    def set_progress(self, value):
        self.progress_bar.setValue(value)
Beispiel #50
0
    def __init__(self, game: InstalledGame, core: LegendaryCore):
        super(GameWidget, self).__init__()
        self.core = core
        self.game = game
        self.dev = core.get_game(self.game.app_name).metadata["developer"]
        self.title = game.title
        self.app_name = game.app_name
        self.version = game.version
        self.size = game.install_size
        self.launch_params = game.launch_parameters
        # self.dev =
        self.game_running = False
        self.layout = QHBoxLayout()
        if os.path.exists(f"{IMAGE_DIR}/{game.app_name}/FinalArt.png"):
            pixmap = QPixmap(f"{IMAGE_DIR}/{game.app_name}/FinalArt.png")
        elif os.path.exists(
                f"{IMAGE_DIR}/{game.app_name}/DieselGameBoxTall.png"):
            pixmap = QPixmap(
                f"{IMAGE_DIR}/{game.app_name}/DieselGameBoxTall.png")
        elif os.path.exists(
                f"{IMAGE_DIR}/{game.app_name}/DieselGameBoxLogo.png"):
            pixmap = QPixmap(
                f"{IMAGE_DIR}/{game.app_name}/DieselGameBoxLogo.png")
        else:
            logger.warning(f"No Image found: {self.game.title}")
            pixmap = None
        if pixmap:

            pixmap = pixmap.scaled(180, 240)
            self.image = QLabel()
            self.image.setPixmap(pixmap)
            self.layout.addWidget(self.image)

        ##Layout on the right
        self.childLayout = QVBoxLayout()

        play_icon = self.style().standardIcon(getattr(QStyle, 'SP_MediaPlay'))
        settings_icon = self.style().standardIcon(getattr(
            QStyle, 'SP_DirIcon'))
        self.title_widget = QLabel(f"<h1>{self.title}</h1>")
        self.launch_button = QPushButton(play_icon, "Launch")
        self.launch_button.clicked.connect(self.launch)
        self.wine_rating = QLabel("Wine Rating: " + self.get_rating())
        self.developer_label = QLabel("Dev: " + self.dev)
        self.version_label = QLabel("Version: " + str(self.version))
        self.size_label = QLabel(
            f"Installed size: {round(self.size / (1024 ** 3), 2)} GB")
        self.settings_button = QPushButton(settings_icon,
                                           " Settings (Icon TODO)")
        self.settings_button.clicked.connect(self.settings)

        self.childLayout.addWidget(self.title_widget)
        self.childLayout.addWidget(self.launch_button)
        self.childLayout.addWidget(self.developer_label)
        self.childLayout.addWidget(self.wine_rating)
        self.childLayout.addWidget(self.version_label)
        self.childLayout.addWidget(self.size_label)
        self.childLayout.addWidget(self.settings_button)

        self.childLayout.addStretch(1)
        self.layout.addLayout(self.childLayout)
        self.layout.addStretch(1)
        self.setLayout(self.layout)
class MainWindow(object):
    SCREEN_HEIGHT = 800
    SCREEN_WIDTH = 800
    def __init__(self):
        self.app = QApplication([])
        self.window = QMainWindow()
        self.window.setFixedSize(self.SCREEN_WIDTH,self.SCREEN_HEIGHT)
        self.window.setWindowTitle('Segment Splitter')
        self.icon = QtGui.QIcon()
        self.icon.addPixmap(QtGui.QPixmap("ico.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.window.setWindowIcon(self.icon)

        ###################
        # INPUT
        ###################
            
        self.title_container = QLabel(self.window)
        self.title_container.setGeometry(QtCore.QRect(0, 0, self.SCREEN_WIDTH, 50))
        # self.title_container = self.set_white(self.title_container)
        
        self.title_label = QLabel("Segment Splitter",self.window)
        self.title_label.setGeometry(QtCore.QRect(0, 0, self.SCREEN_WIDTH, 50))
        self.title_label.setAlignment(QtCore.Qt.AlignCenter)
        
        self.title_label_border = QFrame(self.window)
        self.title_label_border.setGeometry(QtCore.QRect(0, 0, self.SCREEN_WIDTH, 50))
        self.title_label_border.setStyleSheet("border:2px solid rgb(0, 0, 0); ")
        
        self.video_label = QLabel("Input video path:",self.window)
        self.video_label.setGeometry(QtCore.QRect(10, 60, 120, 30))
        self.video_label.setToolTip('Choose the video to split into segments based.\nAccepted formats are mp4, flv and mkv.')
        
        self.video_label_input = QLineEdit("",self.window)
        self.video_label_input.setGeometry(QtCore.QRect(140, 60, 550, 30))
        self.video_label_input.setToolTip('Choose the video to split into segments based.\nAccepted formats are mp4, flv and mkv.')
        
        self.video_button = QPushButton("Browse",self.window)
        self.video_button.setGeometry(QtCore.QRect(700, 60, 80, 30))
        self.video_button.clicked.connect(self.video_input_click)
        
        self.start_split_header = QLabel("Start split image:",self.window)
        self.start_split_header.setGeometry(QtCore.QRect(30, 100, 120, 30))
        self.start_split_header.setToolTip('Choose the image that each clip will start on.\nRefer to GitHub instructions for producing best images.')
        
        self.start_split_button = QPushButton("Browse",self.window)
        self.start_split_button.setGeometry(QtCore.QRect(200, 100, 80, 30))
        self.start_split_button.clicked.connect(self.start_split_image_click)
        
        self.start_split_picture = QLabel("",self.window)
        self.start_split_picture.setGeometry(QtCore.QRect(30, 140, 250, 250))
        self.start_split_picture.setAlignment(QtCore.Qt.AlignCenter)
        
        self.start_split_border = QFrame(self.window)
        self.start_split_border.setGeometry(QtCore.QRect(30, 140, 250, 250))
        self.start_split_border.setStyleSheet("border:2px solid rgb(0, 0, 0); ")
        
        self.end_split_header = QLabel("End split image:",self.window)
        self.end_split_header.setGeometry(QtCore.QRect(300, 100, 120, 30))
        self.end_split_header.setToolTip('Choose the image that each clip will end on.\nIf using single split option, leave this blank.\nRefer to GitHub instructions for producing best images.')
        
        self.end_split_button = QPushButton("Browse",self.window)
        self.end_split_button.setGeometry(QtCore.QRect(470, 100, 80, 30))
        self.end_split_button.clicked.connect(self.end_split_image_click)
        
        self.end_split_picture = QLabel("",self.window)
        self.end_split_picture.setGeometry(QtCore.QRect(300, 140, 250, 250))
        self.end_split_picture.setAlignment(QtCore.Qt.AlignCenter)
        
        self.end_split_border = QFrame(self.window)
        self.end_split_border.setGeometry(QtCore.QRect(300, 140, 250, 250))
        self.end_split_border.setStyleSheet("border:2px solid rgb(0, 0, 0); ")
        
        ###################
        # OPTIONS
        ###################
                
        self.start_threshold_label = QLabel("Start split threshold:",self.window)
        self.start_threshold_label.setGeometry(QtCore.QRect(560, 140, 160, 30))
        self.start_threshold_label.setToolTip('This value influences how strict the image matching is. \n2D games should be a tight value around 50, whereas 3D games can go up to ~500.\nIf the program makes too many segments, lower the value.\nIf the program makes too few segments, increase the value.')  
        
        self.start_threshold_input = QLineEdit("50",self.window)
        self.start_threshold_input.setValidator(QIntValidator(self.start_threshold_input))
        self.start_threshold_input.setGeometry(QtCore.QRect(720, 143, 40, 25))
        
        self.end_threshold_label = QLabel("End split threshold:",self.window)
        self.end_threshold_label.setGeometry(QtCore.QRect(560, 170, 160, 30))
        self.end_threshold_label.setToolTip('This value influences how strict the image matching is. \n2D games should be a tight value around 50, whereas 3D games can go up to ~500.\nIf the program makes too many segments, lower the value.\nIf the program makes too few segments, increase the value.')
        
        self.end_threshold_input = QLineEdit("50",self.window)
        self.end_threshold_input.setValidator(QIntValidator(self.end_threshold_input))
        self.end_threshold_input.setGeometry(QtCore.QRect(720, 173, 40, 25))
        
        self.frame_buffer_label = QLabel("Split wait buffer:",self.window)
        self.frame_buffer_label.setGeometry(QtCore.QRect(560, 200, 160, 30))
        self.frame_buffer_label.setToolTip('This value influences how long after each split \nto wait before checking for the next split.')
        
        self.frame_buffer_input = QLineEdit("60",self.window)
        self.frame_buffer_input.setValidator(QIntValidator(self.frame_buffer_input))
        self.frame_buffer_input.setGeometry(QtCore.QRect(720, 203, 40, 25))
        
        self.start_pre_roll_label = QLabel("Start pre-roll:",self.window)
        self.start_pre_roll_label.setGeometry(QtCore.QRect(560, 230, 160, 30))
        self.start_pre_roll_label.setToolTip('This value will dictate how many frames before the desired split to crop.\nAs an example, if a segment is 60 frames, setting this pre-roll\nto 30 frames will create a 90 frame clip, where the \nbeginning of the split starts 30 frames in.')
        
        self.start_pre_roll_label_input = QLineEdit("0",self.window)
        self.start_pre_roll_label_input.setValidator(QIntValidator(self.frame_buffer_input))
        self.start_pre_roll_label_input.setGeometry(QtCore.QRect(720, 233, 40, 25))
        
        self.end_post_roll_label = QLabel("End post-roll:",self.window)
        self.end_post_roll_label.setGeometry(QtCore.QRect(560, 260, 160, 30))
        self.end_post_roll_label.setToolTip('This value will dictate how many frames after the desired split to crop.\nAs an example, if a segment is 100 frames, setting this post-roll\nto 30 frames will create a 130 frame clip, where the \nsplit starts immediately and has 30 frames extra of video \nafter the split ends.')
        
        self.end_post_roll_label_input = QLineEdit("0",self.window)
        self.end_post_roll_label_input.setValidator(QIntValidator(self.frame_buffer_input))
        self.end_post_roll_label_input.setGeometry(QtCore.QRect(720, 263, 40, 25))
        
        self.create_video_checkbox = QCheckBox("Create video clips",self.window)
        self.create_video_checkbox.setGeometry(QtCore.QRect(560, 320, 150, 30))
        self.create_video_checkbox.setToolTip('Creates video clips of split segments when checked.\nIf only a log of frame windows per segment is desired (without splitting video), then uncheck.\nUnchecking will result in faster processing time.')
        self.create_video_checkbox.setChecked(True)

        self.single_split_checkbox = QCheckBox("Split on start image only",self.window)
        self.single_split_checkbox.setGeometry(QtCore.QRect(560, 350, 200, 30))
        self.single_split_checkbox.setToolTip('Use this setting if the start and end of each segment should only rely upon one image. \nThe starting image will be used.')


        
        
        ###################
        # OUTPUT  
        ###################
        
        self.output_dir_label = QLabel("Output path:",self.window)
        self.output_dir_label.setToolTip('Output path for videos & output log. If left blank, a new directory will be created.')
        self.output_dir_label.setGeometry(QtCore.QRect(10, 400, 120, 30))
        
        self.output_dir_label_input = QLineEdit("",self.window)
        self.output_dir_label_input.setGeometry(QtCore.QRect(140, 400, 550, 30))
        self.output_dir_label_input.setToolTip('Output path for videos & output log. If left blank, a new directory will be created.')
        
        self.output_dir_button = QPushButton("Browse",self.window)
        self.output_dir_button.setGeometry(QtCore.QRect(700, 400, 80, 30))
        self.output_dir_button.clicked.connect(self.output_dir_click)
        
        ###################
        # PROCESSING & LOG
        ###################
        
        self.process_video = QPushButton("PUSH TO BEGIN PROCESSING",self.window)
        self.process_video.setGeometry(QtCore.QRect(50, 450, 700, 30))
        self.process_video.clicked.connect(self.process_video_click)
        self.process_video.setToolTip('Begins processing based on parameters. Options and file paths will be valided before running.')
        
        self.log_header_label = QLabel("Console log:",self.window)
        self.log_header_label.setGeometry(QtCore.QRect(10, 480, 120, 30))

        self.log_output = QTextEdit(self.window)
        self.log_output.setGeometry(QtCore.QRect(30, 510, 740, 250))
        # self.log_output = self.set_white(self.log_output)
        self.log_output.verticalScrollBar().setValue(self.log_output.verticalScrollBar().minimum())
        
        self.log_output_thread = LogThread(self.window)
        self.log_output_thread.log.connect(self.update_log_text)
        # self.log_output_thread.started.connect(lambda: self.update_log('start'))
        
        
        self.log_clear_button = QPushButton("Clear Log",self.window)
        self.log_clear_button.setGeometry(QtCore.QRect(30, 765, 80, 30))
        self.log_clear_button.clicked.connect(self.clear_log)        
        
        self.processing_reset_button = QPushButton("Reset Processing",self.window)
        self.processing_reset_button.setGeometry(QtCore.QRect(120, 765, 130, 30))
        self.processing_reset_button.clicked.connect(self.reset_processing)
        self.processing_reset_button.setToolTip('If the Push to Begin Processing bar is inactive, use this to reset.')
#        
#        self.log_label_border = QFrame(self.window)
#        self.log_label_border.setGeometry(QtCore.QRect(30, 510, 740, 250))
#        self.log_label_border.setStyleSheet("border:2px solid rgb(0, 0, 0); ")
                
        self.github_label = QLabel("https://github.com/cleartonic/segment_splitter",self.window)
        urlLink="<a href=\'https://github.com/cleartonic/segment_splitter'>https://github.com/cleartonic/segment_splitter</a>" 
        self.github_label.setText(urlLink)
        self.github_label.setGeometry(QtCore.QRect(470, 770, 400, 50))
        self.github_label.setAlignment(QtCore.Qt.AlignBottom)
        self.github_label.setAlignment(QtCore.Qt.AlignLeft)
        self.github_label.setOpenExternalLinks(True)
        
        # Final settings
        self.app.setStyle('Fusion')
        self.app.setFont(QtGui.QFont("Segoe UI", 12))
        
        palette = QPalette()
        palette.setColor(QPalette.Window, QColor(53, 53, 53))
        palette.setColor(QPalette.WindowText, QColor(255, 255, 255))
        palette.setColor(QPalette.Base, QColor(25, 25, 25))
        palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
        palette.setColor(QPalette.ToolTipBase, QColor(255, 255, 255))
        palette.setColor(QPalette.ToolTipText, QColor(255, 255, 255))
        palette.setColor(QPalette.Text, QColor(255, 255, 255))
        palette.setColor(QPalette.Button, QColor(53, 53, 53))
        palette.setColor(QPalette.ButtonText, QColor(255, 255, 255))
        palette.setColor(QPalette.BrightText, QColor(120, 120, 0))
        palette.setColor(QPalette.Link, QColor(42, 130, 218))
        palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
        palette.setColor(QPalette.HighlightedText, QColor(0, 0, 0))
        self.app.setPalette(palette)
        
        
    ###############################
    # FUNCTIONS
    ###############################
#    def update_log(self, message):
#        # self.log_output.append(str(message))
        
    def update_log(self, text):
        self.log_output_thread.setText(text)
        self.log_output_thread.start()
        
    def update_log_text(self, val):
        self.log_output.append(str(val))
        
    def clear_log(self, message):
        self.log_output.setText("")
        
    def reset_processing(self, message):
        self.process_video.setEnabled(True)
        
    def set_white(self,obj):
        obj.setAutoFillBackground(True)
        p = obj.palette()
        p.setColor(obj.backgroundRole(),QColor(255, 255, 255))
        obj.setPalette(p)
        return obj
    
    def video_input_click(self):
        dialog = QFileDialog()
        new_file = dialog.getOpenFileName(None,"Select video","",filter="mp4 (*.mp4);;flv (*.flv);;mkv (*.mkv)")
        self.video_label_input.setText(new_file[0])
        
    def output_dir_click(self):
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.DirectoryOnly)
        if dialog.exec_() == QDialog.Accepted:
            self.output_dir_label_input.setText(dialog.selectedFiles()[0])

    def start_split_image_click(self):
        dialog = QFileDialog()
        new_file = dialog.getOpenFileName(None,"Select split image","",filter="png (*.png);;jpeg (*.jpeg);;jpg (*.jpg)")
        if QDialog.Accepted:
            self.start_split_image_loc = new_file[0]
            self.start_split_pixmap = QPixmap(new_file[0])
            self.start_split_picture.setPixmap(self.start_split_pixmap.scaled(250, 250, QtCore.Qt.KeepAspectRatio))

    def end_split_image_click(self):
        dialog = QFileDialog()
        new_file = dialog.getOpenFileName(None,"Select split image","",filter="png (*.png);;jpeg (*.jpeg);;jpg (*.jpg)")
        if QDialog.Accepted:
            self.end_split_image_loc = new_file[0]
            self.end_split_pixmap = QPixmap(new_file[0])
            self.end_split_picture.setPixmap(self.end_split_pixmap.scaled(250, 250, QtCore.Qt.KeepAspectRatio))
            
    def process_video_click(self):
        validate_flag = self.validate_input()
        if type(validate_flag) == bool and validate_flag:
            self.update_log("Success on inputs, beginning generation.")
            self.process_video.setEnabled(False)
            QTimer.singleShot(1, lambda: self.begin_video_processing())
        else:
            self.update_log(validate_flag)

            
    def begin_video_processing(self):
            self.video_processor = VideoProcessor(self, self.processing_start_split_image, self.processing_end_split_image, \
                                             self.processing_video_cv2_cap, self.processing_video_moviepy_cap, \
                                             self.processing_output_dir_label_input, \
                                             self.processing_single_split_checkbox, \
                                             self.processing_create_video_checkbox, \
                                             self.processing_start_threshold, \
                                             self.processing_end_threshold, \
                                             100, \
                                             self.processing_frame_buffer, \
                                             -self.processing_start_pre_roll, \
                                             self.processing_end_post_roll) # Scan size (100) hardcoded for now
            self.video_processor_thread = VideoProcessorThread(self.video_processor)
            self.video_processor_thread.start()
            
    def validate_input(self):
        ############
        # Validate the inputs for running the process
        ############
        pass_flag = True
           
        # THRESHOLDS
        try:
            self.processing_start_threshold = int(main_window.start_threshold_input.text())
            if self.processing_start_threshold <= 0 or self.processing_start_threshold > 1000:
                return "Start threshold needs to be between 1 - 1000."
            self.processing_end_threshold = int(main_window.end_threshold_input.text())
            if self.processing_end_threshold <= 0 or self.processing_end_threshold > 1000:
                return "End threshold needs to be between 1 - 1000."            
            self.processing_frame_buffer = int(main_window.frame_buffer_input.text())
            if self.processing_frame_buffer <= 0 or self.processing_frame_buffer  > 1000:
                return "Frame buffer needs to be between 1 - 1000."
            self.processing_start_pre_roll = int(main_window.start_pre_roll_label_input.text())
            if self.processing_start_pre_roll < 0 or self.processing_start_pre_roll > 1000:
                return "Start pre-roll needs to be between 0 - 1000."
            self.processing_end_post_roll = int(main_window.end_post_roll_label_input.text())
            if self.processing_end_post_roll < 0 or self.processing_end_post_roll> 1000:
                return "End pre-roll needs to be between 0 - 1000."
        except Exception as e:
            print("Error on thresholds, check thresholds and resubmit: "+str(e))
            return "Error on thresholds, check thresholds and resubmit"
            
        # CHECKMARKS
        try:
            if self.single_split_checkbox.checkState() == 0:
                self.processing_single_split_checkbox = False
            else:
                self.processing_single_split_checkbox = True
            if self.create_video_checkbox.checkState() == 0:
                self.processing_create_video_checkbox = False
            else:
                self.processing_create_video_checkbox = True
        except:
            pass
        # START IMAGE
        try:
            self.processing_start_split_image = cv2.imread(self.start_split_image_loc)
            if type(self.processing_start_split_image) != np.ndarray:
                return "Failure to validate start split as image."
        except Exception as e:
            print("Failure to validate start split as image: "+str(e))
            return "Failure to validate start split as image"
            
        # END IMAGE
        try:
            if not self.processing_single_split_checkbox:
                self.processing_end_split_image = cv2.imread(self.end_split_image_loc)
                if type(self.processing_end_split_image) != np.ndarray:
                    return "Failure to validate end split as image."
            else:
                self.processing_end_split_image = None
        except Exception as e:
            print("Failure to validate end split as image: "+str(e))
            return "Failure to validate end split as image"
        
        # INPUT PATH
        try:
            print("Video path: "+self.video_label_input.text())
            self.processing_video_cv2_cap = cv2.VideoCapture(self.video_label_input.text())
            self.processing_video_moviepy_cap = mp.VideoFileClip(self.video_label_input.text())
        except Exception as e:
            print("Failure to load : "+str(e))
            return "Failure to load video file"

        # OUTPUT PATH
        try:
            if self.output_dir_label_input.text() == '':
                timestamp = datetime.datetime.now().strftime("%m-%d-%Y_%H-%M-%S")
                if not os.path.exists(os.path.join(THIS_FILEPATH,'output')):
                    os.mkdir(os.path.join(THIS_FILEPATH,'output'))
                new_dir = os.path.abspath(os.path.join(THIS_FILEPATH,'output',timestamp))
                self.update_log("Creating new directory for current load: "+new_dir)
                os.mkdir(new_dir)
                self.processing_output_dir_label_input = new_dir
            else:
                if not os.path.exists(self.output_dir_label_input.text()):
                    return "Failure on output directory, provide a valid directory path"
                else:
                    self.processing_output_dir_label_input = os.path.abspath(self.output_dir_label_input.text())
                    return "Setting output dir to: "+str(self.output_dir_label_input.text())

        except Exception as e:
            print("Failure on output directory, provide a valid directory path: "+str(e))
            return "Failure on output directory, provide a valid directory path"

        return pass_flag
Beispiel #52
0
    def add_tx_stats(self, vbox):
        hbox_stats = QHBoxLayout()

        # left column
        vbox_left = QVBoxLayout()
        self.tx_desc = TxDetailLabel(word_wrap=True)
        vbox_left.addWidget(self.tx_desc)
        self.status_label = TxDetailLabel()
        vbox_left.addWidget(self.status_label)
        self.date_label = TxDetailLabel()
        vbox_left.addWidget(self.date_label)
        self.amount_label = TxDetailLabel()
        vbox_left.addWidget(self.amount_label)
        self.ln_amount_label = TxDetailLabel()
        vbox_left.addWidget(self.ln_amount_label)

        fee_hbox = QHBoxLayout()
        self.fee_label = TxDetailLabel()
        fee_hbox.addWidget(self.fee_label)
        self.fee_warning_icon = QLabel()
        pixmap = QPixmap(icon_path("warning"))
        pixmap_size = round(2 * char_width_in_lineedit())
        pixmap = pixmap.scaled(pixmap_size, pixmap_size, Qt.KeepAspectRatio,
                               Qt.SmoothTransformation)
        self.fee_warning_icon.setPixmap(pixmap)
        self.fee_warning_icon.setToolTip(
            _("Warning") + ": " +
            _("The fee could not be verified. Signing non-segwit inputs is risky:\n"
              "if this transaction was maliciously modified before you sign,\n"
              "you might end up paying a higher mining fee than displayed."))
        self.fee_warning_icon.setVisible(False)
        fee_hbox.addWidget(self.fee_warning_icon)
        fee_hbox.addStretch(1)
        vbox_left.addLayout(fee_hbox)

        vbox_left.addStretch(1)
        hbox_stats.addLayout(vbox_left, 50)

        # vertical line separator
        line_separator = QFrame()
        line_separator.setFrameShape(QFrame.VLine)
        line_separator.setFrameShadow(QFrame.Sunken)
        line_separator.setLineWidth(1)
        hbox_stats.addWidget(line_separator)

        # right column
        vbox_right = QVBoxLayout()
        self.size_label = TxDetailLabel()
        vbox_right.addWidget(self.size_label)
        self.rbf_label = TxDetailLabel()
        vbox_right.addWidget(self.rbf_label)
        self.rbf_cb = QCheckBox(_('Replace by fee'))
        self.rbf_cb.setChecked(bool(self.config.get('use_rbf', True)))
        vbox_right.addWidget(self.rbf_cb)

        self.locktime_final_label = TxDetailLabel()
        vbox_right.addWidget(self.locktime_final_label)

        locktime_setter_hbox = QHBoxLayout()
        locktime_setter_hbox.setContentsMargins(0, 0, 0, 0)
        locktime_setter_hbox.setSpacing(0)
        locktime_setter_label = TxDetailLabel()
        locktime_setter_label.setText("LockTime: ")
        self.locktime_e = LockTimeEdit()
        locktime_setter_hbox.addWidget(locktime_setter_label)
        locktime_setter_hbox.addWidget(self.locktime_e)
        locktime_setter_hbox.addStretch(1)
        self.locktime_setter_widget = QWidget()
        self.locktime_setter_widget.setLayout(locktime_setter_hbox)
        vbox_right.addWidget(self.locktime_setter_widget)

        self.block_height_label = TxDetailLabel()
        vbox_right.addWidget(self.block_height_label)
        vbox_right.addStretch(1)
        hbox_stats.addLayout(vbox_right, 50)

        vbox.addLayout(hbox_stats)

        # below columns
        self.block_hash_label = TxDetailLabel(word_wrap=True)
        vbox.addWidget(self.block_hash_label)

        # set visibility after parenting can be determined by Qt
        self.rbf_label.setVisible(self.finalized)
        self.rbf_cb.setVisible(not self.finalized)
        self.locktime_final_label.setVisible(self.finalized)
        self.locktime_setter_widget.setVisible(not self.finalized)
Beispiel #53
0
class MainWindow(QMainWindow):

    senal_ingreso = pyqtSignal(Ingresa)
    senal_cerrar_sesion = pyqtSignal(Ingresa)
    trigger_pide = pyqtSignal()
    trigger_edit = pyqtSignal(Edit)
    trigger_bloqueo = pyqtSignal(Imagenes)
    trigger_desbloqueo = pyqtSignal(Imagenes)
    trigger_pide_descarga = pyqtSignal(Imagenes)
    trigger_comentarios = pyqtSignal(Actualiza_edit)
    trigger_pide_come = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.nombre = ''
        uic.loadUi("uis/mainwindow.ui", self)
        self.client = Client(self)
        self.orden = []
        self.imagenes = ['Knightmare.png', 'DragonBall.png',
                         'MickeyMouse.png', 'Mushroom.png']
        while len(self.orden) < 4:
            a = random.randint(0, 3)
            if a not in self.orden:
                self.orden.append(a)

        # aca vemos el orden original
        self.final = [self.imagenes[self.orden[0]], self.imagenes[
            self.orden[1]], self.imagenes[self.orden[2]], self.imagenes[
            self.orden[3]]]

        self.pos1 = self.orden[0]
        self.pos2 = self.orden[1]
        self.pos3 = self.orden[2]
        self.pos4 = self.orden[3]

        self.trigger_pide.connect(self.client.pide)
        self.trigger_edit.connect(self.client.edit)
        self.trigger_bloqueo.connect(self.client.bloqueo)
        self.trigger_desbloqueo.connect(self.client.desbloqueo)
        self.trigger_pide_descarga.connect(self.client.descarga)
        self.trigger_comentarios.connect(self.client.comenta)
        self.trigger_pide_come.connect(self.client.pidecom)
        self.trigger_pide.emit()
        self.imagen1 = QPixmap()
        self.imagen2 = QPixmap()
        self.imagen3 = QPixmap()
        self.imagen4 = QPixmap()
        self.veri1 = QPixmap()
        self.veri2 = QPixmap()
        self.veri3 = QPixmap()
        self.veri4 = QPixmap()

        self.ventana_ingreso = Ingreso()
        self.pop_up_existe = Pop_up_existe()
        self.pop_up_tipo = Pop_up_tipo()
        self.pop_up_maximo = Pop_up_maximo()
        self.pop_up_noexiste = Pop_up_noexiste()
        self.pop_up_conectado = Pop_up_conectado()
        self.espectador = Espectador()
        self.espectador.volver.clicked.connect(self.volveresp)
        self.ventana_edicion = Ventana_edicion()
        self.ventana_edicion.descarga.clicked.connect(self.descar)
        self.espectador.descarga.clicked.connect(self.descar)
        self.ventana_colores = Colores()
        self.ventana_edicion.volver.clicked.connect(self.volver_ingreso)
        self.senal_ingreso.connect(self.client.envio_cliente)
        self.senal_cerrar_sesion.connect(self.client.envio_cliente)
        self.ventana_edicion.comenta.clicked.connect(self.comenta)
        self.espectador.comenta.clicked.connect(self.comenta)
        self.cerrar.clicked.connect(self.cerrar_sesion)
        self.editar1.clicked.connect(self.edita1)
        self.editar2.clicked.connect(self.edita2)
        self.editar3.clicked.connect(self.edita3)
        self.editar4.clicked.connect(self.edita4)
        self.editando = 0
        self.viendo = 0
        self.entrar()

    def entrar(self):
        self.ventana_ingreso.ingresar.clicked.connect(self.ingresar)
        self.ventana_ingreso.registrarse.clicked.connect(self.registrarse)
        self.ventana_ingreso.show()

    def ingresar(self):
        nombre = self.ventana_ingreso.nombre.text()
        self.ventana_ingreso.nombre.clear()
        self.nombre = nombre
        senal = Ingresa(nombre, 'ingreso')
        self.senal_ingreso.emit(senal)

    def registrarse(self):
        nombre = self.ventana_ingreso.nombre.text()
        self.ventana_ingreso.nombre.clear()
        senal = Ingresa(nombre, 'registro')
        self.senal_ingreso.emit(senal)
        self.nombre = nombre

    def volveresp(self):
        self.ventana_edicion.comentarios.clear()
        self.espectador.comentarios.clear()
        self.viendo = 0
        self.espectador.close()
        self.show()

    def cerrar_ventana(self, event):
        v = event.ventana

        if v == 'ventana_ingreso':
            self.ventana_ingreso.close()
            self.show()

    def abrir_ventana(self, event):
        v = event.ventana

        if v == 'pop_up_tipo':
            self.pop_up_tipo.show()

        elif v == 'pop_up_noexiste':
            self.pop_up_noexiste.show()

        elif v == 'pop_up_maximo':
            self.pop_up_maximo.show()

        elif v == 'pop_up_existe':
            self.pop_up_existe.show()

        elif v == 'pop_up_conectado':
            self.pop_up_conectado.show()

    def cerrar_sesion(self):
        senal = Ingresa(self.nombre, 'cerrar_sesion')
        self.close()
        self.ventana_ingreso.show()
        self.senal_cerrar_sesion.emit(senal)

    def genera_imagenes(self, event):
        lista = event.images
        self.imagen1 = QPixmap()
        self.imagen2 = QPixmap()
        self.imagen3 = QPixmap()
        self.imagen4 = QPixmap()
        self.imagen1.loadFromData(lista[self.orden[0]])
        self.imagen2.loadFromData(lista[self.orden[1]])
        self.imagen3.loadFromData(lista[self.orden[2]])
        self.imagen4.loadFromData(lista[self.orden[3]])
        scaled = self.imagen1.scaled(self.foto1.size(), Qt.KeepAspectRatio)
        scaled2 = self.imagen2.scaled(self.foto2.size(), Qt.KeepAspectRatio)
        scaled3 = self.imagen3.scaled(self.foto3.size(), Qt.KeepAspectRatio)
        scaled4 = self.imagen4.scaled(self.foto4.size(), Qt.KeepAspectRatio)
        self.foto1.setPixmap(scaled)
        self.foto2.setPixmap(scaled2)
        self.foto3.setPixmap(scaled3)
        self.foto4.setPixmap(scaled4)

    def comenta(self):
        if self.editando != 0:
            text = self.ventana_edicion.escrito.text()
        else:
            text = self.espectador.escrito.text()
        self.ventana_edicion.escrito.clear()
        self.espectador.escrito.clear()
        e = [self.nombre, text]
        if self.editando == 1 or self.viendo == 1:
            self.trigger_comentarios.emit(Actualiza_edit(e, self.pos1))
        elif self.editando == 2 or self.viendo == 2:
            self.trigger_comentarios.emit(Actualiza_edit(e, self.pos2))
        elif self.editando == 3 or self.viendo == 3:
            self.trigger_comentarios.emit(Actualiza_edit(e, self.pos3))
        else:
            self.trigger_comentarios.emit(Actualiza_edit(e, self.pos4))

    def edita1(self):

        self.editando = 1
        self.pide_come()
        self.desconecta()
        self.trigger_bloqueo.emit(Imagenes(self.pos1))
        self.close()
        scaled = self.imagen1.scaled(self.ventana_edicion.imagen.size(),
                                     Qt.KeepAspectRatio)
        self.ventana_edicion.imagen.setPixmap(scaled)
        self.ventana_edicion.blurry.clicked.connect(self.blurry1)
        self.ventana_edicion.blade.clicked.connect(self.blade1)
        self.ventana_edicion.recortar.clicked.connect(self.recorta1)
        self.ventana_edicion.show()

    def blurry1(self):
        self.trigger_edit.emit(Edit(self.pos1, ['blurry']))

    def blade1(self):
        self.ventana_colores.blanco.clicked.connect(self.blanco1)
        self.ventana_colores.azul.clicked.connect(self.azul1)
        self.ventana_colores.amarillo.clicked.connect(self.amarillo1)
        self.ventana_colores.negro.clicked.connect(self.negro1)
        self.ventana_colores.rojo.clicked.connect(self.rojo1)
        self.ventana_colores.show()

    def recorta1(self):
        self.trigger_edit.emit(Edit(self.pos1, ['recorta']))

    def blanco1(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos1, ['blade', 'blanco']))

    def azul1(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos1, ['blade', 'azul']))

    def amarillo1(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos1, ['blade', 'amarillo']))

    def negro1(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos1, ['blade', 'negro']))

    def rojo1(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos1, ['blade', 'rojo']))

    def edita2(self):
        self.editando = 2
        self.pide_come()
        self.desconecta()
        self.trigger_bloqueo.emit(Imagenes(self.pos2))
        self.close()
        scaled = self.imagen2.scaled(self.ventana_edicion.imagen.size(),
                                     Qt.KeepAspectRatio)
        self.ventana_edicion.imagen.setPixmap(scaled)
        self.ventana_edicion.blurry.clicked.connect(self.blurry2)
        self.ventana_edicion.recortar.clicked.connect(self.recorta2)
        self.ventana_edicion.blade.clicked.connect(self.blade2)
        self.ventana_edicion.show()

    def blurry2(self):
        self.trigger_edit.emit(Edit(self.pos2, ['blurry']))

    def blade2(self):
        self.ventana_colores.blanco.clicked.connect(self.blanco2)
        self.ventana_colores.azul.clicked.connect(self.azul2)
        self.ventana_colores.amarillo.clicked.connect(self.amarillo2)
        self.ventana_colores.negro.clicked.connect(self.negro2)
        self.ventana_colores.rojo.clicked.connect(self.rojo2)
        self.ventana_colores.show()

    def recorta2(self):
        self.trigger_edit.emit(Edit(self.pos2, ['recorta']))

    def blanco2(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos2, ['blade', 'blanco']))

    def azul2(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos2, ['blade', 'azul']))

    def amarillo2(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos2, ['blade', 'amarillo']))

    def negro2(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos2, ['blade', 'negro']))

    def rojo2(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos2, ['blade', 'rojo']))

    def edita3(self):
        self.editando = 3
        self.pide_come()
        self.desconecta()
        self.trigger_bloqueo.emit(Imagenes(self.pos3))
        self.close()
        scaled = self.imagen3.scaled(self.ventana_edicion.imagen.size(),
                                     Qt.KeepAspectRatio)
        self.ventana_edicion.imagen.setPixmap(scaled)
        self.ventana_edicion.blurry.clicked.connect(self.blurry3)
        self.ventana_edicion.recortar.clicked.connect(self.recorta3)
        self.ventana_edicion.blade.clicked.connect(self.blade3)
        self.ventana_edicion.show()

    def blurry3(self):
        self.trigger_edit.emit(Edit(self.pos3, ['blurry']))

    def blade3(self):
        self.ventana_colores.blanco.clicked.connect(self.blanco3)
        self.ventana_colores.azul.clicked.connect(self.azul3)
        self.ventana_colores.amarillo.clicked.connect(self.amarillo3)
        self.ventana_colores.negro.clicked.connect(self.negro3)
        self.ventana_colores.rojo.clicked.connect(self.rojo3)
        self.ventana_colores.show()

    def recorta3(self):
        self.trigger_edit.emit(Edit(self.pos3, ['recorta']))

    def blanco3(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos3, ['blade', 'blanco']))

    def azul3(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos3, ['blade', 'azul']))

    def amarillo3(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos3, ['blade', 'amarillo']))

    def negro3(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos3, ['blade', 'negro']))

    def rojo3(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos3, ['blade', 'rojo']))

    def edita4(self):
        self.editando = 4
        self.pide_come()
        self.desconecta()
        self.trigger_bloqueo.emit(Imagenes(self.pos4))
        self.close()
        scaled = self.imagen4.scaled(self.ventana_edicion.imagen.size(),
                                     Qt.KeepAspectRatio)
        self.ventana_edicion.imagen.setPixmap(scaled)
        self.ventana_edicion.blurry.clicked.connect(self.blurry4)
        self.ventana_edicion.recortar.clicked.connect(self.recorta4)
        self.ventana_edicion.blade.clicked.connect(self.blade4)
        self.ventana_edicion.show()

    def blurry4(self):
        self.trigger_edit.emit(Edit(self.pos4, ['blurry']))

    def blade4(self):
        self.ventana_colores.blanco.clicked.connect(self.blanco4)
        self.ventana_colores.azul.clicked.connect(self.azul4)
        self.ventana_colores.amarillo.clicked.connect(self.amarillo4)
        self.ventana_colores.negro.clicked.connect(self.negro4)
        self.ventana_colores.rojo.clicked.connect(self.rojo4)
        self.ventana_colores.show()

    def recorta4(self):
        self.trigger_edit.emit(Edit(self.pos4, ['recorta']))

    def blanco4(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos4, ['blade', 'blanco']))

    def azul4(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos4, ['blade', 'azul']))

    def amarillo4(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos4, ['blade', 'amarillo']))

    def negro4(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos4, ['blade', 'negro']))

    def rojo4(self):
        self.ventana_colores.close()
        self.trigger_edit.emit(Edit(self.pos4, ['blade', 'rojo']))

    def actualiza(self, evento):
        text = QTextEdit()
        self.activos.setWidget(text)
        usuarios = evento.lista
        for nombre in usuarios:
            text.append(nombre)

    def volver_ingreso(self):
        self.ventana_edicion.comentarios.clear()
        self.espectador.comentarios.clear()
        self.ventana_edicion.editada.setPixmap(QPixmap())
        if self.editando == 1:
            self.trigger_desbloqueo.emit(Imagenes(self.orden[0]))
        elif self.editando == 2:
            self.trigger_desbloqueo.emit(Imagenes(self.orden[1]))
        elif self.editando == 3:
            self.trigger_desbloqueo.emit(Imagenes(self.orden[2]))
        elif self.editando == 4:
            self.trigger_desbloqueo.emit(Imagenes(self.orden[3]))
        self.editando = 0
        self.viendo = 0
        self.ventana_edicion.close()
        self.show()

    def ver1(self):
        self.viendo = 1
        self.pide_come()
        self.close()
        scaled = self.imagen1.scaled(self.espectador.imagen.size(),
                                     Qt.KeepAspectRatio)
        self.espectador.imagen.setPixmap(scaled)
        self.espectador.show()

    def ver2(self):
        self.viendo = 2
        self.pide_come()
        self.close()
        scaled = self.imagen2.scaled(self.espectador.imagen.size(),
                                     Qt.KeepAspectRatio)
        self.espectador.imagen.setPixmap(scaled)
        self.espectador.show()

    def ver3(self):
        self.viendo = 3
        self.pide_come()
        self.close()
        scaled = self.imagen3.scaled(self.espectador.imagen.size(),
                                     Qt.KeepAspectRatio)
        self.espectador.imagen.setPixmap(scaled)
        self.espectador.show()

    def ver4(self):
        self.viendo = 4
        self.pide_come()
        self.close()
        scaled = self.imagen4.scaled(self.espectador.imagen.size(),
                                     Qt.KeepAspectRatio)
        self.espectador.imagen.setPixmap(scaled)
        self.espectador.show()

    def act_imagenes(self, imagen):
        ima = imagen.ima
        foto = imagen.nro
        nro = self.orden.index(foto)
        if nro == 0:
            self.imagen1 = QPixmap()
            self.imagen1.loadFromData(ima)
            scaled = self.imagen1.scaled(self.ventana_edicion.editada.size(),
                                         Qt.KeepAspectRatio)
            self.ventana_edicion.editada.setPixmap(scaled)
        elif nro == 1:
            self.imagen2 = QPixmap()
            self.imagen2.loadFromData(ima)
            scaled = self.imagen2.scaled(self.ventana_edicion.editada.size(),
                                         Qt.KeepAspectRatio)
            self.ventana_edicion.editada.setPixmap(scaled)
        elif nro == 2:
            self.imagen3 = QPixmap()
            self.imagen3.loadFromData(ima)
            scaled = self.imagen3.scaled(self.ventana_edicion.editada.size(),
                                         Qt.KeepAspectRatio)
            self.ventana_edicion.editada.setPixmap(scaled)
        else:
            self.imagen4 = QPixmap()
            self.imagen4.loadFromData(ima)
            scaled = self.imagen4.scaled(self.ventana_edicion.editada.size(),
                                         Qt.KeepAspectRatio)
            self.ventana_edicion.editada.setPixmap(scaled)

    def desconecta(self):
        try:
            self.ventana_edicion.blurry.clicked.disconnect()
        except Exception:
            pass
        try:
            self.ventana_edicion.blade.clicked.disconnect()
        except Exception:
            pass
        try:
            self.ventana_colores.blanco.clicked.disconnect()
        except Exception:
            pass
        try:
            self.ventana_colores.rojo.clicked.disconnect()
        except Exception:
            pass
        try:
            self.ventana_colores.azul.clicked.disconnect()
        except Exception:
            pass
        try:
            self.ventana_colores.amarillo.clicked.disconnect()
        except Exception:
            pass
        try:
            self.ventana_colores.negro.clicked.disconnect()
        except Exception:
            pass
        try:
            self.ventana_edicion.recortar.clicked.disconnect()
        except Exception:
            pass

    def bloquea(self, evento):
        dict = evento.images
        self.editar1.close()
        self.editar2.close()
        self.editar3.close()
        self.editar4.close()

        if dict[self.orden[0]] == False:
            self.editar1 = QPushButton('Editar', self)
            self.editar1.resize(self.editar1.sizeHint())
            self.editar1.move(50, 230)
            self.editar1.clicked.connect(self.edita1)
        else:
            self.editar1 = QPushButton('Ver', self)
            self.editar1.resize(self.editar1.sizeHint())
            self.editar1.move(50, 230)
            self.editar1.clicked.connect(self.ver1)

        if dict[self.orden[1]] == False:
            self.editar2 = QPushButton('Editar', self)
            self.editar2.resize(self.editar2.sizeHint())
            self.editar2.move(330, 230)
            self.editar2.clicked.connect(self.edita2)
        else:
            self.editar2 = QPushButton('Ver', self)
            self.editar2.resize(self.editar2.sizeHint())
            self.editar2.move(330, 230)
            self.editar2.clicked.connect(self.ver2)

        if dict[self.orden[2]] == False:
            self.editar3 = QPushButton('Editar', self)
            self.editar3.resize(self.editar3.sizeHint())
            self.editar3.move(50, 520)
            self.editar3.clicked.connect(self.edita3)
        else:
            self.editar3 = QPushButton('Ver', self)
            self.editar3.resize(self.editar3.sizeHint())
            self.editar3.move(50, 520)
            self.editar3.clicked.connect(self.ver3)

        if dict[self.orden[3]] == False:
            self.editar4 = QPushButton('Editar', self)
            self.editar4.resize(self.editar4.sizeHint())
            self.editar4.move(320, 520)
            self.editar4.clicked.connect(self.edita4)
        else:
            self.editar4 = QPushButton('Ver', self)
            self.editar4.resize(self.editar4.sizeHint())
            self.editar4.move(320, 520)
            self.editar4.clicked.connect(self.ver4)

        self.editar1.show()
        self.editar2.show()
        self.editar3.show()
        self.editar4.show()




    # revisar los boqueos....

    def descar(self):
        if self.editando == 1 or self.viendo == 1:
            self.trigger_pide_descarga.emit(Imagenes(self.orden[0]))
        elif self.editando == 2 or self.viendo == 2:
            self.trigger_pide_descarga.emit(Imagenes(self.orden[1]))
        elif self.editando == 3 or self.viendo == 3:
            self.trigger_pide_descarga.emit(Imagenes(self.orden[2]))
        elif self.editando == 4 or self.viendo == 4:
            self.trigger_pide_descarga.emit(Imagenes(self.orden[3]))

    def descarga(self, event):
        ima = event.images[0]
        n = event.images[1]
        path = 'downloads/'
        if self.final[self.editando - 1] == self.imagenes[n]:
            print(self.imagenes[n])
            with open(path + self.imagenes[n], 'wb') as file:
                file.write(ima)

    def comenta1(self, event):
        self.ventana_edicion.comentarios.clear()
        self.espectador.comentarios.clear()
        dic = event.lista
        if self.viendo == 1 or self.editando == 1:
            for come in dic[self.orden[0]]:
                self.ventana_edicion.comentarios.addItem(come)
                self.espectador.comentarios.addItem(come)
        elif self.viendo == 2 or self.editando == 2:
            for come in dic[self.orden[1]]:
                self.ventana_edicion.comentarios.addItem(come)
                self.espectador.comentarios.addItem(come)
        elif self.viendo == 3 or self.editando == 3:
            for come in dic[self.orden[2]]:
                self.ventana_edicion.comentarios.addItem(come)
                self.espectador.comentarios.addItem(come)
        elif self.viendo == 4 or self.editando == 4:
            for come in dic[self.orden[3]]:
                self.ventana_edicion.comentarios.addItem(come)
                self.espectador.comentarios.addItem(come)

    def pide_come(self):
        self.trigger_pide_come.emit()
Beispiel #54
0
    def abrir_archivo(self):
        nombre = self.textbox.text()
        self.registro = leer_archivo(nombre)
        print(self.registro)
        # Hideamos lo anterior
        self.label_carga.hide()
        self.textbox.hide()
        self.boton_carga.hide()

        ## Iniciamos el programa sin escucha

        self.diapos_totales = len([
            f for f in listdir("1/") if isfile(join("1/", f)) and ".jpg" in f
        ])

        self.label_1.hide()
        self.curso1.hide()
        self.boton1.hide()
        # Configuramos los widgets de la interfaz
        self.diapositivas = QLabel("", self)
        # self.diapositivas.move()
        pixmap = QPixmap("1/1.jpg")
        pixmap = pixmap.scaled(650, 450)
        self.diapositivas.setPixmap(pixmap)
        self.diapositivas.show()
        self.diapositivas.move(100, 120)

        self.label = QLabel('Esperando inicio', self)
        self.label.setFont(QFont("Sans Serif", 25))
        self.boton = QPushButton('Iniciar escucha', self)
        self.boton.clicked.connect(self.start_threads)
        self.tabla = QListWidget(self)
        self.boton_2 = QPushButton("Guardar", self)
        self.boton_2.move(200, 700)
        self.boton_2.clicked.connect(self.guardar_archivo)
        self.boton_3 = QPushButton("Siguiente", self)
        self.boton_3.move(400, 600)
        self.boton_4 = QPushButton("Anterior", self)
        self.boton_4.move(200, 600)

        self.tabla.show()
        self.boton_3.show()
        self.boton_4.show()

        self.boton_3.clicked.connect(self.siguiente)
        self.boton_4.clicked.connect(self.anterior)

        self.tabla.resize(400, 600)
        self.tabla.move(800, 100)
        self.label.resize(1000, 30)
        self.label.move(100, 50)
        self.boton.move(50, 700)
        self.resize(1500, 1000)

        self.diapo = 1
        for i in self.registro[int(self.diapo - 1)]:
            self.tabla.addItem(i)

        # Conectamos la señal del thread al método que maneja
        self.threads_response.connect(self.update_labels)

        # Configuramos las propiedades de la ventana.
        self.setWindowTitle('Interaula')
        self.show()
Beispiel #55
0
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setFixedSize(480, 450)
        labelA = QLabel(self)
        labelA.setText('  Exercicio  ')
        labelA.move(400, 140)

        labelAB = QLabel(self)
        labelAB.setText('  Nro')
        labelAB.move(400, 180)
        #labelAB.setStyleSheet("QLabel { background-color : blue; color : red; }");

        labelB = QLabel(self)
        labelB.setText(' de 40')
        labelB.move(425, 180)
        #labelB.setStyleSheet("QLabel { background-color : red; color : blue; }");

        labelC = QLabel(self)
        labelC.setText('    Tempo    ')
        labelC.move(400, 240)
        #labelC.setStyleSheet("QLabel { background-color : red; color : blue; }");
        start = time.time()
        end = time.time()
        print(end - start)

        labelCD = QLabel(self)
        labelCD.setText(str(end - start))
        labelCD.move(400, 280)

        labelD = QLabel(self)
        labelD.setText('   segundos  ')
        labelD.move(425, 280)
        #labelD.setStyleSheet("QLabel { background-color : red; color : blue; }");
        #printit(self)
        #printit2(self)
        #threading.Timer(15.0, printit).start()
        #time.sleep(15)
        self.lb = QLabel(self)
        pixmap = QPixmap("hdd.jpg")
        self.lb.move(80, 90)
        height_of_label = 250
        self.lb.resize(250, height_of_label)
        self.lb.setPixmap(
            pixmap.scaled(self.lb.size(), QtCore.Qt.IgnoreAspectRatio))
        labelAB = QLabel(self)
        labelAB.setText('  1')
        labelAB.move(400, 180)
        time.sleep(15)
        #self.show()
        print('foto 1')
        #threading.Timer(15.0, printit).start()
        self.lb = QLabel(self)
        pixmap = QPixmap("gato.gif")
        self.lb.move(80, 90)
        height_of_label = 250
        self.lb.resize(250, height_of_label)
        self.lb.setPixmap(
            pixmap.scaled(self.lb.size(), QtCore.Qt.IgnoreAspectRatio))
        labelAB = QLabel(self)
        labelAB.setText('  2')
        labelAB.move(400, 180)
        time.sleep(15)
        #self.show()
        print('foto 2')
        self.lb = QLabel(self)
        pixmap = QPixmap("gatomusical.gif")
        self.lb.move(80, 90)
        height_of_label = 250
        self.lb.resize(250, height_of_label)
        self.lb.setPixmap(
            pixmap.scaled(self.lb.size(), QtCore.Qt.IgnoreAspectRatio))
        labelAB = QLabel(self)
        labelAB.setText('  3')
        labelAB.move(400, 180)
        print('foto 3')

        # self.show()

        button = QPushButton('Ok', self)
        button.setToolTip('This is an example button')
        button.move(120, 350)
        button.clicked.connect(self.on_click)

        button = QPushButton('Close', self)
        button.setToolTip('This is an example button')
        button.move(250, 350)
        button.clicked.connect(self.on_click)
        self.show()
class ManipulacaoImagens(QWidget):
    def __init__(self, imagemOriginal, controleVisibilidadeItens, controleChecagemFiltros):
        super(ManipulacaoImagens, self).__init__()
        self.imagemOriginal = imagemOriginal
        self.imagemResultado = 'imagensResultado/imagemTransformada'
        self.extensaoImagemResultado = '.ppm'
        self.extensaoImagemOriginal = ''
        self.endImagemOriginal = ''
        self.endImagemResultado = ''
        self.controleVisibilidadeItens = controleVisibilidadeItens
        self.controleChecagemFiltros = controleChecagemFiltros

    '''Abre imagem selecionada pelo usuário e mantêm oculta diretório que mantem cópias de imagens anteriores que foram 
    transformadas, também solicita habilitar visibilidade dos menus e ações, remoção de cópias de imagens anteriores 
    transformadas, zera porcentagem da barra de progresso, defini pixmap da Imagem a ser exibida'''

    def abrirImagem(self):
        ocultarDiretorioImgResultado()

        arquivoImagem, _ = QFileDialog.getOpenFileName(self, caption="Abrir Imagem",
                                                       directory=QtCore.QDir.currentPath(),
                                                       filter='Imagens(*.ppm; *.pgm; *.pbm)',
                                                       initialFilter='Imagens(*.ppm; *.pgm; *.pbm)')

        if arquivoImagem:
            self.excluirCopiaImgTransformada()
            self.controleChecagemFiltros.removerChecagemFiltrosUsados()
            self.endImagemOriginal = arquivoImagem
            self.pixmapImagem = QPixmap(self.endImagemOriginal)
            self.extensaoImagemOriginal = os.path.splitext(os.path.basename(arquivoImagem))[1]
            self.extrairInfoImagem()
            self.exibirImagem()
            self.controleVisibilidadeItens.alterarVisibilidadeItensMenuTransformacoes(self.extensaoImagemOriginal)

    '''Exibe informações sobre aplicativo e imagem quando selecionado menu Sobre'''

    def extrairInfoImagem(self):
        try:
            self.parts = self.endImagemOriginal.rpartition('/')
            self.nomeimagem = self.parts[2]
            self.leituraimagem = open(self.endImagemOriginal, "r+")
            self.tipoimagem = self.leituraimagem.readline()
            self.comentarioimagem = self.leituraimagem.readline()
            self.dimensoesimagem = self.leituraimagem.readline()
            self.dimensoesimagem = self.dimensoesimagem.split()
            self.larguraimagem = self.dimensoesimagem[0]
            self.alturaimagem = self.dimensoesimagem[1]
        except:
            pass

    def exibirImagem(self):
        if self.pixmapImagem.width() > int(GetSystemMetrics(0) / 2) or \
                self.pixmapImagem.height() > int(GetSystemMetrics(1) / 2):
            self.pixmapImagem = self.pixmapImagem.scaled(int(GetSystemMetrics(0) / 2), int(GetSystemMetrics(1) / 2),
                                                         QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)

        self.imagemOriginal.setPixmap(self.pixmapImagem)
        self.imagemOriginal.setAlignment(QtCore.Qt.AlignCenter)

    '''Salva Imagem com nome de arquivo e diretório escolhidos pelo usuário. Procura pela imagem transformada, caso
    não exista, é salvo a imagem original com o nome que o usuário escolher'''

    def salvarImagemComo(self):
        try:
            if self.endImagemOriginal != '':
                imagemSalvaComo, tipos = QFileDialog.getSaveFileName(self, caption='Salvar como',
                                                                     directory=QtCore.QDir.currentPath(),
                                                                     filter='Imagens(*.ppm; *.pgm; *.pbm)',
                                                                     initialFilter='Imagens(*.ppm; *.pgm; *.pbm)')
                if imagemSalvaComo:
                    self.parts = imagemSalvaComo.rpartition('/')
                    self.enderecoSalvo = self.parts[0]
                    if self.endImagemResultado != '':
                        shutil.move(self.endImagemResultado, self.enderecoSalvo + '/' +
                                   os.path.splitext(os.path.basename(imagemSalvaComo))[0] +
                                   self.extensaoImagemResultado)
                    else:
                        shutil.copyfile(self.endImagemOriginal, self.enderecoSalvo + '/' +
                                        os.path.splitext(os.path.basename(imagemSalvaComo))[0] +
                                        self.extensaoImagemOriginal)
        except:
            pass

    def procurarImagemTransformadaNaoSalva(self):
        return os.path.exists(self.imagemResultado + self.extensaoImagemResultado)


    def excluirCopiaImgTransformada(self):
        try:
            if os.path.exists(self.imagemResultado + "Copia" + '.ppm'):
                os.remove(self.imagemResultado + "Copia" + '.ppm')

            if os.path.exists(self.imagemResultado + "Copia" + '.pgm'):
                os.remove(self.imagemResultado + "Copia" + '.pgm')

            if os.path.exists(self.imagemResultado + "Copia" + '.pbm'):
                os.remove(self.imagemResultado + "Copia" + '.pbm')

        except:
            pass

    def excluirImagemTransformadaNaoSalva(self):
        try:
            if os.path.exists(self.imagemResultado + '.ppm'):
                os.remove(self.imagemResultado + '.ppm')

            if os.path.exists(self.imagemResultado + '.pgm'):
                os.remove(self.imagemResultado + '.pgm')

            if os.path.exists(self.imagemResultado + '.pbm'):
                os.remove(self.imagemResultado + '.pbm')
        except:
            pass
Beispiel #57
0
class BigTask(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(300, 50, 1600, 950)

        self.toponym_text = QLineEdit(self)
        self.toponym_text.resize(500, 30)
        self.toponym_text.move(180, 910)
        self.toponym_text.setDisabled(True)

        self.btn1 = QPushButton('Начать набор текста', self)
        self.btn1.resize(150, 40)
        self.btn1.move(15, 905)
        self.btn1.clicked.connect(self.start_text)

        self.btn2 = QPushButton('Искать!', self)
        self.btn2.resize(150, 40)
        self.btn2.move(710, 905)
        self.btn2.clicked.connect(self.find_toponym)
        self.btn2.setDisabled(True)

        self.btn3 = QPushButton('Сброс поискового результата', self)
        self.btn3.resize(200, 40)
        self.btn3.move(1200, 905)
        self.btn3.clicked.connect(self.reset_result)

        self.label = QLabel(self)
        self.label.setText("")
        self.label.resize(110, 30)
        self.label.move(980, 910)

        self.label2 = QLabel(self)
        self.label2.setText("")
        self.label2.resize(110, 30)
        self.label2.move(1250, 100)

        self.statham = QLabel(self)
        self.statham.setText("")
        self.statham.resize(1200, 35)
        self.statham.move(50, 10)

        self.sorry = QLabel(self)
        self.sorry.setText("")
        self.sorry.resize(300, 320)
        self.sorry.move(1250, 300)
        pixmap = QPixmap('shrek.jpg')
        self.sorry.setPixmap(pixmap)
        self.sorry.hide()

        self.sorry_text = QLabel(self)
        self.sorry_text.setText("")
        self.sorry_text.resize(300, 30)
        self.sorry_text.move(1250, 250)

        self.address = QLabel(self)
        self.address.setText("")
        self.address.resize(300, 40)
        self.address.move(1250, 50)

        self.postcode = QCheckBox('Почтовый индекс', self)
        self.postcode.move(1250, 200)
        self.postcode.clicked.connect(self.find_toponym)

        # Перемещать центр карты на W, S, D, A вверх, вниз, вправо и влево соответственно
        self.start_longitude = 43.820637
        self.start_lattitude = 56.364506
        self.max_longitube = 180
        self.min_longitube = -180
        self.max_lattitude = 90
        self.min_lattitude = -90
        self.right_border = 43.824742
        self.up_border = 56.366784
        self.left_border = 43.816532
        self.down_border = 56.362227
        self.point = False

        # Масштаб меняется на PgUp/PgDown
        self.delta = 0.005
        self.dop_delta = ["0.005", "0.005"]

        # Слой меняется на кнопку L
        self.layer = "map"

        self.image = QLabel(self)
        self.image.move(0, 0)
        self.image.resize(1200, 900)
        self.make_image()

    def start_text(self):
        self.toponym_text.setDisabled(False)
        self.btn2.setDisabled(False)

    def mousePressEvent(self, QMouseEvent):
        self.toponym_text.setDisabled(True)
        self.btn2.setDisabled(True)

    def make_image(self):
        global map_file
        map_params = {
            "ll":
            ",".join([str(self.start_longitude),
                      str(self.start_lattitude)]),
            "spn": ','.join(self.dop_delta),
            "l": self.layer
        }
        if self.point:
            map_params[
                "pt"] = f"{self.point_longitude},{self.point_lattitude},pm2rdl1"
        map_api_server = "http://static-maps.yandex.ru/1.x/"
        response = requests.get(map_api_server, params=map_params)
        if self.layer == "map":
            map_file = "map.png"
        else:
            map_file = "map.jpg"
        with open(map_file, "wb") as file:
            file.write(response.content)
        self.pixmap = QPixmap(map_file)
        self.image.setPixmap(self.pixmap.scaled(1200, 900))

    def find_toponym(self):
        self.sorry_text.setText('')
        self.sorry.hide()
        toponym_to_find = self.toponym_text.text()
        if self.sender().text() == 'Почтовый индекс' and not toponym_to_find:
            return
        if not toponym_to_find:
            self.statham.setFont(QFont("Times", 20, QFont.Bold))
            self.statham.setText(
                'Я ОТКАЗЫВАЮСЬ работать, пока вы не введете адрес')
            self.pixmap = QPixmap('стэтхэм.jpg')
            self.image.setPixmap(self.pixmap.scaled(1100, 790))
            return
        geocoder_api_server = "http://geocode-maps.yandex.ru/1.x/"
        geocoder_params = {
            "apikey": "40d1649f-0493-4b70-98ba-98533de7710b",
            "geocode": toponym_to_find,
            "format": "json"
        }
        response = requests.get(geocoder_api_server, params=geocoder_params)
        json_response = response.json()
        found = json_response['response']['GeoObjectCollection'][
            'metaDataProperty']['GeocoderResponseMetaData']['found']
        if not response or found == '0':
            self.label.setText("Объект не найден")
        else:
            self.dop_delta = select_parameters(json_response)
            dop = json_response['response']["GeoObjectCollection"][
                "featureMember"][0]["GeoObject"]
            full_address = dop["metaDataProperty"]["GeocoderMetaData"][
                "text"].split()
            if self.postcode.isChecked():
                try:
                    full_address.append(
                        str(dop['metaDataProperty']['GeocoderMetaData']
                            ['AddressDetails']['Country']['AdministrativeArea']
                            ['SubAdministrativeArea']['Locality']
                            ['Thoroughfare']['Premise']['PostalCode']
                            ['PostalCodeNumber']))
                except:
                    self.sorry_text.setText(
                        'К сожалению, почтовый индекс не найден')
                    self.sorry.show()
            out = ''
            count = 0
            for part in full_address:
                if count + len(part) <= 47:
                    out += part + ' '
                    count += len(part)
                else:
                    out += '\n' + part + ' '
                    count = 0
            self.label2.setText("")
            self.address.setText(out)

            self.label.setText("")
            toponym = json_response["response"]["GeoObjectCollection"][
                "featureMember"][0]["GeoObject"]
            toponym_coordinates = toponym["Point"]["pos"]
            toponym_corners = toponym["boundedBy"]["Envelope"]
            self.start_longitude, self.start_lattitude = [
                float(i) for i in toponym_coordinates.split(" ")
            ]
            self.right_border, self.up_border = [
                float(i) for i in toponym_corners["upperCorner"].split(" ")
            ]
            self.left_border, self.down_border = [
                float(i) for i in toponym_corners["lowerCorner"].split(" ")
            ]
            self.point = True
            self.point_longitude, self.point_lattitude = self.start_longitude, self.start_lattitude
            if not self.sender().text() == 'Почтовый индекс':
                self.make_image()

    def reset_result(self):
        self.point = False
        self.make_image()
        self.toponym_text.clear()
        self.address.setText('')
        self.sorry_text.setText('')
        self.sorry.hide()

    def mousePressEvent(self, event):
        if 0 <= event.x() <= 1200 and 0 <= event.y() <= 900 and event.button(
        ) == Qt.LeftButton:
            y_in_px = float(self.dop_delta[1]) / 900
            x_in_px = float(self.dop_delta[0]) / 1200
            lattitude = self.start_lattitude + float(
                self.dop_delta[1]) / 2 - y_in_px * event.y()
            longitude = self.start_longitude - float(
                self.dop_delta[0]) / 2 + x_in_px * event.x()

            geocoder_api_server = "http://geocode-maps.yandex.ru/1.x/"
            geocoder_params = {
                "apikey": "40d1649f-0493-4b70-98ba-98533de7710b",
                "geocode": ",".join([str(longitude),
                                     str(lattitude)]),
                "format": "json"
            }
            response = requests.get(geocoder_api_server,
                                    params=geocoder_params)
            json_response = response.json()
            dop = json_response['response']["GeoObjectCollection"][
                "featureMember"][0]["GeoObject"]
            full_address = dop["metaDataProperty"]["GeocoderMetaData"]["text"]
            self.label2.setText("")
            self.make_image_address(full_address)

        elif 0 <= event.x() <= 1200 and 0 <= event.y() <= 900 and event.button(
        ) == Qt.RightButton:
            y_in_px = float(self.dop_delta[1]) / 900
            x_in_px = float(self.dop_delta[0]) / 1200
            lattitude = self.start_lattitude + float(
                self.dop_delta[1]) / 2 - y_in_px * event.y()
            longitude = self.start_longitude - float(
                self.dop_delta[0]) / 2 + x_in_px * event.x()

            search_api_server = "https://search-maps.yandex.ru/v1/"
            api_key = "dda3ddba-c9ea-4ead-9010-f43fbc15c6e3"

            start_pos = ",".join([str(longitude), str(lattitude)])

            search_params = {
                "apikey": api_key,
                "text": "магазин,аптека",
                "lang": "ru_RU",
                "ll": start_pos,
                "type": "biz"
            }

            response = requests.get(search_api_server, params=search_params)
            json_response = response.json()

            organization = json_response["features"][0]

            org_name = organization["properties"]["CompanyMetaData"]["name"]
            print(org_name)

            org_address = organization["properties"]["CompanyMetaData"][
                "address"]

            point = organization["geometry"]["coordinates"]

            if lonlat_distance(tuple(point),
                               (float(longitude), float(lattitude))) > 50:
                return
            self.label2.setText(org_name)
            self.make_image_address(org_address)

    def make_image_address(self, toponym_to_find):
        geocoder_api_server = "http://geocode-maps.yandex.ru/1.x/"
        geocoder_params = {
            "apikey": "40d1649f-0493-4b70-98ba-98533de7710b",
            "geocode": toponym_to_find,
            "format": "json"
        }
        response = requests.get(geocoder_api_server, params=geocoder_params)
        json_response = response.json()
        found = json_response['response']['GeoObjectCollection'][
            'metaDataProperty']['GeocoderResponseMetaData']['found']
        if not response or found == '0':
            self.label.setText("Объект не найден")
        else:
            self.dop_delta = select_parameters(json_response)
            dop = json_response['response']["GeoObjectCollection"][
                "featureMember"][0]["GeoObject"]
            full_address = dop["metaDataProperty"]["GeocoderMetaData"][
                "text"].split()
            if self.postcode.isChecked():
                try:
                    full_address.append(
                        str(dop['metaDataProperty']['GeocoderMetaData']
                            ['AddressDetails']['Country']['AdministrativeArea']
                            ['SubAdministrativeArea']['Locality']
                            ['Thoroughfare']['Premise']['PostalCode']
                            ['PostalCodeNumber']))
                except:
                    self.sorry_text.setText(
                        'К сожалению, почтовый индекс не найден')
                    self.sorry.show()
            out = ''
            count = 0
            for part in full_address:
                if count + len(part) <= 47:
                    out += part + ' '
                    count += len(part)
                else:
                    out += '\n' + part + ' '
                    count = 0
            self.address.setText(out)

        self.label.setText("")
        toponym = json_response["response"]["GeoObjectCollection"][
            "featureMember"][0]["GeoObject"]
        toponym_coordinates = toponym["Point"]["pos"]
        toponym_corners = toponym["boundedBy"]["Envelope"]
        self.start_longitude, self.start_lattitude = [
            float(i) for i in toponym_coordinates.split(" ")
        ]
        self.right_border, self.up_border = [
            float(i) for i in toponym_corners["upperCorner"].split(" ")
        ]
        self.left_border, self.down_border = [
            float(i) for i in toponym_corners["lowerCorner"].split(" ")
        ]
        self.point = True
        self.point_longitude, self.point_lattitude = self.start_longitude, self.start_lattitude
        self.make_image()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_S or e.key() == 1067:
            self.start_lattitude -= float(self.dop_delta[0])
            if self.start_lattitude > self.max_lattitude - float(
                    self.dop_delta[0]) / 2:
                self.start_lattitude = self.max_lattitude - float(
                    self.dop_delta[0]) / 2
        elif e.key() == Qt.Key_W or e.key() == 1062:
            self.start_lattitude += float(self.dop_delta[0])
            if self.start_lattitude < self.min_lattitude + float(
                    self.dop_delta[0]) / 2:
                self.start_lattitude = self.min_lattitude + float(
                    self.dop_delta[0]) / 2
        elif e.key() == Qt.Key_D or e.key() == 1042:
            self.start_longitude += float(self.dop_delta[1]) * 2
            if self.start_longitude > self.max_longitube - float(
                    self.dop_delta[1]):
                self.start_longitude = self.max_longitube - float(
                    self.dop_delta[1])
        elif e.key() == Qt.Key_A or e.key() == 1060:
            self.start_longitude -= float(self.dop_delta[1]) * 2
            if self.start_longitude < self.min_longitube + float(
                    self.dop_delta[1]):
                self.start_longitude = self.min_longitube + float(
                    self.dop_delta[1])
        elif e.key() == Qt.Key_PageUp:
            self.delta = min(90, self.delta * 2)
            self.dop_delta = (str(min(90,
                                      float(self.dop_delta[0]) * 2)),
                              str(min(90,
                                      float(self.dop_delta[1]) * 2)))
        elif e.key() == Qt.Key_PageDown:
            self.delta = max(0.000001, self.delta / 2)
            self.dop_delta = (str(max(0.000001,
                                      float(self.dop_delta[0]) / 2)),
                              str(max(0.000001,
                                      float(self.dop_delta[1]) / 2)))
        elif e.key() == Qt.Key_L or e.key() == 1044:
            layers = ["map", "sat", "sat,skl"]
            self.layer = layers[(layers.index(self.layer) + 1) % 3]
        self.make_image()
Beispiel #58
0
    def refresh(self):
        """Called to update the widget when the network state has changed."""
        self._plugin.logger.trace("Refreshing the status bar widget")

        # Get the corresponding color, text and icon
        if self._plugin.network.connected:
            color, text, icon = "green", "Connected", "connected.png"
        elif self._plugin.network.client:
            color, text, icon = "orange", "Connecting", "connecting.png"
        else:
            color, text, icon = "red", "Disconnected", "disconnected.png"

        # Update the text of the server widgets
        server = self._plugin.network.server
        if server is None:
            server = "&lt;no server&gt;"
        else:
            server = "%s:%d" % (server["host"], server["port"])
        text_format = '%s | %s -- <span style="color: %s;">%s</span>'
        self._servers_text_widget.setText(
            text_format % (self._plugin.description(), server, color, text))
        self._servers_text_widget.adjustSize()

        # Update the icon of the server widgets
        pixmap = QPixmap(self._plugin.plugin_resource(icon))
        pixmap_height = self._servers_text_widget.sizeHint().height()
        self._servers_icon_widget.setPixmap(
            pixmap.scaled(
                pixmap_height,
                pixmap_height,
                Qt.KeepAspectRatio,
                Qt.SmoothTransformation,
            ))

        # Get all active invites
        invites = self._plugin.interface.invites
        # Find the most recent one
        most_recent = 0
        if invites:
            most_recent = max(invite.time for invite in invites)

        # Get the corresponding icon
        if most_recent > 0 and time.time() - most_recent < 60.0:
            icon = "hot.png"
        elif most_recent > 0 and time.time() - most_recent < 300.0:
            icon = "warm.png"
        elif most_recent > 0:
            icon = "cold.png"
        else:
            icon = "empty.png"

        # Update the text of the invites widgets
        self._invites_text_widget.setText(" | %d " % len(invites))
        self._invites_text_widget.adjustSize()

        # Update the icon of the invites widgets
        pixmap = QPixmap(self._plugin.plugin_resource(icon))
        pixmap_height = self._servers_text_widget.sizeHint().height()
        self._invites_icon_widget.setPixmap(
            pixmap.scaled(
                pixmap_height,
                pixmap_height,
                Qt.KeepAspectRatio,
                Qt.SmoothTransformation,
            ))

        # Update the text of the users widget
        users = len(self._plugin.core.get_users())
        self._users_text_widget.setText(" | %d" % users)
        self._users_text_widget.adjustSize()

        # Update the icon of the users widget
        template = self._plugin.plugin_resource("user.png")
        color = self._plugin.config["user"]["color"]
        pixmap = self.make_icon(template, color)
        pixmap_height = self._servers_text_widget.sizeHint().height()
        self._users_icon_widget.setPixmap(
            pixmap.scaled(
                pixmap_height,
                pixmap_height,
                Qt.KeepAspectRatio,
                Qt.SmoothTransformation,
            ))

        # Update the size of the widget
        self.updateGeometry()
Beispiel #59
0
    def initUI(self):
        """
        初始化UI
        :return:
        """
        self.setObjectName("loginWindow")
        self.setStyleSheet('#loginWindow{background-color:white}')
        self.setFixedSize(650, 400)
        self.setWindowTitle("登录")
        self.setWindowIcon(QIcon('static/logo_title.png'))

        self.text = "CSSRC消息盒子用户登录"

        # 添加顶部logo图片
        pixmap = QPixmap("static/logo_header.png")
        scaredPixmap = pixmap.scaled(650, 140)
        label = QLabel(self)
        label.setPixmap(scaredPixmap)

        # 绘制顶部文字
        lbl_logo = QLabel(self)
        lbl_logo.setText(self.text)
        lbl_logo.setStyleSheet(
            "QWidget{color:white;font-weight:600;background: transparent;font-size:30px;}"
        )
        lbl_logo.setFont(QFont("Microsoft YaHei"))
        lbl_logo.move(150, 50)
        lbl_logo.setAlignment(Qt.AlignCenter)
        lbl_logo.raise_()

        # 登录表单内容部分
        login_widget = QWidget(self)
        login_widget.move(0, 140)
        login_widget.setGeometry(0, 140, 650, 260)

        hbox = QHBoxLayout()
        # 添加左侧logo
        logolb = QLabel(self)
        logopix = QPixmap("static/logo.png")
        logopix_scared = logopix.scaled(100, 100)
        logolb.setPixmap(logopix_scared)
        logolb.setAlignment(Qt.AlignCenter)
        hbox.addWidget(logolb, 1)
        # 添加右侧表单
        fmlayout = QFormLayout()
        lbl_workerid = QLabel("用户名")
        lbl_workerid.setFont(QFont("Microsoft YaHei"))
        self.led_workerid = QLineEdit()
        self.led_workerid.setFixedWidth(270)
        self.led_workerid.setFixedHeight(38)

        lbl_pwd = QLabel("密码")
        lbl_pwd.setFont(QFont("Microsoft YaHei"))
        self.led_pwd = QLineEdit()
        self.led_pwd.setEchoMode(QLineEdit.Password)
        self.led_pwd.setFixedWidth(270)
        self.led_pwd.setFixedHeight(38)

        btn_login = QPushButton("登录")
        btn_login.setFixedWidth(270)
        btn_login.setFixedHeight(40)
        btn_login.setFont(QFont("Microsoft YaHei"))
        btn_login.setObjectName("login_btn")
        btn_login.setStyleSheet(
            "#login_btn{background-color:#2c7adf;color:#fff;border:none;border-radius:4px;}"
        )
        btn_login.clicked.connect(self.to_mainclient)

        fmlayout.addRow(lbl_workerid, self.led_workerid)
        fmlayout.addRow(lbl_pwd, self.led_pwd)
        fmlayout.addWidget(btn_login)
        hbox.setAlignment(Qt.AlignCenter)
        # 调整间距
        fmlayout.setHorizontalSpacing(20)
        fmlayout.setVerticalSpacing(12)

        hbox.addLayout(fmlayout, 2)

        login_widget.setLayout(hbox)

        self.center()
        self.show()
 def showImages(self, filename):
     self.labelImage.move(0, 100)
     self.labelImage.resize(640, 480)
     pixmap = QPixmap(filename)
     pixmapScaled = pixmap.scaled(640, 480, Qt.KeepAspectRatio)
     self.labelImage.setPixmap(pixmapScaled)