You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PyQt的QLabel中将numpy灰度图像转为伪彩色显示?

How to Render NumPy Grayscale Images as Pseudocolor in PyQt QLabel

Hey there! You're already halfway there with displaying grayscale images in QLabel—adding pseudocolor just requires a couple extra steps to map your grayscale values to a color palette, similar to how matplotlib's imshow works with colormaps. Here's how to tweak your code to make it happen:

Key Steps to Add Pseudocolor

  • First, normalize your grayscale array to the range [0, 1] (most colormaps expect this input range)
  • Apply a colormap to convert grayscale values to RGB/A color data
  • Convert the resulting color array to a QImage for PyQt to render

Modified Code with Pseudocolor Support

We'll use matplotlib's built-in colormaps (like viridis, jet, etc.) since they're easy to work with, but you could also define a custom colormap if needed. Here's your updated code:

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import numpy as np
import qimage2ndarray
import matplotlib.cm as cm  # Import matplotlib's colormap module

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)
        
        # Step 1: Normalize grayscale image to [0, 1] range
        normalized_img = self.img / self.img.max()  # Handles any value range, not just 0-255
        
        # Step 2: Apply colormap (replace 'viridis' with any matplotlib colormap name)
        colormap = cm.get_cmap('viridis')
        pseudocolor_img = colormap(normalized_img)  # Outputs RGBA array (shape: (256,256,4))
        
        # Step 3: Convert RGBA array to QImage (array2qimage handles color arrays)
        QImg = qimage2ndarray.array2qimage(pseudocolor_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_())

What Changed?

  • Added import matplotlib.cm as cm to access pre-built colormaps
  • Normalization: We scale the grayscale values to [0,1] so the colormap applies correctly (this works even if your image has values outside the 0-255 range)
  • Colormap Application: cm.get_cmap('viridis') loads your chosen palette, and calling it on the normalized array returns an RGBA color array
  • QImage Conversion: Instead of gray2qimage, we use array2qimage since we now have a 4-channel (RGBA) color array

Custom Colormap Option (No Matplotlib Dependency)

If you don't want to rely on matplotlib, you can create a simple colormap manually. For example, a blue-to-red gradient:

def custom_colormap(gray_value):
    # gray_value is normalized to [0,1]
    r = gray_value
    b = 1 - gray_value
    g = 0.0
    return (r, g, b, 1.0)  # RGBA

# Replace the colormap section in paintEvent with:
pseudocolor_img = np.apply_along_axis(custom_colormap, 2, normalized_img[..., np.newaxis])

This will give you a red-blue gradient without needing matplotlib installed.

内容的提问来源于stack exchange,提问作者Qiang Zhang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:16:42