QT将灰色图像绘制为伪彩色(PyQt)



目前,我有一个图像(numpy(,我想用颜色在QLabel中绘制它。

可以找到类似的演示:https://matplotlib.org/users/image_tutorial.html。matplotlib 可以使用带有颜色图的 imshow 来显示图像。

现在,我可以在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_())

我有一个解决方案可以在伪图像中显示灰色图像。

首先,我使用 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_())

最新更新