Matplotlib中选择已绘制图像及将带填充区绘图转灰度图并存为变量的方法
解决方法:将Matplotlib绘图转为灰度图并保存为变量,以及选择已绘制元素
一、将完整绘图转为灰度图并保存为变量
以下是修改后的代码,直接实现渲染完整绘图、转灰度并保存为变量的需求:
import matplotlib.pyplot as plt import skimage.io import numpy as np from skimage.color import rgb2gray # 读取原始图像 image = skimage.io.imread("anaconda2/Videos/(4F) 2008-05-22 10.30.59 HOOSH/2008-05-22 10.30.59 HOOSH0010.png") fig, ax = plt.subplots() ax.imshow(image) ax.set_ylim(ymin=720, ymax=0) ax.set_xlim(xmin=0, xmax=1280) ax.plot(x2,y,'r-',x3,y,'r-',x4,y,'r-',x5,y,'r-',x6,y,'r-',x7,y,'r-',x8,y,'r-',x9,y,'r-',x10,y,'r-',x11,y,'r-',) ax.fill_betweenx(y,x2,x3,color='yellow') # 强制渲染画布上所有元素(包括原图、线条、填充区) fig.canvas.draw() # 将画布内容转为RGB格式的numpy数组 rgb_data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) rgb_data = rgb_data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) # 转换为灰度图 # 方式1:用skimage的工具函数 gray_image = rgb2gray(rgb_data) # 方式2:手动用灰度转换公式(无需skimage) # gray_image = 0.2989 * rgb_data[:,:,0] + 0.5870 * rgb_data[:,:,1] + 0.1140 * rgb_data[:,:,2] # 若需要0-255的8位整数格式(部分场景需要) gray_image_8bit = (gray_image * 255).astype(np.uint8) # 现在gray_image或gray_image_8bit就是可用于后续函数的灰度图变量 plt.close(fig) # 关闭画布释放内存
关键说明:
fig.canvas.draw()必须调用,确保所有绘制元素(包括线条、填充区)都被渲染- 转换后的灰度图变量可以直接传入其他处理函数,无需保存为本地文件
二、在Matplotlib中选择已绘制的图像元素
如果要定位imshow()绘制的原始图像,可以通过轴对象的子元素筛选:
# 获取当前轴上的所有绘制元素 all_elements = ax.get_children() # 筛选出imshow创建的AxesImage对象 target_image = None for elem in all_elements: if isinstance(elem, plt.AxesImage): target_image = elem break # 获取该图像的原始像素数据 if target_image: original_image_data = target_image.get_array()
说明:
ax.get_children()返回轴上所有元素,包括图像、线条、刻度、填充区域等plt.AxesImage是imshow()专属的对象类型,筛选后即可获取对应图像的属性和数据
内容的提问来源于stack exchange,提问作者Danero22
相关产品推荐
相关产品推荐

