如何找到通过使用 matplotlib 绘制的图传递的像素

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


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。我应该怎么做?谢谢!


繁星点点滴滴
浏览 66回答 1
1回答

Cats萌萌

可以通过多种方式将图形转换为 RGBA 数组。最简单的可能是将文件另存为 PNG,然后使用plt.imread或类似的方式再次加载文件。如果这对你来说似乎是迂回的,你可以使用plot2img我在下面使用的,它抓取画布并通过中间表示将其转换为数组作为字符串缓冲区。之后,只需对图像进行阈值化并提取中轴,使用scikit-image.#!/usr/bin/env python"""https://stackoverflow.com/q/62014554/2912349"""import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.backends.backend_agg import FigureCanvasAggfrom skimage.color import rgb2grayfrom skimage.filters import threshold_otsufrom skimage.morphology import medial_axisdef plot2img(fig, remove_margins=True):&nbsp; &nbsp; # https://stackoverflow.com/a/35362787/2912349&nbsp; &nbsp; # https://stackoverflow.com/a/54334430/2912349&nbsp; &nbsp; if remove_margins:&nbsp; &nbsp; &nbsp; &nbsp; fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)&nbsp; &nbsp; canvas = FigureCanvasAgg(fig)&nbsp; &nbsp; canvas.draw()&nbsp; &nbsp; img_as_string, (width, height) = canvas.print_to_buffer()&nbsp; &nbsp; return np.fromstring(img_as_string, dtype='uint8').reshape((height, width, 4))if __name__ == '__main__':&nbsp; &nbsp; t = np.arange(0., 5., 0.2)&nbsp; &nbsp; y = (t**2)+10*np.sin(t)&nbsp; &nbsp; # plot in a large figure such that the resulting image has a high resolution&nbsp; &nbsp; fig, ax = plt.subplots(figsize=(20, 20))&nbsp; &nbsp; ax.plot(t, y)&nbsp; &nbsp; ax.axis('off')&nbsp; &nbsp; # convert figure to an RGBA array&nbsp; &nbsp; as_rgba = plot2img(fig)&nbsp; &nbsp; # close plot made with non-interactive Agg backend so that we can open the other later&nbsp; &nbsp; plt.close('all')&nbsp; &nbsp; # threshold the image&nbsp; &nbsp; as_grayscale = rgb2gray(as_rgba)&nbsp; &nbsp; threshold = threshold_otsu(as_grayscale)&nbsp; &nbsp; as_bool = as_grayscale < threshold&nbsp; &nbsp; # find midline&nbsp; &nbsp; midline = medial_axis(as_bool)&nbsp; &nbsp; # plot results&nbsp; &nbsp; fig, (ax1, ax2) = plt.subplots(1, 2)&nbsp; &nbsp; ax1.imshow(as_bool, cmap='gray_r')&nbsp; &nbsp; ax2.imshow(midline, cmap='gray_r')&nbsp; &nbsp; plt.show()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python