python - 如何找到用 matplotlib 绘制的图传递的像素

标签 python image numpy matplotlib pixel

我使用以下代码绘制函数:

t = np.arange(0., 5., 0.2)
plt.plot(t, (t**2)+10*np.sin(t))
plt.axis('off')

我想知道如何将绘图保存为 0/1 数组,其中如果绘图通过,像素值为 1,否则为 0。

后续问题是,如果我用一定的线宽绘制绘图,我希望像素值只有在绘图的“中心”线上时才为 1,否则为 0。我应该怎么做?谢谢!

最佳答案

可以通过多种方式将图形转换为 RGBA 数组。 最简单的可能是将文件另存为 PNG,然后使用 plt.imread 或类似文件再次加载该文件。如果这对您来说似乎很绕行,您可以使用我下面使用的 plot2img,它会抓取 Canvas 并通过中间表示形式将其转换为数组作为字符串缓冲区。

之后,只需对图像进行阈值处理并提取中轴,这可以使用 scikit-image 提供的函数轻松完成。

enter image description here

#!/usr/bin/env python
"""
https://stackoverflow.com/q/62014554/2912349
"""

import numpy as np
import matplotlib.pyplot as plt

from matplotlib.backends.backend_agg import FigureCanvasAgg

from skimage.color import rgb2gray
from skimage.filters import threshold_otsu
from skimage.morphology import medial_axis


def plot2img(fig, remove_margins=True):
    # https://stackoverflow.com/a/35362787/2912349
    # https://stackoverflow.com/a/54334430/2912349

    if remove_margins:
        fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)

    canvas = FigureCanvasAgg(fig)
    canvas.draw()
    img_as_string, (width, height) = canvas.print_to_buffer()
    return np.fromstring(img_as_string, dtype='uint8').reshape((height, width, 4))


if __name__ == '__main__':

    t = np.arange(0., 5., 0.2)
    y = (t**2)+10*np.sin(t)

    # plot in a large figure such that the resulting image has a high resolution
    fig, ax = plt.subplots(figsize=(20, 20))
    ax.plot(t, y)
    ax.axis('off')

    # convert figure to an RGBA array
    as_rgba = plot2img(fig)

    # close plot made with non-interactive Agg backend so that we can open the other later
    plt.close('all')

    # threshold the image
    as_grayscale = rgb2gray(as_rgba)
    threshold = threshold_otsu(as_grayscale)
    as_bool = as_grayscale < threshold

    # find midline
    midline = medial_axis(as_bool)

    # plot results
    fig, (ax1, ax2) = plt.subplots(1, 2)
    ax1.imshow(as_bool, cmap='gray_r')
    ax2.imshow(midline, cmap='gray_r')
    plt.show()

关于python - 如何找到用 matplotlib 绘制的图传递的像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62014554/

相关文章:

python - python 中的函数会更改输入变量,这是为什么?

python - 大型 Numpy Scipy CSR 矩阵,按行操作

java - 仅使用 Java 制作 ImageView 抖动

python - 如何使用Numpy加快Python中OpenCV图像的循环?

python - Flask-WTForm : Flash does not display errors

python - 如何使用 Python 转发电子邮件

html - 相对 img src 被解析为绝对...我错过了什么?

python - 计算图像中白色背景上的蓝调线数

python - 成对相似度/相似度矩阵计算优化

python - NumPy 是否搞乱了 CX_Freeze?