目前,我有一个图像(numpy),我想在QLabel中用颜色绘制它。
可以找到类似的演示:https://matplotlib.org/users/image_tutorial.html。 matplotlib可以使用imshow和colormap显示图像。
现在,我可以在QLabel中显示灰色图像,但我不知道如何将其显示为伪色。
用于显示灰色图像的代码是(self.img就是我所拥有的):
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import numpy as np
import qimage2ndarray
class MyLabel(QLabel):
def __init__(self):
super(MyLabel, self).__init__()
img = np.zeros((256,256))
img[0:128,0:128] = 255
self.img = img
def paintEvent(self, QPaintEvent):
super(MyLabel, self).paintEvent(QPaintEvent)
QImg = qimage2ndarray.gray2qimage(self.img)
pos = QPoint(0, 0)
source = QRect(0, 0, 256,256)
painter = QPainter(self)
painter.drawPixmap(pos, QPixmap.fromImage(QImg), source)
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
layout = QHBoxLayout(self)
self.label = MyLabel()
layout.addWidget(self.label)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
答案 0 :(得分:0)
我有一个在伪图像中显示灰色图像的解决方案。
首先,我使用opencv生成伪图像:
disImg = cv2.applyColorMap(img, cv2.COLORMAP_AUTUMN)
然后,将图像转换为QImage:
QImg = QImage(disImg.data, disImg.shape[1], disImg.shape[0], disImg.strides[0], QImage.Format_RGB888)
最后,我们可以通过drawpixmap在QLabel中显示它,整个代码应该是:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import numpy as np
import qimage2ndarray
import matplotlib.pyplot as plt
import cv2
class MyLabel(QLabel):
def __init__(self):
super(MyLabel, self).__init__()
img = np.zeros((256,256),dtype=np.uint8)
img[0:128,0:128] = 255
img[128:255,128:255] = 128
disImg = cv2.applyColorMap(img, cv2.COLORMAP_AUTUMN)
QImg = QImage(disImg.data, disImg.shape[1], disImg.shape[0], disImg.strides[0], QImage.Format_RGB888)
self.qimg = QImg
cv2.imshow('test',disImg)
cv2.waitKey()
def paintEvent(self, QPaintEvent):
super(MyLabel, self).paintEvent(QPaintEvent)
pos = QPoint(0, 0)
source = QRect(0, 0, 256,256)
painter = QPainter(self)
painter.drawPixmap(pos, QPixmap.fromImage(self.qimg), source)
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
layout = QHBoxLayout(self)
self.resize(300,300)
self.label = MyLabel()
layout.addWidget(self.label)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())