matplotlib 更改现有 skimage 图上的线宽

matplotlib change line width on existing skimage plot

我正在使用封装在 skimage 中的绘图函数来绘制两组关键点之间的匹配。特别是,我正在使用这个函数:plot_matches

这很好用,但是绘制的线条很粗。我知道使用 matplotlib 可以使用绘图中的 linewidth 参数控制线条粗细。在这种情况下,绘图函数由 link.

中的 plot_matches 函数调用

顺便说一句,我是这样使用的:

import matplotlib.pyplot as plt
from skimage.feature import plot_matches

fig, ax = plt.subplots()
plt.gray()
plot_matches(ax, img1, img2, k1[:, [0, 1]],
             k2[:, [0, 1]], matches, only_matches=True)
ax.axis('off')
plt.show()

这种用法有没有办法控制线宽属性?

不幸的是,plot_matches 只是 hardcodes 根据其内部设置的绘图参数,没有进一步的关键字参数被传递到 matplotlib 函数。

您可以选择在调用该函数之前使用 rcParams 更改标准线宽。

plt.rcParams["lines.linewidth"] = 3
plot_matches(...)

可能您需要在绘图后将其设置回默认值 (1.5),以便能够在要生成的更多绘图中使用该标准。

另一种可能的解决方案是获取 line2D 对象的列表,然后使用 set_linewidth()

更改线宽
lines = ax.lines
for line in lines:

    line.set_linewidth(2)

plot_matches 的问题在于,它可以根据输入在轴上创建许多可能的艺术家,因此新对象没有 return 值那么多绘图功能可以。您可以扩展@DavidG 的回答以检查您调用 plot_matches 时专门添加了哪些行。这会使您的代码稍微复杂一些,但可能值得付出努力,具体取决于您的需要:

import matplotlib.pyplot as plt
from skimage.feature import plot_matches

def my_plot_matches(ax, *args, line_options={}, **kwargs):
    nlines = len(ax.lines)
    plot_matches(ax, *args, **kwargs)
    new_lines = ax.lines[nlines:]
    if new_lines and line_options:
        plt.setp(new_lines, **line_options)

fig, ax = plt.subplots()
plt.gray()
my_plot_matches(ax, img1, img2, k1[:, [0, 1]], k2[:, [0, 1]], matches, only_matches=True, line_options={'linewidth': 2})
ax.axis('off')
plt.show()

这个版本依赖于这样一个事实,即 plot_matches 在轴上绘制的任何内容都会附加到线对象的内部列表中。我假设 plot_matches 之前不在列表中的任何内容都在列表末尾,需要修改。