def paintEvent(self, event): outerRadius = min(self.width(), self.height()) baseRect = QRectF(1, 1, outerRadius - 2, outerRadius - 2) buffer = QImage(outerRadius, outerRadius, QImage.Format_ARGB32) buffer.fill(0) p = QPainter(buffer) p.setRenderHint(QPainter.Antialiasing) # data brush self.rebuildDataBrushIfNeeded() # background self.drawBackground(p, buffer.rect()) # base circle self.drawBase(p, baseRect) # data circle arcStep = 360.0 / (self.max - self.min) * self.value self.drawValue(p, baseRect, self.value, arcStep) # center circle innerRect, innerRadius = self.calculateInnerRect(baseRect, outerRadius) self.drawInnerBackground(p, innerRect) # text self.drawText(p, innerRect, innerRadius, self.value) # finally draw the bar p.end() painter = QPainter(self) painter.drawImage(0, 0, buffer)
def run(self): image = QImage() image.load(str(self.filename)) mask = QImage(image.size(), QImage.Format_RGB32) mask.fill(Qt.black) maskfile = self.filename.parent / (self.filename.stem + ".mask") if maskfile.exists(): bitmap = QImage(str(maskfile)) if bitmap.size() != image.size(): raise Exception("Mask %s doesn't match image size" % maskfile) mask.fill(QColor.fromRgbF(1.0, 0.0, 1.0)) p = QPainter(mask) p.setCompositionMode(QPainter.CompositionMode_Multiply) p.drawImage(mask.rect(), bitmap) p.end() self.view.imagefile = self.filename self.view.image = image self.view.mask = mask self.view.maskfile = maskfile self.view.path = list() self.view.changed = False self.view.update()
def get_whole_scene_img(self): self.hide_proxies() img = QImage(self.sceneRect().width() / self.total_scale_div, self.sceneRect().height() / self.total_scale_div, QImage.Format_RGB32) img.fill(Qt.transparent) painter = QPainter(img) painter.setRenderHint(QPainter.Antialiasing) rect = QRectF() rect.setLeft(-self.viewport().pos().x()) rect.setTop(-self.viewport().pos().y()) rect.setWidth(img.rect().width()) rect.setHeight(img.rect().height()) # rect is right... but it only renders from the viewport's point down-and rightwards, not from topleft (0,0) ... self.render(painter, rect, rect.toRect()) self.show_proxies() return img
def _show_legend(self): pen = QPen(Qt.transparent) gradient = self._make_legend_gradient(self.LEGEND_X, self.LEGEND_Y, self.LEGEND_X, self.LEGEND_Y + self.legend_height) brush = QBrush(gradient) self.legend = self.traceScene.addRect(self.LEGEND_X, self.LEGEND_Y, self.LEGEND_WIDTH, self.legend_height, pen, brush) reference_gradient = self._make_legend_gradient(0, 0, self.LEGEND_WIDTH, 1000) base_img = QImage(self.LEGEND_WIDTH, 1000, QImage.Format.Format_ARGB32) p = QPainter(base_img) p.fillRect(base_img.rect(),reference_gradient) self.legend_img = base_img #reference shade
def paint(self, painter): """ Overrides QQuickPaintedItem.paint(). This creates the image in the QML item. The QQuickPaintedItem.update() method will schedule a paint request to be processed by the QML Scene Graph when the next frame is rendered. The item will only be redrawn if it is visible. http://doc.qt.io/qt-5/qquickpainteditem.html#paint http://doc.qt.io/qt-5/qquickpainteditem.html#update """ try: # image_bytes_argb = self._canvas.tostring_argb() # It's not clear what the deal is here... this is supposedly in rgba order, but we specify ARGB32 # as the format? If it were an endianness issue, it'd need to be ABGR, not ARGB...? image_bytes_rgba = self._canvas.buffer_rgba() except AttributeError: # If canvas.draw() hasn't been called yet, it'll fail to find the renderer... just move on. return image = QImage(image_bytes_rgba, self._width_px, self._height_px, QImage.Format_ARGB32) pixmap = QPixmap.fromImage(image) image_rect = image.rect() painter.eraseRect(image_rect) painter.drawPixmap(QPoint(0, 0), pixmap)
class View(QWidget): previous = Signal() next = Signal() def __init__(self, window): super(View, self).__init__(window) self.setFocusPolicy(Qt.StrongFocus) self.shiftKey = False self.ctrlKey = False self.lastMousePos = QPoint() self.lastTabletPos = QPoint() self.mode = 'add' self.maskOnly = False self.refresh = QTimer(self) self.refresh.setSingleShot(True) self.refresh.timeout.connect(self.repaint) self.addCursor = makeCursor('images/cursor-add.png', QColor.fromRgbF(0.5, 0.5, 1.0)) self.delCursor = makeCursor('images/cursor-del.png', QColor.fromRgbF(1.0, 0.5, 0.5)) self.setCursor(self.addCursor) self.imagefile = None self.maskfile = None self.image = QImage() self.mask = QImage(self.image.size(), QImage.Format_RGB32) self.mask.fill(Qt.black) self.changed = False self.update() self.path = list() self.load_threads = QThreadPool() self.load_threads.setMaxThreadCount(4) def load(self, filename): self.load_threads.start(LoadTask(self, filename)) def save(self): if self.maskfile and self.changed: self.load_threads.waitForDone() if self.maskfile and self.changed: bitmap = self.mask.createMaskFromColor( QColor.fromRgbF(1.0, 0.0, 1.0).rgb()) bitmap.save(str(self.maskfile), "PNG") self.changed = False def update(self): widgetRatio = self.width() / self.height() aspectRatio = self.image.width() / max(1, self.image.height()) if aspectRatio >= widgetRatio: width = self.width() height = self.width() / aspectRatio else: width = self.height() * aspectRatio height = self.height() self.rc = QRectF((self.width() - width) / 2.0, (self.height() - height) / 2.0, width, height) self.repaint() def resizeEvent(self, event): self.update() def paintEvent(self, event): p = QPainter(self.mask) for (mode, p1, p2, weight) in self.path: if mode == 'add': p.setPen( QPen(QColor.fromRgbF(1.0, 0.0, 1.0), (weight * 10.0)**2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) else: p.setPen( QPen(QColor.fromRgbF(0.0, 0.0, 0.0), (weight * 10.0)**2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) p.drawLine(realCoords(p1, self.mask.rect()), realCoords(p2, self.mask.rect())) self.changed = True self.path = list() p.end() p = QPainter(self) p.setCompositionMode(QPainter.CompositionMode_SourceOver) if not self.maskOnly: p.drawImage(self.rc, self.image) p.setCompositionMode(QPainter.CompositionMode_Plus) p.drawImage(self.rc, self.mask) p.end() def closeEvent(self, event): self.refresh.stop() event.accept() def enterEvent(self, event): self.setFocus(Qt.OtherFocusReason) def keyPressEvent(self, event): k = event.key() if k == Qt.Key_Shift: self.shiftKey = True if k == Qt.Key_Control: self.ctrlKey = True if k == Qt.Key_Space: self.maskOnly = not self.maskOnly self.repaint() def keyReleaseEvent(self, event): k = event.key() mod = event.modifiers() if k == Qt.Key_Shift: self.shiftKey = False if k == Qt.Key_Control: self.ctrlKey = False def mousePressEvent(self, event): x = event.x() y = event.y() self.lastMousePos = event.pos() if event.button() == Qt.ExtraButton1: if self.mode == 'add': self.mode = 'del' self.setCursor(self.delCursor) else: self.mode = 'add' self.setCursor(self.addCursor) elif event.button() == Qt.ExtraButton2: self.maskOnly = not self.maskOnly self.repaint() elif event.button() == Qt.ExtraButton3: self.previous.emit() elif event.button() == Qt.ExtraButton4: self.next.emit() def mouseMoveEvent(self, event): x = event.x() y = event.y() dx = x - self.lastMousePos.x() dy = y - self.lastMousePos.y() self.lastMousePos = event.pos() # if event.buttons() & Qt.LeftButton: # elif event.buttons() & Qt.MiddleButton: # elif event.buttons() & Qt.RightButton: def wheelEvent(self, event): dx = event.angleDelta().x() / 8 dy = event.angleDelta().y() / 8 # self.cameraZoom.emit(dy / 15) def tabletEvent(self, event): if event.device() == QTabletEvent.Stylus and event.pointerType( ) == QTabletEvent.Pen: if event.type() == QEvent.TabletPress: self.tabletPressEvent(event) elif event.type() == QEvent.TabletRelease: self.tabletReleaseEvent(event) elif event.type() == QEvent.TabletMove: if event.pressure() > 0.0: self.tabletMoveEvent(event) else: print('tabletEvent', event.device(), event.type(), event.pointerType()) else: print('tabletEvent', event.device(), event.type(), event.pointerType()) def tabletPressEvent(self, event): if event.buttons() & Qt.LeftButton: self.lastTabletPos = normalizeCoords(event.posF(), self.rc) if event.buttons() & Qt.MiddleButton: if self.mode == 'add': self.mode = 'del' self.setCursor(self.delCursor) else: self.mode = 'add' self.setCursor(self.addCursor) if event.buttons() & Qt.RightButton: self.next.emit() def tabletReleaseEvent(self, event): self.lastTabletPos = normalizeCoords(event.posF(), self.rc) def tabletMoveEvent(self, event): self.path.append((self.mode, self.lastTabletPos, normalizeCoords(event.posF(), self.rc), event.pressure())) self.lastTabletPos = normalizeCoords(event.posF(), self.rc) if not self.refresh.isActive(): self.refresh.start(50)
def paintEvent(self, e): """ Overrides QLabel paintEvent(). Displays the presentation layer of a vImage object, with its current offset and zooming coefficient. @param e: paint event @type e: """ mimg = self.img if mimg is None: return r = mimg.resize_coeff(self) qp = self.qp window = self.window qp.begin(self) # smooth painting qp.setRenderHint(QPainter.SmoothPixmapTransform) # TODO may be useless # fill background qp.fillRect(QRect(0, 0, self.width(), self.height()), vImage.defaultBgColor) # draw presentation layer. # As offsets can be float numbers, we use a QRectF instead of a QRect. # r is relative to the full resolution image, so we use mimg width and height w, h = mimg.width() * r, mimg.height() * r rectF = QRectF(mimg.xOffset, mimg.yOffset, w, h) # draw a checker background to view (semi-)transparent images qp.fillRect(rectF, imageLabel.checkerBrush) px = mimg.prLayer.qPixmap if px is not None: qp.drawPixmap(rectF, px, px.rect()) else: currentImage = mimg.prLayer.getCurrentImage() qp.drawImage( rectF, currentImage, QImage.rect(currentImage) ) # CAUTION : vImage.rect() is overwritten by the attribute rect # draw selection rectangle and cloning marker of the active layer, if any layer = mimg.getActiveLayer() rect, mark = layer.rect, layer.marker if layer.visible: if rect is not None: qp.setPen(Qt.green) qp.drawRect(rect.left() * r + mimg.xOffset, rect.top() * r + mimg.yOffset, rect.width() * r, rect.height() * r) if not (mark is None or layer.sourceFromFile): qp.setPen(Qt.white) qp.drawEllipse(mark.x() * r + mimg.xOffset, mark.y() * r + mimg.yOffset, 10, 10) # draw the cropping marks lm, rm, tm, bm = 0, 0, 0, 0 if mimg.isCropped: c = QColor(128, 128, 128, 192) lm = window.cropTool.btnDict['left'].margin * r rm = window.cropTool.btnDict['right'].margin * r tm = window.cropTool.btnDict['top'].margin * r bm = window.cropTool.btnDict['bottom'].margin * r qp.fillRect(QRectF(mimg.xOffset, mimg.yOffset, lm, h), c) # left qp.fillRect(QRectF(mimg.xOffset + lm, mimg.yOffset, w - lm, tm), c) # top qp.fillRect( QRectF(mimg.xOffset + w - rm, mimg.yOffset + tm, rm, h - tm), c) # right qp.fillRect( QRectF(mimg.xOffset + lm, mimg.yOffset + h - bm, w - lm - rm, bm), c) # bottom # draw rulers if mimg.isRuled: deltaX, deltaY = (w - lm - rm) // 3, (h - tm - bm) // 3 qp.drawLine(lm + mimg.xOffset, deltaY + tm + mimg.yOffset, w - rm + mimg.xOffset, deltaY + tm + mimg.yOffset) qp.drawLine(lm + mimg.xOffset, 2 * deltaY + tm + mimg.yOffset, w - rm + mimg.xOffset, 2 * deltaY + tm + mimg.yOffset) qp.drawLine(deltaX + lm + mimg.xOffset, tm + mimg.yOffset, deltaX + lm + mimg.xOffset, h - bm + mimg.yOffset) qp.drawLine(2 * deltaX + lm + mimg.xOffset, tm + mimg.yOffset, 2 * deltaX + lm + mimg.xOffset, h - bm + mimg.yOffset) # tag before/after views name = self.objectName() if name == "label_2" or name == "label_3": # draw filled rect qp.fillPath(qp.markPath, QBrush(Qt.gray)) # draw text qp.setPen(Qt.white) qp.setFont(qp.font) qp.drawText(qp.markRect, Qt.AlignCenter | Qt.AlignVCenter, "Before" if name == "label_2" else "After") qp.end()
class CanvasWidget(QLabel): def __init__(self, parent=None): super(CanvasWidget, self).__init__(parent) self.state = 0 self.toolState = 0 # pen:1,scissor:2 self.scissorLogic = None self.img_w = 0 self.img_h = 0 self.img = None self.drawItemList = { "images": [], "lines": [], "polylines": [], "points": [] } self.makeCurve = False self.mouseInPoint = False self.makeControlP = False self.selectedItem = {"points": [], "in_lines": [], "out_lines": []} self.seleced = 0 self.setMouseTracking(True) self.initUI() pass def initUI(self): self.qp = QPainter() self.backView = QImage(785, 703, QImage.Format_RGB888) self.opeView = QImage(785, 703, QImage.Format_RGB888) self.setImage(dir) pass # 槽函数 def paintEvent(self, event): self.drawList(self.qp, self.opeView, self.drawItemList) self.qp.begin(self) self.qp.drawImage(event.rect(), self.opeView) self.qp.end() pass def drawBackView(self, i): self.qp.begin(self.backView) self.qp.end() pass def drawOpeView(self): self.qp.begin(self.opeView) self.qp.end() pass def mouseMoveEvent(self, event): pos = event.localPos() if self.state == 1 and self.toolState == 1: print("state1") self.selectedItem["points"] = [] self.selectedItem["in_lines"] = [] self.selectedItem["out_lines"] = [] for item in self.drawItemList["points"]: if item.disToPoint(pos.x(), pos.y(), 5): self.selectedItem["points"].append(item) print("in point") break print(id(self.selectedItem["points"])) if len(self.selectedItem["points"]) >= 1: print("in") self.state = 2 self.selectedItem["points"][0].onMouseIn() self.update() elif self.state == 2 and self.toolState == 1: print("state2") if not self.selectedItem["points"][0].disToPoint( pos.x(), pos.y(), 5): self.state = 1 self.selectedItem["points"][0].onMouseOut() self.selectedItem["points"] = [] self.selectedItem["in_lines"] = [] self.selectedItem["out_lines"] = [] self.update() elif self.state == 3 and self.toolState == 1: print("state3") self.selectedItem["points"][0].x = int(pos.x()) self.selectedItem["points"][0].y = int(pos.y()) for i in self.selectedItem["in_lines"]: i.setP2(int(pos.x()), int(pos.y())) print(self.selectedItem["out_lines"]) for i in self.selectedItem["out_lines"]: i.setP1(int(pos.x()), int(pos.y())) cPoint = self.selectedItem["points"][0] if cPoint.id & DrawItem.ID_CONTROL != 0: if cPoint.item.controlP1[ 0] == cPoint.x and cPoint.item.controlP1[1] == cPoint.y: cPoint.item.setControlP1(int(pos.x()), int(pos.y())) else: cPoint.item.setControlP2(int(pos.x()), int(pos.y())) self.update() # scissor elif self.state == 0 and self.toolState == 2: # list[0]=itemStaticList,list[1]=itemDynamicList list = [ x for x in self.drawItemList["lines"] if x.id & DrawItem.ID_SCISSOR != 0 ] freeX = pos.x() / self.width() * self.img.shape[1] freeY = pos.y() / self.height() * self.img.shape[0] if self.scissorLogic.scissor.isSetSeed: xs, ys = self.scissorLogic.CalculateMininumPath( int(freeY), int(freeX)) print("add") print(xs) list[1].xs = xs list[1].ys = ys self.update() pass pass def mousePressEvent(self, event): pos = event.localPos() # 状态机实现,Pen if self.state == 0 and self.toolState == 1: # 空状态 print("state:0") item = ItemPoint(pos.x(), pos.y()) item.width = self.width() item.height = self.height() item.id = DrawItem.ID_PEN | DrawItem.ID_END item.pen = QPen(Qt.red, 6) self.drawItemList["points"].append(item) self.state = 1 self.update() elif self.state == 1 and self.toolState == 1: print("state:1") # 至少有一个点 # 画点 item = ItemPoint(pos.x(), pos.y()) item.width = self.width() item.height = self.height() item.id = DrawItem.ID_PEN | DrawItem.ID_END item.pen = QPen(Qt.red, 6) self.drawItemList["points"].append(item) # 画一条线 penPointlist = [ x for x in self.drawItemList["points"] if (x.id ^ (DrawItem.ID_PEN | DrawItem.ID_END)) == 0 ] i = penPointlist[-2] print("pen id") print(penPointlist) print(i.id) line = ItemBezierLine(20, i.x, i.y, pos.x(), pos.y()) line.width = self.width() line.height = self.height() line.pen = QPen(Qt.red, 3) line.id = DrawItem.ID_PEN print(i.x, i.y) self.drawItemList["lines"].append(line) self.update() elif self.state == 2 and self.toolState == 1: if event.button() == Qt.LeftButton: print("press left state 2") item = self.selectedItem["points"][0] penLineItem = [ x for x in self.drawItemList["lines"] if x.id & DrawItem.ID_PEN != 0 ] for i in penLineItem: if i.x1 == item.x and i.y1 == item.y: self.selectedItem["out_lines"].append(i) elif i.x2 == item.x and i.y2 == item.y: self.selectedItem["in_lines"].append(i) self.state = 3 elif event.button() == Qt.RightButton: print("press right state 2") item = self.selectedItem["points"][0] penLineItem = [ x for x in self.drawItemList["lines"] if (x.type == "bezier line" and x.id & DrawItem.ID_PEN != 0 ) ] for i in penLineItem: if i.x1 == item.x and i.y1 == item.y and not i.hasControlP1: self.selectedItem["out_lines"].append(i) elif i.x2 == item.x and i.y2 == item.y and not i.hasControlP2: self.selectedItem["in_lines"].append(i) if len(self.selectedItem["in_lines"]) <= 0 and len( self.selectedItem["out_lines"]) <= 0: return else: self.state = 4 elif self.state == 4 and self.toolState == 1: # 添加控制点 print("state4") item = DrawItem.ItemControlPoint(pos.x(), pos.y()) item.width = self.width() item.height = self.height() if len(self.selectedItem["out_lines"]) > 0: for line in self.selectedItem["out_lines"]: line.setControlP1(pos.x(), pos.y()) item.item = line if len(self.selectedItem["in_lines"]) > 0: for line in self.selectedItem["in_lines"]: line.setControlP2(pos.x(), pos.y()) item.item = line item.pen = QPen(Qt.green, 6) item.id = DrawItem.ID_PEN | DrawItem.ID_CONTROL self.drawItemList["points"].append(item) line = DrawItem.ItemLine(self.selectedItem["points"][0].x, self.selectedItem["points"][0].y, pos.x(), pos.y()) line.width = self.width() line.height = self.height() line.pen = QPen(Qt.yellow, 3) line.id = DrawItem.ID_PEN self.drawItemList["lines"].append(line) self.state = 2 self.update() pass # scissor elif self.state == 0 and self.toolState == 2: print("scissor set seed start") x = pos.x() * self.img_w / self.width() y = pos.y() * self.img_h / self.height() list = [ item for item in self.drawItemList["lines"] if item.id & DrawItem.ID_SCISSOR != 0 ] l = IntelligentScissor.DEFAULT_SEARCh_LENGTH x1 = x - l / 2 if x - l / 2 >= 0 else 0 y1 = y - l / 2 if y - l / 2 >= 0 else 0 x2 = x + l / 2 if x + l / 2 < self.img_w else self.img_w - 1 y2 = y + l / 2 if y + l / 2 < self.img_h else self.img_h - 1 if not self.scissorLogic.scissor.isSetSeed: print("scissor set seed start") self.scissorLogic.SetSeed(int(y), int(x)) list[0].xs.append(x) list[0].ys.append(y) rect = DrawItem.ItemRect(x1, y1, x2, y2) rect.height = self.img_h rect.width = self.img_w rect.id = DrawItem.ID_SCISSOR pen = QPen(Qt.yellow, 3) pen.setStyle(Qt.DashLine) rect.pen = pen self.drawItemList["polylines"].append(rect) else: seedx = self.scissorLogic.GetSeedC() seedy = self.scissorLogic.GetSeedR() print(seedx) print(seedy) if abs(x - seedx) > l / 2 or abs(y - seedy) > l / 2: return print("scissor set seed start") self.scissorLogic.SetSeed(int(y), int(x)) for i in range(len(list[1].xs)): list[0].xs.append(list[1].xs[-1 - i]) list[0].ys.append(list[1].ys[-1 - i]) list[1].xs = [] list[1].ys = [] rect = None for item in self.drawItemList["polylines"]: if item.id & DrawItem.ID_SCISSOR != 0: rect = item break rect.setPos(x1, y1, x2, y2) print(x1, y1, x2, y2) print("top") print(list[0].xs[-1]) print(list[0].ys[-1]) self.scissorLogic.LiveWireDP(int(y), int(x)) self.update() pass def mouseReleaseEvent(self, event): if self.state == 3 and self.toolState == 1: self.state = 2 pass def setImage(self, dir): img = QImage(dir) self.img_w = img.width() self.img_h = img.height() self.img = cv2.imread(dir) self.qp.begin(self.backView) self.qp.drawImage(self.backView.rect(), img) self.qp.end() # {"images": [], "lines": [], "points": []} def drawList(self, painter: QPainter, view: QPaintDevice, list): if len(list) <= 0: return print("start draw item:") print("-----------------------") for keys, value in enumerate(list): if len(list[value]) > 0: for item in list[value]: item.testType() item.paint(painter, view) print("-----------------------") pass def linearTrans(self, x, y, w0, h0, w1, h1): return (x * w1 / w0, y * h1 / h0)
class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1024, 590) MainWindow.setMinimumSize(QtCore.QSize(1024, 590)) MainWindow.setMaximumSize(QtCore.QSize(1024, 590)) MainWindow.setStyleSheet("background-color: rgb(220, 220, 220);") self.switch = 0 self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(10, 10, 166, 41)) self.label.setStyleSheet( "border-image: url(:/newPrefix/WhatsApp Image 2020-09-11 at 12.46.25 AM.jpeg);" ) pixmap = QPixmap(r"D:\finalapp\images\applogo.jpeg") self.label.setPixmap(pixmap) self.label.setScaledContents(True) self.label.setText("") self.label.setObjectName("label") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(950, 10, 31, 31)) self.pushButton.setStyleSheet( "border-image: url(:/newPrefix/help.png);") self.pushButton.setText("") self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(910, 10, 31, 31)) self.pushButton_2.setStyleSheet( "border-image: url(:/newPrefix/contact.jpg);") self.pushButton_2.setText("") self.pushButton_2.setObjectName("pushButton_2") self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(180, 50, 341, 91)) self.label_2.setStyleSheet("border: 2px solid black;\n" "background-color: rgb(255, 255, 255);") self.label_2.setText("") self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(540, 50, 341, 91)) self.label_3.setStyleSheet("border: 2px solid black;\n" "background-color: rgb(255, 255, 255);") self.label_3.setText("") self.label_3.setObjectName("label_3") self.label_4 = QtWidgets.QLabel(self.centralwidget) self.label_4.setGeometry(QtCore.QRect(200, 70, 81, 16)) self.label_4.setStyleSheet("font: 87 11pt \"Arial Black\";\n" "background-color: rgb(255, 255, 255);") self.label_4.setScaledContents(True) self.label_4.setIndent(-1) self.label_4.setObjectName("label_4") self.label_6 = QtWidgets.QLabel(self.centralwidget) self.label_6.setGeometry(QtCore.QRect(200, 100, 91, 16)) self.label_6.setStyleSheet("font: 87 11pt \"Arial Black\";\n" "background-color: rgb(255, 255, 255);") self.label_6.setScaledContents(True) self.label_6.setIndent(-1) self.label_6.setObjectName("label_6") self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setGeometry(QtCore.QRect(300, 70, 161, 21)) self.lineEdit.setObjectName("lineEdit") self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setGeometry(QtCore.QRect(300, 100, 161, 21)) self.lineEdit_2.setObjectName("lineEdit_2") self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_4.setGeometry(QtCore.QRect(470, 100, 31, 21)) self.pushButton_4.setStyleSheet( "border-image: url(:/newPrefix/submit.png);") self.pushButton_4.setText("") self.pushButton_4.setObjectName("pushButton_4") self.pushButton_4.clicked.connect(self.password) self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_3.setGeometry(QtCore.QRect(470, 70, 31, 21)) self.pushButton_3.setAutoFillBackground(False) self.pushButton_3.setStyleSheet( "border-image: url(:/newPrefix/file.jpg);") self.pushButton_3.setText("") self.pushButton_3.setIconSize(QtCore.QSize(11, 11)) self.pushButton_3.setObjectName("pushButton_3") self.pushButton_3.clicked.connect(self.browseImage) self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_5.setGeometry(QtCore.QRect(550, 60, 101, 31)) self.pushButton_5.setStyleSheet("font: 87 8pt \"Arial Black\";") self.pushButton_5.setObjectName("pushButton_5") self.pushButton_5.clicked.connect(self.open_settings) self.pushButton_6 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_6.setGeometry(QtCore.QRect(770, 60, 101, 31)) self.pushButton_6.setStyleSheet("font: 87 8pt \"Arial Black\";") self.pushButton_6.setObjectName("pushButton_6") self.pushButton_6.clicked.connect(self.openFontDialog) self.pushButton_7 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_7.setGeometry(QtCore.QRect(660, 60, 101, 31)) self.pushButton_7.setStyleSheet("font: 87 8pt \"Arial Black\";") self.pushButton_7.setObjectName("pushButton_7") self.pushButton_7.clicked.connect(self.printpreviewDialog) self.pushButton_8 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_8.setGeometry(QtCore.QRect(660, 100, 101, 31)) self.pushButton_8.setStyleSheet("font: 87 8pt \"Arial Black\";") self.pushButton_8.setObjectName("pushButton_8") self.pushButton_8.clicked.connect(self.resizeimage) self.pushButton_9 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_9.setGeometry(QtCore.QRect(550, 100, 101, 31)) self.pushButton_9.setStyleSheet("font: 87 8pt \"Arial Black\";") self.pushButton_9.setObjectName("pushButton_9") self.pushButton_9.clicked.connect(self.trouble) self.pushButton_10 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_10.setGeometry(QtCore.QRect(770, 100, 101, 31)) self.pushButton_10.setStyleSheet("font: 87 8pt \"Arial Black\";") self.pushButton_10.setObjectName("pushButton_10") self.line = QtWidgets.QFrame(self.centralwidget) self.line.setGeometry(QtCore.QRect(0, 160, 1021, 31)) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.checkBox = QtWidgets.QCheckBox(self.centralwidget) self.checkBox.setGeometry(QtCore.QRect(20, 540, 121, 21)) font = QtGui.QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.checkBox.setFont(font) self.checkBox.setObjectName("checkBox") self.checkBox.stateChanged.connect(self.clickBox) self.checkBox_2 = QtWidgets.QCheckBox(self.centralwidget) self.checkBox_2.setGeometry(QtCore.QRect(880, 540, 121, 21)) self.checkBox_2.stateChanged.connect(self.clickBox2) font = QtGui.QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.checkBox_2.setFont(font) self.checkBox_2.setObjectName("checkBox_2") self.label_5 = QtWidgets.QLabel(self.centralwidget) self.label_5.setGeometry(QtCore.QRect(10, 210, 1001, 311)) self.label_5.setStyleSheet("background-color: rgb(239, 239, 239);") self.label_5.setText("") self.label_5.setObjectName("label_5") self.groupBox = QtWidgets.QGroupBox(self.centralwidget) self.groupBox.setGeometry(QtCore.QRect(18, 215, 490, 300)) self.groupBox.setTitle("") self.groupBox.setObjectName("groupBox") self.label_7 = QtWidgets.QLabel(self.groupBox) self.label_7.setGeometry(QtCore.QRect(0, 0, 491, 53)) self.label_7.setStyleSheet("") self.label_7.setText("") self.label_7.setObjectName("label_7") self.label_9 = QtWidgets.QLabel(self.groupBox) self.label_9.setGeometry(QtCore.QRect(40, 50, 120, 152)) self.label_9.setStyleSheet("") self.label_9.setText("") self.label_9.setObjectName("label_9") self.label_10 = QtWidgets.QLabel(self.groupBox) self.label_10.setGeometry(QtCore.QRect(170, 63, 251, 25)) self.label_10.setStyleSheet("") self.label_10.setText("") self.label_10.setObjectName("label_10") self.label_11 = QtWidgets.QLabel(self.groupBox) self.label_11.setGeometry(QtCore.QRect(170, 89, 251, 25)) self.label_11.setStyleSheet("") self.label_11.setText("") self.label_11.setObjectName("label_11") self.label_12 = QtWidgets.QLabel(self.groupBox) self.label_12.setGeometry(QtCore.QRect(170, 115, 251, 25)) self.label_12.setStyleSheet("") self.label_12.setText("") self.label_12.setObjectName("label_12") self.label_13 = QtWidgets.QLabel(self.groupBox) self.label_13.setGeometry(QtCore.QRect(170, 140, 251, 21)) self.label_13.setStyleSheet("") self.label_13.setText("") self.label_13.setObjectName("label_13") self.label_14 = QtWidgets.QLabel(self.groupBox) self.label_14.setGeometry(QtCore.QRect(170, 170, 251, 25)) self.label_14.setStyleSheet("") self.label_14.setText("") self.label_14.setObjectName("label_14") self.label_15 = QtWidgets.QLabel(self.groupBox) self.label_15.setGeometry(QtCore.QRect(0, 270, 491, 32)) self.label_15.setStyleSheet("") self.label_15.setText("") self.label_15.setObjectName("label_15") self.label_16 = QtWidgets.QLabel(self.groupBox) self.label_16.setGeometry(QtCore.QRect(0, 267, 491, 5)) self.label_16.setStyleSheet("") self.label_16.setText("") self.label_16.setObjectName("label_16") self.label_20 = QtWidgets.QLabel(self.groupBox) self.label_20.setGeometry(QtCore.QRect(10, 60, 16, 141)) self.label_20.setText("") self.label_20.setObjectName("label_20") self.label_21 = QtWidgets.QLabel(self.groupBox) self.label_21.setGeometry(QtCore.QRect(460, 70, 16, 171)) self.label_21.setText("") self.label_21.setObjectName("label_21") self.label_23 = QtWidgets.QLabel(self.groupBox) self.label_23.setGeometry(QtCore.QRect(90, 246, 311, 23)) self.label_23.setStyleSheet("font-size:12") self.label_23.setFont(QFont('Arial', 12, weight=QtGui.QFont.Bold)) self.label_23.setObjectName("label_23") self.label_23.setAlignment(Qt.AlignAbsolute) self.label_24 = QtWidgets.QLabel(self.groupBox) self.label_24.setGeometry(QtCore.QRect(110, 222, 311, 23)) self.label_24.setStyleSheet("font-size:15") self.label_24.setFont(QFont('Arial', 12, weight=QtGui.QFont.Bold)) self.label_24.setObjectName("label_24") self.label_24.setAlignment(Qt.AlignBottom) self.label_31 = QtWidgets.QLabel(self.groupBox) self.label_31.setGeometry(QtCore.QRect(10, 60, 21, 141)) self.label_31.setStyleSheet("") self.label_31.setText("") self.label_31.setObjectName("label_31") self.label_32 = QtWidgets.QLabel(self.groupBox) self.label_32.setGeometry(QtCore.QRect(450, 70, 31, 171)) self.label_32.setStyleSheet("") self.label_32.setText("") self.label_32.setObjectName("label_32") self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget) self.groupBox_2.setGeometry(QtCore.QRect(515, 215, 490, 300)) self.groupBox_2.setTitle("") self.groupBox_2.setObjectName("groupBox_2") self.label_8 = QtWidgets.QLabel(self.groupBox_2) self.label_8.setGeometry(QtCore.QRect(0, 0, 491, 51)) self.label_8.setText("") self.label_8.setObjectName("label_8") self.label_17 = QtWidgets.QLabel(self.groupBox_2) self.label_17.setGeometry(QtCore.QRect(0, 0, 491, 51)) self.label_17.setStyleSheet("") self.label_17.setText("") self.label_17.setObjectName("label_17") self.label_19 = QtWidgets.QLabel(self.groupBox_2) self.label_19.setGeometry(QtCore.QRect(0, 269, 491, 31)) self.label_19.setStyleSheet("") self.label_19.setText("") self.label_19.setObjectName("label_19") self.label_18 = QtWidgets.QLabel(self.groupBox_2) self.label_18.setGeometry(QtCore.QRect(0, 262, 491, 5)) self.label_18.setStyleSheet("") self.label_18.setText("") self.label_18.setObjectName("label_18") self.label_22 = QtWidgets.QLabel(self.groupBox_2) self.label_22.setGeometry(QtCore.QRect(330, 70, 143, 143)) self.label_22.setText("") self.label_22.setObjectName("label_22") self.label_25 = QtWidgets.QLabel(self.groupBox_2) self.label_25.setGeometry(QtCore.QRect(330, 60, 143, 143)) self.label_25.setStyleSheet("") self.label_25.setText("") self.label_25.setObjectName("label_25") self.label_26 = QtWidgets.QLabel(self.groupBox_2) self.label_26.setGeometry(QtCore.QRect(330, 220, 161, 21)) self.label_26.setStyleSheet("") self.label_26.setText("") self.label_26.setObjectName("label_26") self.label_27 = QtWidgets.QLabel(self.groupBox_2) self.label_27.setGeometry(QtCore.QRect(70, 220, 261, 21)) self.label_27.setStyleSheet("font-size:15") self.label_27.setText("") self.label_27.setFont(QFont('Arial', 12, weight=QtGui.QFont.Bold)) self.label_27.setObjectName("label_27") self.label_27.setAlignment(Qt.AlignAbsolute) self.label_28 = QtWidgets.QLabel(self.groupBox_2) self.label_28.setGeometry(QtCore.QRect(30, 240, 281, 22)) self.label_28.setStyleSheet("") self.label_28.setStyleSheet("font-size:12") self.label_28.setText("") self.label_28.setFont(QFont('Arial', 12, weight=QtGui.QFont.Bold)) self.label_28.setObjectName("label_28") self.label_28.setAlignment(Qt.AlignAbsolute | Qt.AlignJustify) self.label_29 = QtWidgets.QLabel(self.groupBox_2) self.label_29.setGeometry(QtCore.QRect(10, 60, 321, 75)) self.label_29.setStyleSheet("") self.label_29.setText("") self.label_29.setObjectName("label_29") self.label_30 = QtWidgets.QLabel(self.groupBox_2) self.label_30.setGeometry(QtCore.QRect(10, 140, 341, 75)) self.label_30.setStyleSheet("") self.label_30.setText("") self.label_30.setObjectName("label_30") MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) # create temp folder self.path = tempfile.mkdtemp() def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Aapki Pehchaan")) self.label_4.setText(_translate("MainWindow", "Filename:")) self.label_6.setText(_translate("MainWindow", "Password:"******"MainWindow", "Settings")) self.pushButton_6.setText(_translate("MainWindow", "Font")) self.pushButton_7.setText(_translate("MainWindow", "Print")) self.pushButton_8.setText(_translate("MainWindow", "Resize")) self.pushButton_9.setText(_translate("MainWindow", "Report")) self.pushButton_10.setText(_translate("MainWindow", "License")) self.checkBox.setText(_translate("MainWindow", "PRINT FRONT")) self.checkBox_2.setText(_translate("MainWindow", "PRINT BACK")) def clickBox(self, state): if state == QtCore.Qt.Checked: print('Checked') self.take_screenshot() else: print('Unchecked') def clickBox2(self, state): if state == QtCore.Qt.Checked: print('Checked') self.take_screenshot2() else: print('Unchecked') def topimage(self): pixmap = QPixmap(r'images/Ashok Stambh Front.png') self.label_7.setPixmap(pixmap) self.label_7.setScaledContents(True) def nextpagebottomimage(self): pixmap = QPixmap(r'D:\finalapp\images\Back side Symbol.png') self.label_19.setPixmap(pixmap) self.label_19.setScaledContents(True) def photoextraction(self, doc): for i in range(len(doc)): for img in doc.getPageImageList(i): xref = img[0] pix = fitz.Pixmap(doc, xref) if pix.n < 1: pix.writePNG( os.path.join(self.path, "p%s-%s.png" % (i, xref))) else: pix1 = fitz.Pixmap(fitz.csRGB, pix) pix1.writePNG( os.path.join(self.path, "p%s-%s.png" % (i, xref))) try: # HUMAN IMAGE IN ADHAR if pix.width == float( 0.8 ) * pix.height or pix.width == 0.75 * pix.height: self.human_image = os.path.join( self.path, "p%s-%s.png" % (i, xref)) pixmap = QPixmap(self.human_image) self.label_9.setPixmap(pixmap) self.label_9.setScaledContents(True) # SCANNER CODE IN ADHAR elif pix.width == pix.height: pixmap = QPixmap( os.path.join(self.path, "p%s-%s.png" % (i, xref))) self.label_25.setPixmap(pixmap) self.label_25.setScaledContents(True) except Exception as e: print(e) print("fault in human and scanner image") def setText_to_elements(self, a): self.label_13.setText(self.text_ex['DOB']) self.label_10.setText(self.text_ex['namehindi']) self.label_11.setText(self.text_ex['englishname']) self.label_12.setText(self.text_ex['gender string']) self.label_29.setText(self.text_ex['hindiAddress']) self.label_30.setText("Address: " + "\n" + self.text_ex['engAddress']) self.label_30.adjustSize() self.label_27.setText(self.text_ex['Adhaar no']) if (self.text_ex['VID'] != None): self.label_23.setText("VID: " + self.text_ex['VID']) self.label_23.adjustSize() self.label_23.setStyleSheet( "border-top:0.5px solid rgb(220, 220, 220);") self.label_28.setText("VID: " + self.text_ex['VID']) self.label_28.adjustSize() self.label_28.setStyleSheet( "border-top:0.5px solid rgb(220, 220, 220);") self.label_24.setText(self.text_ex['Adhaar no']) def password(self): self.switch = 1 r = self.lineEdit.text() pwd = self.lineEdit_2.text() if pwd != "": try: mypdf = pikepdf.open(r, pwd) r = os.path.join(self.path, "/pdffile", r, "unlocked.pdf") mypdf.save(r) except pikepdf._qpdf.PasswordError: print("hi") self.showdialog() # print('cannot decrypt %s with password %s' % (r, pwd)) else: pikepdf.open(r) print(r) # Hit fast api endpoint with PDF file doc = fitz.open(r) # # try: res = requests.post(BASE_URL + '/uploadfile/', files={'pdf': open(r, 'rb')}) data = res.json() self.text_ex = data["text"] name = self.name_ex(doc) self.text_ex["englishname"] = name try: self.groupBox.setStyleSheet("background-color:rgb(255,255,255)") self.groupBox_2.setStyleSheet("background-color:rgb(255,255,255)") self.photoextraction(doc) self.setText_to_elements(self.text_ex) self.nextpagetop() self.topimage() self.redline() self.nextpagetop() self.defaultfooter() self.nextpagebottomimage() self.label_26.clear() except Exception as e: print(e) print("Sorry!response invalid") def image_smoothening(self, img): ret1, th1 = cv2.threshold(img, BINARY_THREHOLD, 255, cv2.THRESH_BINARY) ret2, th2 = cv2.threshold(th1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) blur = cv2.GaussianBlur(th2, (1, 1), 0) ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) return th3 def remove_noise_and_smooth(self, file_name): img = cv2.imread(file_name, 0) img = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC) gaus = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 25) img = self.image_smoothening(gaus) return img def name_ex(self, doc): page = doc.loadPage(0) mat = fitz.Matrix(2, 2) pix = page.getPixmap(matrix=mat) outfile = os.path.join(self.path, "outfile.png") output = pix.writePNG(outfile) image_full = cv2.imread(outfile) path = os.path.join(self.path, "image_full.png") cv2.imwrite(path, image_full) image_front = image_full[1140:1475, 120:500] a = os.path.join(self.path, "image_front.png") cv2.imwrite(a, image_front) image_front1 = self.remove_noise_and_smooth(a) pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' text = pytesseract.image_to_string(image_front1, lang="eng") try: newlist1 = [] for xx in text.split('\n'): newlist1.append(xx) newlist1 = list(filter(lambda x: len(x) > 1, newlist1)) a = 0 str2 = "Government" str1 = "of" for no in newlist1: if str2 in no or str1 in no: b = a a = a + 1 name = newlist1[b + 2] name = name.split(" ") print(name) if len(name) == 2: print(name) name = " ".join(name) print(name) return name else: name = " ".join(name) name = re.sub(r'[(' ')]', '', name) name = re.sub(r'[0-9]+', '', name) # name = re.sub(r'[;'';;!@#!@#!#!$!=()|:><~~' '__-]+','',name) wordlist = self.text_ex['raw'].split("\n") name = get_close_matches(name, wordlist) print(name) return name[0] except Exception as e: print(e) pass def showdialog(self): msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setText("file extension not supported") msg.setWindowTitle("ERROR!") retval = msg.exec_() print("value of pressed message box button:", retval) def browseImage(self): """ this function opens the dialog box. """ foldername = QFileDialog.getOpenFileName() ext = os.path.splitext(foldername[0])[1] valid_extensions = '.pdf' if ext != valid_extensions: print(u'File not supported!') self.showdialog() pdffile = foldername[0] self.lineEdit.setText(pdffile) def printpreviewDialog(self): printer = QPrinter(QPrinter.HighResolution) previewDialog = QPrintPreviewDialog(printer, parent=None, flags=Qt.WindowFlags()) previewDialog.paintRequested.connect(self.printImage) previewDialog.exec_() def printImage(self, printer): "Prints the current diagram" self.image = QImage('test1.tif') # # Create the printer printerobject = QPrinter() # Set the settings printdialog = QPrintDialog(printerobject) if printdialog.exec_() == QDialog.Accepted: painter = QPainter(printer) rect = painter.viewport() size = self.image.size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.image.rect()) painter.drawImage(0, 0, self.image) def take_screenshot2(self): from PySide2 import QtCore as pyqt5c from PySide2 import QtWidgets as pyqt5w screen = pyqt5w.QApplication.primaryScreen() pixmap = screen.grabWindow(self.groupBox_2.winId()) ba = pyqt5c.QByteArray() buff = pyqt5c.QBuffer(ba) pixmap = pixmap.scaled(500, 500, Qt.KeepAspectRatio, Qt.SmoothTransformation) pixmap.save('test1.tif', 'TIF') return ba.data() def take_screenshot(self): from PySide2 import QtCore as pyqt5c from PySide2 import QtWidgets as pyqt5w screen = pyqt5w.QApplication.primaryScreen() pixmap = screen.grabWindow(self.groupBox.winId()) ba = pyqt5c.QByteArray() buff = pyqt5c.QBuffer(ba) pixmap = pixmap.scaled(500, 500, Qt.KeepAspectRatio, Qt.SmoothTransformation) pixmap.save('test1.tif', 'TIF') return ba.data() def openFontDialog(self): ok, font = QFontDialog.getFont() if ok: self.label_10.setFont(font) self.label_11.setFont(font) self.label_12.setFont(font) self.label_13.setFont(font) self.label_14.setFont(font) self.label_30.setFont(font) self.label_29.setFont(font) self.label_10.adjustSize() self.label_11.adjustSize() self.label_12.adjustSize() self.label_13.adjustSize() self.label_14.adjustSize() self.label_30.adjustSize() self.label_29.adjustSize() def trouble(self): self.window = QtWidgets.QMainWindow() self.ui = Ui_MainWindow3() self.ui.setupUi(self.window) self.window.show() def photoframe(self): if self.ui.checkBox_10.isChecked() == True: self.label_9.setStyleSheet("border: 2px solid black;") else: self.label_9.setStyleSheet("border: 0px solid black;") def redline(self): pixmap = QPixmap(r'D:\finalapp\images\redline.jpeg') self.label_16.setPixmap(pixmap) self.label_16.setScaledContents(True) self.label_18.setPixmap(pixmap) self.label_18.setScaledContents(True) def frontpageheader(self): if self.ui.checkBox.isChecked() == True: self.topimage() else: self.label_7.clear() def rearpagefooter(self): if self.ui.checkBox_6.isChecked() == True: self.nextpagebottomimage() else: self.label_19.clear() def phnno(self): if self.ui.checkBox_14.isChecked() == True: self.label_14.setText("Mobile No:" + self.text_ex['mobile no']) else: self.label_14.clear() def put_uid(self): sentence = self.text_ex['Adhaar no'] space = sentence.replace(" ", "") number = space import barcode from barcode.writer import ImageWriter ITF = barcode.get_barcode_class('itf') itf = ITF(number, writer=ImageWriter()) fullname = itf.save('itf_barcode', options={"write_text": False}) print(fullname) pixmap = QPixmap('itf_barcode.png') self.label_26.setPixmap(pixmap) self.label_26.setScaledContents(True) def barcode(self): try: if self.ui.checkBox_7.isChecked() == True: self.put_uid() self.label_28.clear() self.label_27.clear() else: self.label_26.clear() self.label_28.setText("VID: " + self.text_ex['VID']) self.label_27.setText(self.text_ex['Adhaar no']) except: self.label_26.clear() self.label_28.setText("VID: " + self.text_ex['VID']) self.label_27.setText(self.text_ex['Adhaar no']) def vid(self): if self.ui.checkBox_15.isChecked() == True: if (self.text_ex['VID'] != None): self.label_23.setText("VID: " + self.text_ex['VID']) self.label_28.setText("VID: " + self.text_ex['VID']) # self.label_23.setAlignment(Qt.AlignCenter) # self.label_28.setAlignment(Qt.AlignCenter) else: self.label_23.clear() self.label_28.clear() def frontpageheadermargin(self): if self.ui.checkBox_2.isChecked() == True: pixmap = QPixmap(r'D:\finalapp\images\redline.jpeg') self.label_16.setPixmap(pixmap) self.label_16.setScaledContents(True) else: self.label_16.clear() def RearPageFooterMargin(self): if self.ui.checkBox_5.isChecked() == True: pixmap = QPixmap(r'D:\finalapp\images\redline.jpeg') self.label_18.setPixmap(pixmap) self.label_18.setScaledContents(True) else: self.label_18.clear() def rearpageheader(self): if self.ui.checkBox_4.isChecked() == True: self.nextpagetop() else: pixmap = QPixmap(None) self.label_17.setPixmap(pixmap) self.label_17.setScaledContents(True) def nextpagetop(self): pixmap = QPixmap('images/Aadhar Back Side Top.jpg') self.label_17.setPixmap(pixmap) self.label_17.setScaledContents(True) def defaultfooter(self): pixmap1 = QPixmap('images/footertext/hinditext.jpg') self.label_15.setPixmap(pixmap1) self.label_15.setScaledContents(True) # self.label_15.adjustSize() def hindifooter(self): if self.ui.checkBox_16.isChecked() == True: pixmap1 = QPixmap('images/footertext/hinditext.jpg') self.label_15.setPixmap(pixmap1) self.label_15.setScaledContents(True) else: pixmap = QPixmap(None) self.label_15.setPixmap(pixmap) self.label_15.setScaledContents(True) def Tamilfooter(self): if self.ui.checkBox_17.isChecked() == True: pixmap1 = QPixmap('images/footertext/Tamiltext.png') self.label_15.setPixmap(pixmap1) self.label_15.setScaledContents(True) else: pixmap = QPixmap(None) self.label_15.setPixmap(pixmap) self.label_15.setScaledContents(True) def Marathifooter(self): if self.ui.checkBox_19.isChecked() == True: pixmap1 = QPixmap('images/footertext/Marathitext.png') self.label_15.setPixmap(pixmap1) self.label_15.setScaledContents(True) else: pixmap = QPixmap(None) self.label_15.setPixmap(pixmap) self.label_15.setScaledContents(True) def Punjabifooter(self): if self.ui.checkBox_18.isChecked() == True: pixmap1 = QPixmap('images/footertext/Punjabitext.png') self.label_15.setPixmap(pixmap1) self.label_15.setScaledContents(True) else: pixmap = QPixmap(None) self.label_15.setPixmap(pixmap) self.label_15.setScaledContents(True) def FrontPageFooter(self): if self.ui.checkBox_3.isChecked() == True: if self.ui.checkBox_16.isChecked(): self.hindifooter() elif self.ui.checkBox_17.isChecked(): self.Tamilfooter() elif self.ui.checkBox_19.isChecked(): self.Marathifooter() else: pixmap = QPixmap(None) self.label_15.setPixmap(pixmap) self.label_15.setScaledContents(True) else: pixmap = QPixmap(None) self.label_15.setPixmap(pixmap) self.label_15.setScaledContents(True) def put_dd(self): filename = os.path.join(self.path, "img01.png") fnt = ImageFont.truetype('arial.ttf', 37) # create new image a = self.text_ex["Downloaddate"] image = Image.new(mode="RGB", size=(440, 100), color="white") draw = ImageDraw.Draw(image) draw.text((18, 18), a, font=fnt, fill=(0, 0, 0)) image.save(filename) # os.system(filename) angle = 90 # What angle would you like to rotate self.pixmap = QPixmap(filename) # image for your label pixmap_rotated = self.pixmap.transformed( QTransform().rotate(angle), QtCore.Qt.SmoothTransformation) self.label_31.setPixmap( pixmap_rotated) # set rotated pixmap into your QLabel self.label_31.setScaledContents(True) self.label_31.setAlignment(Qt.AlignCenter) self.label_31.setStyleSheet("QLabel {background-color: white;}") def put_id(self): filename = os.path.join(self.path, "img02.png") fnt = ImageFont.truetype('arial.ttf', 37) # create new image image = Image.new(mode="RGB", size=(440, 100), color="white") draw = ImageDraw.Draw(image) a = self.text_ex["Issuedate"] draw.text((0, 0), a, font=fnt, fill=(0, 0, 0)) image.save(filename) # os.system(filename) angle = 270 + 180 # What angle would you like to rotate self.pixmap = QPixmap(filename) # image for your label pixmap_rotated = self.pixmap.transformed( QTransform().rotate(angle), QtCore.Qt.SmoothTransformation) self.label_32.setPixmap( pixmap_rotated) # set rotated pixmap into your QLabel self.label_32.setScaledContents(True) self.label_32.setAlignment(Qt.AlignCenter) def dd(self): if self.ui.checkBox_11.isChecked() == True: self.put_dd() else: pixmap = QPixmap(None) self.label_31.setPixmap(pixmap) self.label_31.setScaledContents(True) def id(self): if self.ui.checkBox_12.isChecked() == True: self.put_id() else: pixmap = QPixmap(None) self.label_32.setPixmap(pixmap) self.label_32.setScaledContents(True) def uid(self): if self.ui.checkBox_8.isChecked() == True: self.put_uid() else: pixmap = QPixmap(None) self.label_26.setPixmap(pixmap) self.label_26.setScaledContents(True) def open_settings(self): self.window = QtWidgets.QMainWindow() self.ui = Ui_MainWindow1() self.ui.setup(self.window) self.ui.checkBox_15.setChecked(True) self.ui.checkBox_15.toggled.connect(self.vid) self.ui.checkBox_14.toggled.connect(self.phnno) self.ui.checkBox_7.toggled.connect(self.barcode) self.ui.checkBox_2.setChecked(True) self.ui.checkBox_2.toggled.connect(self.frontpageheadermargin) self.ui.checkBox_5.setChecked(True) self.ui.checkBox_5.toggled.connect(self.RearPageFooterMargin) self.ui.checkBox.setChecked(True) self.ui.checkBox.toggled.connect(self.frontpageheader) self.ui.checkBox_6.setChecked(True) self.ui.checkBox_6.toggled.connect(self.rearpagefooter) # self.ui.checkBox_10.setChecked(True) self.ui.checkBox_10.toggled.connect(self.photoframe) self.ui.checkBox_4.setChecked(True) self.ui.checkBox_4.toggled.connect(self.rearpageheader) self.ui.checkBox_16.setChecked(True) self.ui.checkBox_16.toggled.connect(self.hindifooter) self.ui.checkBox_17.toggled.connect(self.Tamilfooter) self.ui.checkBox_18.toggled.connect(self.Punjabifooter) self.ui.checkBox_19.toggled.connect(self.Marathifooter) self.ui.checkBox_3.setChecked(True) self.ui.checkBox_3.toggled.connect(self.FrontPageFooter) self.ui.checkBox_11.toggled.connect(self.dd) self.ui.checkBox_12.toggled.connect(self.id) self.ui.checkBox_8.toggled.connect(self.uid) self.window.show() def resizeimage(self): self.Resize = QtWidgets.QMainWindow() self.ui2 = Ui_MainWindow9() self.ui2.setupUi(self.Resize) self.ui2.horizontalSlider_11.valueChanged[int].connect(self.height) self.ui2.horizontalSlider_10.valueChanged[int].connect(self.Width) self.ui2.horizontalSlider_9.valueChanged[int].connect(self.side) self.Resize.show() def side(self, value): w = self.ui2.horizontalSlider_9.value() self.label_25.resize(w, w) def height(self, value): w = self.ui2.horizontalSlider_10.value() self.label_9.resize(w, value) def Width(self, value): h = self.ui2.horizontalSlider_11.value() self.label_9.resize(value, h)
class IconEditor(QWidget): def __init__(self): super(IconEditor, self).__init__() self.setAttribute(Qt.WA_StaticContents) self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.curColor = Qt.black self.zoom = 8 * 1 self.image = QImage(16, 16, QImage.Format_ARGB32) self.image.fill(qRgba(0, 0, 0, 0)) def penColor(self): return self.curColor def setPenColor(self, newColor): self.curColor = newColor def zoomFactor(self): return self.zoom def setZoomFactor(self, newZoom): if newZoom < 1: newZoom = 1 if newZoom != self.zoom: self.zoom = newZoom self.update() self.updateGeometry() def iconImage(self): return self.image def setIconImage(self, newImage): if newImage != self.image: print('updating image') self.image = newImage.convertToFormat(QImage.Format_ARGB32) self.update() self.updateGeometry() def sizeHint(self): size = self.zoom * self.image.size() if self.zoom >= 3: size += QSize(1, 1) return size def pixelRect(self, i, j): if self.zoom >= 3: return QRect(self.zoom * i + 1, self.zoom * j + 1, self.zoom - 1, self.zoom - 1) else: return QRect(self.zoom * i, self.zoom * j, self.zoom, self.zoom) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.setImagePixel(event.pos(), True) print('mouse left press') elif event.button() == Qt.RightButton: self.setImagePixel(event.pos(), False) print('mouse right press') def mouseMoveEvent(self, event): if event.buttons() & Qt.LeftButton: self.setImagePixel(event.pos(), True) elif event.buttons() & Qt.RightButton: self.setImagePixel(event.pos(), False) def setImagePixel(self, pos, opaque): i = pos.x() // self.zoom j = pos.y() // self.zoom print(f'setting pixel ({i}, {j})') if self.image.rect().contains(i, j): if opaque: penC = QColor('black') self.image.setPixel(i, j, penC.rgba()) # self.image.setPixel(i, j, QColor(255, i*2.56, j*2.56, 255).rgb()) else: print('#' * 10) self.image.setPixel(QPoint(i, j), qRgba(0, 0, 0, 0)) print(f'Pixel Rect: {self.pixelRect(i,j)}') self.update(self.pixelRect(i, j)) def paintEvent(self, event): painter = QPainter(self) if self.zoom >= 3: painter.setPen(self.palette().foreground().color()) # painter.setPen(QPen('red')) for i in range(0, self.image.width()): painter.drawLine(self.zoom * i, 0, self.zoom * i, self.zoom * self.image.height()) for j in range(0, self.image.height()): painter.drawLine(0, self.zoom * j, self.zoom * self.image.width(), self.zoom * j) for i in range(0, self.image.width()): for j in range(0, self.image.height()): rect = self.pixelRect(i, j) if event.region().intersected(rect): color = QColor.fromRgba(self.image.pixel(i, j)) if color.alpha() < 255: painter.fillRect(rect, Qt.white) painter.fillRect(rect, color) penColorProperty = property(QColor, penColor, setPenColor) iconImageProperty = property(QImage, iconImage, setIconImage) zoomFactorProperty = property(int, zoomFactor, setZoomFactor)
def mouseEvent(widget, event, qp=qp, window=window): # TODO split into 3 handlers """ Mouse event handler. The handler implements mouse actions on a vImage in a QLabel. It handles image positioning, zooming, and tool actions. It must be called by the mousePressed, mouseMoved and mouseReleased methods of the QLabel. This can be done by subclassing (not directly compatible with Qt Designer) or by dynamically assigning mouseEvent to the former three methods (cf. the function set_event_handler below). NOTE 1. Mouse hover generates mouse move events NOTE 2. Due to wheeelEvent, xOffset and yOffset are float numbers @param widget: @type widget: QLabel object with img attribute of type mImage @param event: mouse event @type event: QMouseEvent @param window: @type window: QMainWidget """ global pressed, clicked if type(event) == QContextMenuEvent: return # get image and active layer img = widget.img layer = img.getActiveLayer() r = img.resize_coeff(widget) # x, y coordinates (relative to widget) x, y = event.x(), event.y() modifiers = event.modifiers() # app.keyboardModifiers() eventType = event.type() ################### # mouse press event ################### if eventType == QEvent.MouseButtonPress: # Mouse hover generates mouse move events, # so, we set pressed to select only non hovering events pressed = True if event.button() == Qt.LeftButton: # no move yet clicked = True State['ix'], State['iy'] = x, y State['ix_begin'], State['iy_begin'] = x, y State['x_imagePrecPos'], State['y_imagePrecPos'] = (x - img.xOffset) // r, (y - img.yOffset) // r # add current mask to history if window.btnValues['drawFG'] or window.btnValues['drawBG']: if layer.maskIsEnabled: layer.historyListMask.addItem(layer.mask.copy()) # dragBtn or arrow elif modifiers == Qt.ControlModifier | Qt.AltModifier: if layer.isCloningLayer(): layer.updateCloningMask() layer.updateSourcePixmap() return ################## # mouse move event ################## elif eventType == QEvent.MouseMove: # hover event if not pressed: x_img, y_img = (x - img.xOffset) / r, (y - img.yOffset) / r # read input and current colors from active layer (coordinates are relative to the full-sized image) clr = img.getActivePixel(x_img, y_img, qcolor=True) clrC = img.getActivePixel(x_img, y_img, fromInputImg=False, qcolor=True) window.infoView.setText(clr, clrC) return clicked = False if img.isMouseSelectable: # don't draw on a non visible layer if window.btnValues['rectangle'] or window.btnValues['drawFG'] or window.btnValues['drawBG']: if not layer.visible: dlgWarn('Select a visible layer for drawing or painting') pressed = False return elif not window.btnValues['rectangle'] and not layer.maskIsEnabled: dlgWarn('Enable the mask before painting') pressed = False return # marquee tool if window.btnValues['rectangle']: # rectangle coordinates are relative to full image x_img = (min(State['ix_begin'], x) - img.xOffset) // r y_img = (min(State['iy_begin'], y) - img.yOffset) // r w = abs(State['ix_begin'] - x) // r h = abs(State['iy_begin'] - y) // r layer.rect = QRect(x_img, y_img, w, h) # drawing tools elif window.btnValues['drawFG'] or window.btnValues['drawBG']: if layer.maskIsEnabled: toolOpacity = window.verticalSlider2.value() / 100 if modifiers == Qt.NoModifier: if layer.isSegmentLayer(): color = vImage.defaultColor_UnMasked_SM if \ window.btnValues['drawFG'] else vImage.defaultColor_Masked_SM else: color = vImage.defaultColor_UnMasked if \ window.btnValues['drawFG'] else vImage.defaultColor_Masked else: color = vImage.defaultColor_UnMasked_Invalid qp.begin(layer.mask) # get pen width (relative to image) w_pen = window.verticalSlider1.value() // r # mode source : result is source (=pen) pixel color and opacity qp.setCompositionMode(qp.CompositionMode_Source) tmp_x = (x - img.xOffset) // r tmp_y = (y - img.yOffset) // r qp.setPen(QPen(color, w_pen)) qp.setOpacity(toolOpacity) # paint the brush tips spaced by 0.25 * w_pen # use 1-norm for performance a_x, a_y = tmp_x - State['x_imagePrecPos'], tmp_y - State['y_imagePrecPos'] d = abs(a_x) + abs(a_y) x, y = State['x_imagePrecPos'], State['y_imagePrecPos'] radius = w_pen / 2 if d == 0: qp.drawEllipse(QPointF(x, y), radius, radius) # center, radius : QPointF mandatory, else bounding rect topleft and size else: step = w_pen * 0.25 / d for i in range(int(1 / step) + 1): qp.drawEllipse(QPointF(x, y), radius, radius) # center, radius : QPointF mandatory, else bounding rect topleft and size x, y = x + a_x * step, y + a_y * step qp.end() State['x_imagePrecPos'], State['y_imagePrecPos'] = tmp_x, tmp_y ############################ # update upper stack # should be layer.applyToStack() if any upper layer visible : too slow layer.updatePixmap() # maskOnly=True not used: removed ############################# img.prLayer.applyNone() window.label.repaint() # dragBtn or arrow else: # drag image if modifiers == Qt.NoModifier: img.xOffset += x - State['ix'] img.yOffset += y - State['iy'] if window.btnValues['Crop_Button']: window.cropTool.drawCropTool(img) # drag active layer only elif modifiers == Qt.ControlModifier: layer.xOffset += (x - State['ix']) layer.yOffset += (y - State['iy']) layer.updatePixmap() img.prLayer.applyNone() # drag cloning virtual layer elif modifiers == Qt.ControlModifier | Qt.AltModifier: if layer.isCloningLayer(): layer.xAltOffset += (x - State['ix']) layer.yAltOffset += (y - State['iy']) layer.vlChanged = True if layer.maskIsSelected or not layer.maskIsEnabled: layer.setMaskEnabled(color=False) layer.applyCloning(seamless=False, showTranslated=True, moving=True) # not mouse selectable widget : probably before window alone ! else: if modifiers == Qt.NoModifier: img.xOffset += (x - State['ix']) img.yOffset += (y - State['iy']) elif modifiers == Qt.ControlModifier: layer.xOffset += (x - State['ix']) layer.yOffset += (y - State['iy']) layer.updatePixmap() # update current coordinates State['ix'], State['iy'] = x, y if layer.isGeomLayer(): layer.tool.moveRotatingTool() ##################### # mouse release event # mouse click event #################### elif eventType == QEvent.MouseButtonRelease: pressed = False if event.button() == Qt.LeftButton: if layer.maskIsEnabled \ and layer.getUpperVisibleStackIndex() != -1\ and (window.btnValues['drawFG'] or window.btnValues['drawBG']): layer.applyToStack() if img.isMouseSelectable: # click event if clicked: x_img, y_img = (x - img.xOffset) / r, (y - img.yOffset) / r # read input and current colors from active layer (coordinates are relative to the full-sized image) clr = img.getActivePixel(x_img, y_img, qcolor=True) clrC = img.getActivePixel(x_img, y_img, fromInputImg=False, qcolor=True) red, green, blue = clr.red(), clr.green(), clr.blue() # read color from presentation layer redP, greenP, blueP = img.getPrPixel(x_img, y_img) # color chooser : when visible the colorPicked signal is not emitted if getattr(window, 'colorChooser', None) and window.colorChooser.isVisible(): if (modifiers & Qt.ControlModifier) and (modifiers & Qt.ShiftModifier): window.colorChooser.setCurrentColor(clr) elif modifiers & Qt.ControlModifier: window.colorChooser.setCurrentColor(clrC) else: window.colorChooser.setCurrentColor(QColor(redP, greenP, blueP)) else: # emit colorPicked signal layer.colorPicked.sig.emit(x_img, y_img, modifiers) # select grid node for 3DLUT form if layer.is3DLUTLayer(): layer.getGraphicsForm().selectGridNode(red, green, blue) # rectangle selection if window.btnValues['rectangle'] and (modifiers == Qt.ControlModifier): layer.rect = None layer.selectionChanged.sig.emit() # for raw layer, set multipliers to get selected pixel as White Point : NOT USED YET if layer.isRawLayer() and window.btnValues['colorPicker']: # get demosaic buffer and sample raw pixels bufRaw = layer.parentImage.demosaic nb = QRect(x_img-2, y_img-2, 4, 4) r = QImage.rect(layer.parentImage).intersected(nb) if not r.isEmpty(): color = np.sum(bufRaw[r.top():r.bottom()+1, r.left():r.right()+1], axis=(0, 1))/(r.width()*r.height()) else: color = bufRaw[y_img, x_img, :] color = [color[i] - layer.parentImage.rawImage.black_level_per_channel[i] for i in range(3)] form = layer.getGraphicsForm() if form.sampleMultipliers: row, col = 3*y_img//layer.height(), 3*x_img//layer.width() if form.samples: form.setRawMultipliers(*form.samples[3*row + col], sampling=False) else: form.setRawMultipliers(1/color[0], 1/color[1], 1/color[2], sampling=True) else: # not clicked if window.btnValues['rectangle']: layer.selectionChanged.sig.emit() # cloning layer elif layer.isCloningLayer(): if layer.vlChanged: # the virtual layer was moved : clone layer.applyCloning(seamless=True, showTranslated=True, moving=True) layer.vlChanged = False # updates widget.repaint() # sync split views linked = True if widget.objectName() == 'label_2': splittedWin.syncSplittedView(window.label_3, window.label_2, linked) window.label_3.repaint() elif widget.objectName() == 'label_3': splittedWin.syncSplittedView(window.label_2, window.label_3, linked) window.label_2.repaint()
def paintEvent(widg, e, qp=qp): """ Paint event handler. It displays the presentation layer of a vImage object in a Qlabel, with current offset and zooming coefficient. The widget must have a valid img attribute of type vImage. The handler should be used to override the paintEvent method of widg. This can be done by subclassing (not directly compatible with Qt Designer) or by assigning paintEvent to the method widg.paintEvent (cf. the function set_event_handler below). @param widg: widget @type widg: QLabel with a img attribute of type vImage @param e: paint event @type e: @param qp: @type qp: QPainter """ mimg = getattr(widg, 'img', None) if mimg is None: return r = mimg.resize_coeff(widg) qp.begin(widg) # smooth painting qp.setRenderHint(QPainter.SmoothPixmapTransform) # may be useless # fill background qp.fillRect(QRect(0, 0, widg.width(), widg.height()), vImage.defaultBgColor) # draw the presentation layer. # As offsets can be float numbers, we use QRectF instead of QRect # r is relative to the full resolution image, so we use mimg width and height w, h = mimg.width() * r, mimg.height() * r rectF = QRectF(mimg.xOffset, mimg.yOffset, w, h) px = mimg.prLayer.qPixmap if px is not None: qp.drawPixmap(rectF, px, px.rect()) else: currentImage = mimg.prLayer.getCurrentImage() qp.drawImage(rectF, currentImage, QImage.rect(currentImage)) # CAUTION : vImage.rect() is overwritten by attribute rect # draw the selection rectangle of the active layer, if any layer = mimg.getActiveLayer() rect = layer.rect if layer.visible and rect is not None: qp.setPen(QColor(0, 255, 0)) qp.drawRect(rect.left()*r + mimg.xOffset, rect.top()*r + mimg.yOffset, rect.width()*r, rect.height()*r) # draw the cropping marks lm, rm, tm, bm = 0, 0, 0, 0 if mimg.isCropped: c = QColor(128, 128, 128, 192) lm = window.cropTool.btnDict['left'].margin*r rm = window.cropTool.btnDict['right'].margin*r tm = window.cropTool.btnDict['top'].margin*r bm = window.cropTool.btnDict['bottom'].margin*r # left qp.fillRect(QRectF(mimg.xOffset, mimg.yOffset, lm, h), c) # top qp.fillRect(QRectF(mimg.xOffset+lm, mimg.yOffset, w - lm, tm), c) # right qp.fillRect(QRectF(mimg.xOffset+w-rm, mimg.yOffset+tm, rm, h-tm), c) # bottom qp.fillRect(QRectF(mimg.xOffset+lm, mimg.yOffset+h-bm, w-lm-rm, bm), c) # draw rulers if mimg.isRuled: deltaX, deltaY = (w-lm-rm)//3, (h-tm-bm)//3 qp.drawLine(lm+mimg.xOffset, deltaY+tm+mimg.yOffset, w-rm+mimg.xOffset, deltaY+tm+mimg.yOffset) qp.drawLine(lm+mimg.xOffset, 2*deltaY+tm+mimg.yOffset, w-rm+mimg.xOffset, 2*deltaY+tm+mimg.yOffset) qp.drawLine(deltaX+lm+mimg.xOffset, tm+mimg.yOffset, deltaX+lm+mimg.xOffset, h-bm+mimg.yOffset) qp.drawLine(2*deltaX+lm+mimg.xOffset, tm+mimg.yOffset, 2*deltaX+lm+mimg.xOffset, h-bm+mimg.yOffset) # tag before/after views name = widg.objectName() if name == "label_2" or name == "label_3": # draw filled rect qp.fillPath(qp.markPath, QBrush(Qt.gray)) # draw text qp.setPen(Qt.white) qp.setFont(qp.font) qp.drawText(qp.markRect, Qt.AlignCenter | Qt.AlignVCenter, "Before" if name == "label_2" else "After") qp.end()