如何用plt.imshow创建含时序光栅与灰色间隔的图像?
问题描述
尝试用plt.imshow创建一幅随时间分布的图像:
- 刺激时段显示黑白光栅条纹,间期显示灰色块
- 已获取时间数组
grating_time,以及刺激起止索引对index_pairs(约40组,对应40次刺激) - 初始尝试绘制刺激区白块、间期黑块未达预期,代码如下:
index_pairs = [list(pair) for pair in zip(starts_of_gratings_clean, ends_of_gratings_clean)] # Parameters image_height = 50 # Initialize the final image total_time = grating_time.to_numpy()[-1] total_width = len(grating_time) image = np.zeros((image_height, total_width), dtype=np.uint8) # Iterate over the index pairs and set white regions for start_idx, end_idx in index_pairs: image[:, start_idx:end_idx] = 255 # Plot the image plt.imshow(image, cmap='gray', aspect='auto', extent=[grating_time.to_numpy()[0], grating_time.to_numpy()[-1], 0, image_height]) plt.xlabel('Time') plt.ylabel('Grating') plt.show()
需求:
- 修复现有代码,实现刺激区白块、间期灰色块
- 进一步将刺激区替换为黑白条纹(例如3白2黑的条纹模式)
解决方案
1. 基础修复:刺激区白块 + 间期灰色块
初始代码的核心问题是将图像初始化为全黑(np.zeros),而需求中间期应为灰色。只需把初始图像设为灰色背景,再将刺激区设为白色即可:
import numpy as np import matplotlib.pyplot as plt # 假设starts_of_gratings_clean、ends_of_gratings_clean、grating_time已提前定义 index_pairs = [list(pair) for pair in zip(starts_of_gratings_clean, ends_of_gratings_clean)] # 参数设置 image_height = 50 gray_value = 128 # 间期的灰度值(0=黑,255=白,128=中灰) # 初始化图像为灰色背景 total_width = len(grating_time) image = np.full((image_height, total_width), gray_value, dtype=np.uint8) # 填充刺激区为白色 for start_idx, end_idx in index_pairs: image[:, start_idx:end_idx] = 255 # 绘图 plt.imshow(image, cmap='gray', aspect='auto', extent=[grating_time[0], grating_time[-1], 0, image_height]) plt.xlabel('Time') plt.ylabel('Grating') plt.show()
2. 进阶实现:刺激区黑白条纹
要生成黑白条纹,先定义条纹模式(比如3行白、2行黑),再将模式重复适配图像高度,最后填充到刺激时段区域:
import numpy as np import matplotlib.pyplot as plt # 假设starts_of_gratings_clean、ends_of_gratings_clean、grating_time已提前定义 index_pairs = [list(pair) for pair in zip(starts_of_gratings_clean, ends_of_gratings_clean)] # 参数设置 image_height = 50 gray_value = 128 # 间期灰度值 # 定义条纹模式:3行白(255)、2行黑(0),循环重复 stripe_pattern = [255]*3 + [0]*2 # 生成适配图像高度的条纹模板(转为列向量方便广播填充) stripe_template = np.tile(stripe_pattern, (image_height // len(stripe_pattern)) + 1)[:image_height].reshape(-1, 1) # 初始化图像为灰色背景 total_width = len(grating_time) image = np.full((image_height, total_width), gray_value, dtype=np.uint8) # 填充刺激区为黑白条纹 for start_idx, end_idx in index_pairs: image[:, start_idx:end_idx] = stripe_template # 绘图 plt.imshow(image, cmap='gray', aspect='auto', extent=[grating_time[0], grating_time[-1], 0, image_height]) plt.xlabel('Time') plt.ylabel('Grating') plt.show()
关键说明:
- 若需要横向条纹(沿时间轴的黑白条),可将条纹模板改为行向量,再填充到对应行范围
- 调整
stripe_pattern的元素数量和值,可自定义条纹的宽度、颜色比例
内容的提问来源于stack exchange,提问作者Panagiotis Eleftheriadis
相关产品推荐
相关产品推荐

