You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PsychoPy Builder中创建显示图像?结果图像替换难题求助

解决方案

问题1:程序启动时目标图像不存在导致报错

  • 避免在Builder界面预先添加结果图像组件,改用代码组件动态创建图像刺激:
    在用于显示结果的routine中添加代码组件,在Begin Routine段写入:
    import os
    result_img_path = "result_plot.png"
    # 若文件不存在,临时生成空白占位图
    if not os.path.exists(result_img_path):
        from PIL import Image
        blank_img = Image.new('RGB', (800, 600), color='white')
        blank_img.save(result_img_path)
    # 创建图像刺激实例
    result_stim = visual.ImageStim(win, image=result_img_path)
    
    接着在Each Frame段添加绘制代码:
    result_stim.draw()
    
    这种方式只会在进入结果显示环节时才处理图像文件,彻底避开启动阶段的文件检查。

问题2:新生成图像无法替换旧占位图显示

这是因为PsychoPy会缓存已加载的图像资源,即使本地文件更新,程序仍会读取缓存中的旧内容。可通过以下方式解决:

  • 生成新图像后,强制刷新图像刺激的加载源:
    在完成结果图像生成的代码后,调用图像刺激的setImage方法并关闭日志记录(强制跳过缓存检查):
    # 假设已成功生成新的result_plot.png
    result_stim.setImage("result_plot.png", log=False)
    
  • 或直接清除全局图像缓存:
    from psychopy import visual
    visual.cache.ClearCache()
    
    清除缓存后重新创建图像刺激或调用setImage加载新文件即可。

额外技巧:给结果图像添加动态后缀(如被试ID、时间戳),每次生成全新文件名,从根源避免缓存冲突:

import time
# 生成带时间戳的唯一文件名
result_img_path = f"result_plot_{int(time.time())}.png"
# 绘图和显示时均使用该路径

内容的提问来源于stack exchange,提问作者Ashley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:35:05