当试图从URL获取图像时,Micropython MemoryError



嗨,我已经买了显示包2 (https://shop.pimoroni.com/products/pico-display-pack-2-0?variant=39374122582099),并试图显示图像。如果我下载图像并将其放在pi pico w上,那么图像显示正常。我正试图从URL下载并显示图像,但我正在获取

MemoryError:内存分配失败,分配21760字节

我是新的这种编码,我正在努力看到我做错了什么。这是我完整的py代码

import network
import urequests
import time
import picographics
import jpegdec
from pimoroni import Button

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("SSID","password")
time.sleep(5)
print(wlan.isconnected())

display = picographics.PicoGraphics(display=picographics.DISPLAY_PICO_DISPLAY_2, rotate=0)
display.set_backlight(0.8)
# Create a new JPEG decoder for our PicoGraphics
j = jpegdec.JPEG(display)
# Open the JPEG file
#j.open_file("squid.jpg")
# Decode the JPEG
#j.decode(0, 0, jpegdec.JPEG_SCALE_FULL)
if wlan.isconnected():

res = urequests.get(url='https://squirrel365.io/tmp/squid.jpg')

j.open_RAM(memoryview(res.content))
# Decode the JPEG
j.decode(0, 0, jpegdec.JPEG_SCALE_FULL)
# Display the result
display.update()

'什么好主意吗?

小锚

我已经测试过了,可以从URL得到纯文本,只要我试着得到一个图像,我得到内存错误

你没有做错任何事!你只是在使用一个资源非常有限的设备。如果您重新安排代码,以便在初始化任何图形资源之前执行读取,将数据写入文件,然后让jpeg模块从磁盘读取数据,那会怎么样?比如:

import jpegdec
import network
import picographics
import time
import urequests
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("SSID","password")
while not wlan.isconnected():
print('waiting for network')
time.sleep(1)
res = urequests.get(url='https://squirrel365.io/tmp/squid.jpg')
with open('squid.jpg', 'wb') as fd:
fd.write(res.content)
display = picographics.PicoGraphics(display=picographics.DISPLAY_PICO_DISPLAY_2, rotate=0)
display.set_backlight(0.8)
# Create a new JPEG decoder for our PicoGraphics
j = jpegdec.JPEG(display)
# Open the JPEG file
j.open_file("squid.jpg")
# Decode the JPEG
j.decode(0, 0, jpegdec.JPEG_SCALE_FULL)
# Display the result
display.update()

有时可以通过在代码中添加显式垃圾收集来释放额外的内存:

import gc
.
.
.
with open('squid.jpg', 'wb') as fd:
fd.write(res.content)
gc.collect()

最新更新