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

OLED显示屏图像缩放异常及AssertionError问题求助

解决OLED显示屏图像适配问题

首先,咱们先搞清楚那个AssertionError的原因:luma.oled库的device.display()方法要求传入的图像尺寸必须和设备的尺寸完全一致。你的OLED是128x128的,所以当你把图像改成64x64时,尺寸不匹配就触发了断言错误,这是库的保护机制,避免显示异常。

再看你现有代码的问题:你先调用了.transform(device.size, ...)把图像转换成设备尺寸,之后又做了一次resize((128,128)),这属于重复操作;而且之前的transform参数(仿射变换矩阵是(1,0,0,0,1,0))其实只是做了无变化的转换,根本没起到缩放或适配的作用,这也是为什么你之前调整大小后还是只显示部分图像的原因。

下面给你两种可行的解决方案,根据你的需求选择:

方案1:直接拉伸图像适配屏幕(简单快捷,不在乎比例变形)

这种方式会把原图直接拉伸到屏幕尺寸,代码最简洁:

#!/usr/bin/env python
import math
import time
import random
import os.path
from demo_opts import get_device
from luma.core.render import canvas
from PIL import Image

def main():
    img_path = os.path.abspath(os.path.join(
        os.path.dirname(__file__), 'plot.jpg'))
    img = Image.open(img_path)
    
    # 直接将图像调整为设备尺寸,同时转换为设备支持的颜色模式
    new_img = img.resize(device.size, Image.Resampling.LANCZOS).convert(device.mode)
    
    while True:
        device.display(new_img)
        time.sleep(5)

if __name__ == "__main__":
    try:
        device = get_device()
        main()
    except KeyboardInterrupt:
        pass

这里用device.size代替硬写的(128,128),代码更通用,以后换不同尺寸的OLED也不用改数值;Image.Resampling.LANCZOS是PIL推荐的高质量缩放算法,能让缩放后的图像更清晰。

方案2:保持图像比例,居中显示(避免拉伸变形)

如果不想让图像变形,可以先把图像按比例缩小到屏幕能容纳的最大尺寸,然后在屏幕居中显示,剩下的区域可以填充背景色(比如黑色):

#!/usr/bin/env python
import math
import time
import random
import os.path
from demo_opts import get_device
from luma.core.render import canvas
from PIL import Image, ImageOps

def main():
    img_path = os.path.abspath(os.path.join(
        os.path.dirname(__file__), 'plot.jpg'))
    img = Image.open(img_path)
    
    # 计算图像按比例缩放后的尺寸,确保不超过屏幕大小
    img.thumbnail(device.size, Image.Resampling.LANCZOS)
    
    # 创建和屏幕尺寸一致的背景图(这里用黑色,你可以改成其他颜色)
    background = Image.new(device.mode, device.size, "black")
    
    # 计算居中位置
    x = (device.size[0] - img.size[0]) // 2
    y = (device.size[1] - img.size[1]) // 2
    
    # 将缩放后的图像粘贴到背景图的居中位置
    background.paste(img, (x, y))
    
    # 转换为设备支持的模式
    new_img = background.convert(device.mode)
    
    while True:
        device.display(new_img)
        time.sleep(5)

if __name__ == "__main__":
    try:
        device = get_device()
        main()
    except KeyboardInterrupt:
        pass

这样处理后,图像会保持原有比例,不会变形,同时完整显示在屏幕中央。

你可以根据自己的需求选择其中一种方案,替换掉原来的代码,应该就能解决图像只显示一部分或者断言错误的问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:59:03