pythonimageopencvpyqt5qpixmap

Display an image in a label without saving it


The following lines are in my script:

    from PyQt5 import QtGui, QtWidgets, QtCore
    from PyQt5.QtGui import QIcon, QPixmap
    from PyQt5.Widgets import *
    import cv2

imgCross = positioningCross(Dy, Dx, center, imgCross)
cv2.imwrite("img.png", imgCross)
self.ImgLabel.setPixmap(QPixmap("img.png"))

def positioningCross(Dy, Dx, center, imgCross): if(center[1,0]>=center[0,0]): Dy2 = center[0,0] + np.absolute(Dy) else: Dy2 = center[1,0] + np.absolute(Dy)

if(center[0,1]>=center[1,1]): Dx2 = center[1,1] + np.absolute(Dx)/2 else: Dx2 = center[0,1] + np.absolute(Dx)/2 P1 = (center[0,1]/2,center[0,0]/2) P2 = (center[1,1]/2,center[1,0]/2) P3 = (Dx2/2,Dy2/2+100) P4 = (Dx2/2,Dy2/2-100) cv2.line(imgCross,(int(P1[0]),int(P1[1])),(int(P2[0]),int(P2[1])),(0,0,255),1) cv2.line(imgCross,(int(P3[0]),int(P3[1])),(int(P4[0]),int(P4[1])),(0,0,255),1) imgCross= cv2.flip(imgCross,1) return imgCross

I want to paint two lines with positioningCross into imgCross and display it in a label of my GUI. At the moment, I'm saving the modified image in a folder, but I want to know if it is possible to add it to the Label without saving it?

My solution is ok, but I guess it could be better

Has anyone an idea?


Solution

  • Your code is a bit incomplete, but the following should show you how to do what you want.

    import sys
    from PyQt5 import QtGui, QtWidgets, QtCore
    from PyQt5.QtGui import QIcon, QPixmap
    from PyQt5.QtWidgets import *
    
    app = QApplication(sys.argv)
    label = QLabel()
    pixmap = QPixmap(32, 32)
    painter = QtGui.QPainter(pixmap)
    # Now draw whatever you like on the pixmap..no need to save to file
    painter.setPen(QtCore.Qt.red)
    painter.setBrush(QtGui.QBrush(QtCore.Qt.white))
    rect = QtCore.QRect(0, 0, 31, 31)
    painter.drawRect(rect)
    painter.drawText(rect, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter, "foo")
    painter.end()
    label.setPixmap(pixmap)
    
    label.show()
    
    sys.exit(app.exec_())