我想制作一个生成器,从 url 生成批量图像来训练keras模型。我有另一个生成器可以为我提供图像 url。
我目前所做的是将图像下载到磁盘,然后从磁盘加载图像。
def loadImage(URL):
with urllib.request.urlopen(URL) as url:
with open('temp.jpg', 'wb') as f:
f.write(url.read())
img_path = 'temp.jpg'
img = image.load_img(img_path, target_size=(125, 125))
os.remove(img_path)
x = image.img_to_array(img)
return x
def imageGenerator(batch_size):
i = 0
batch = []
for URL in imageUrlGenerator():
if i>batch_size:
yield batch
batch = []
i=0
batch.append(loadImage(URL))
i+=1
Run Code Online (Sandbox Code Playgroud)
这有效,但我想知道是否没有更快的方法来从网络加载图像而无需写入和读取磁盘。
目标是拥有一个在 python 3 中运行并读取特定 gmail 帐户上传入电子邮件的应用程序,如何侦听该电子邮件的接收?
它应该做的是等到收件箱收到新邮件,从电子邮件中读取主题和正文,并从正文中获取文本(无格式)。
这是我到目前为止得到的:
import imaplib
import email
import datetime
import time
mail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
mail.login(user, password)
mail.list()
mail.select('inbox')
status, data = mail.search(None, 'ALL')
for num in data[0].split():
status, data = mail.fetch(num, '(RFC822)')
email_msg = data[0][1]
email_msg = email.message_from_bytes(email_msg)
maintype = email_msg.get_content_maintype()
if maintype == 'multipart':
for part in email_msg.get_payload():
if part.get_content_maintype() == 'text':
print(part.get_payload())
elif maintype == 'text':
print(email_msg.get_payload())
Run Code Online (Sandbox Code Playgroud)
但这有几个问题:当消息是多部分的时,每个部分都会被打印,有时最后一部分基本上是整个消息,但采用 html 格式。
另外,这会打印收件箱中的所有消息,如何使用 imaplib 监听新电子邮件?或与其他库。