PyQtGraph 的 ImageView 小部件包含一个直方图:
这两个功能允许用户编辑/生成颜色查找表(LUT)以对显示的图像进行伪彩色。
默认情况下,颜色渐变设置为黑白,如下所示:
如何将默认渐变设置为默认黑白以外的其他渐变?
最小可重现示例代码
import numpy as np
import pyqtgraph as pg
data = np.array(
[
[0.0, 0.0, 0.5, 2.5, 2.5, 3.5],
[2.0, 2.0, 1.5, 0.5, 2.5, 3.5],
[2.0, 2.0, 2.0, 2.5, 0.5, 1.5],
[3.0, 3.0, 2.5, 3.0, 1.5, 0.5],
[3.0, 3.0, 3.0, 4.5, 1.5, 1.5],
]
)
# Get QApplication instance if it exists, else create new one
app = pg.Qt.mkQApp("Example Cost Matrix Visualisation")
# Create and configure plot
plot = pg.PlotItem()
plot.setTitle("Cost Matrix")
plot.setLabel(axis="top", text="Y Signal")
plot.setLabel(axis="left", text="X Signal")
# Create image item and view
im = pg.ImageItem(data, axisOrder="row-major")
imv = pg.ImageView(imageItem=im, view=plot)
imv.show()
imv.setHistogramLabel("Cost Matrix Histogram")
app.exec()
与
GradientEditorItem
的 HistogramLUTItem
关联的 ImageView
负责定义用于为伪彩色图像创建 LUT 的梯度。
人们可以通过使用 GradientEditorItem
在 0.0 和 1.0 之间的位置通过 RGB 值刻度指定自己的渐变来更改 restoreState
的渐变:
hist_lut_item = image_view.getHistogramWidget().item
hist_lut_item.gradient.restoreState(
{"mode": "rgb", "ticks": [(0.00, (0, 0, 255)), (1.00, (255, 0, 0))]}
)
这会产生以下结果:
或者使用预设(在GradientPresets.py中可以找到有效预设的列表):
hist_lut_item = image_view.getHistogramWidget().item
hist_lut_item.gradient.loadPreset('thermal')
完整代码示例
import numpy as np
import pyqtgraph as pg
data = np.array(
[
[0.0, 0.0, 0.5, 2.5, 2.5, 3.5],
[2.0, 2.0, 1.5, 0.5, 2.5, 3.5],
[2.0, 2.0, 2.0, 2.5, 0.5, 1.5],
[3.0, 3.0, 2.5, 3.0, 1.5, 0.5],
[3.0, 3.0, 3.0, 4.5, 1.5, 1.5],
]
)
# Get QApplication instance if it exists, else create new one
app = pg.Qt.mkQApp("Example Cost Matrix Visualisation")
# Create and configure plot
plot = pg.PlotItem()
plot.setTitle("Cost Matrix")
plot.setLabel(axis="top", text="Y Signal")
plot.setLabel(axis="left", text="X Signal")
# Create image item and view
im = pg.ImageItem(data, axisOrder="row-major")
imv = pg.ImageView(imageItem=im, view=plot)
imv.show()
imv.setHistogramLabel("Cost Matrix Histogram")
# Get HistogramLUTItem
ht = imv.getHistogramWidget().item
# Specify own gradient via RGB valued ticks at locations between 0.0 and 1.0
ht.gradient.restoreState(
{"mode": "rgb", "ticks": [(0.00, (0, 0, 255)), (1.00, (255, 0, 0))]}
)
# # Alternatively, use one of the default presets. See all options here:
# # https://github.com/pyqtgraph/pyqtgraph/blob/master/pyqtgraph/graphicsItems/GradientPresets.py
# ht.gradient.loadPreset("thermal")
app.exec()