1 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
可以通過多種方式將圖形轉(zhuǎn)換為 RGBA 數(shù)組。最簡單的可能是將文件另存為 PNG,然后使用plt.imread
或類似的方式再次加載文件。如果這對你來說似乎是迂回的,你可以使用plot2img
我在下面使用的,它抓取畫布并通過中間表示將其轉(zhuǎn)換為數(shù)組作為字符串緩沖區(qū)。
之后,只需對圖像進(jìn)行閾值化并提取中軸,使用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()
添加回答
舉報(bào)