1 回答
TA贡献1805条经验 获得超9个赞
可以通过多种方式将图形转换为 RGBA 数组。最简单的可能是将文件另存为 PNG,然后使用plt.imread
或类似的方式再次加载文件。如果这对你来说似乎是迂回的,你可以使用plot2img
我在下面使用的,它抓取画布并通过中间表示将其转换为数组作为字符串缓冲区。
之后,只需对图像进行阈值化并提取中轴,使用scikit-image
.
#!/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()
添加回答
举报