【问题标题】:Is there a way to convert a folder of images (pngs, gifs) to an arraylist in Python?有没有办法将图像文件夹(png、gif)转换为 Python 中的数组列表?
【发布时间】:2020-10-27 00:12:49
【问题描述】:

所以我正在创建一个不和谐机器人,作为一些朋友在我们服务器上的爱好! 我正在学习 python 编程以及 discord bot 的一些额外内容,但我不知道如何将图像文件夹转换为 ArrayList,以便我可以随机选择图像用于发送 gif 或png 作为回应!

【问题讨论】:

  • 您可以使用cv2.imencode()将图像编码为字符串并将它们存储在ArrayList中,然后在响应中发送字符串并使用cv2.imdecode()对其进行解码
  • 您具体在哪个部分苦苦挣扎? ArrayList 这不就是Java中的一种对象吗?请参阅How to Askhelp center

标签: python discord.py


【解决方案1】:

您可以尝试这样的方法来获取文件路径:

import os
imagePaths = [f for f in os.listdir('.') if os.path.isfile(f)]
# Assuming you have a directory of only .pngs and .gifs

当您需要随机选择一个时,以下可能会有所帮助

import random

randomImagePath = random.choice(imagePaths)

实际发送图片可以看this answer。为了保持一致性,我将在一个小测试脚本中添加它的整体外观:

import os
import random
import discord

""" Any discord setup needed """

def imageGenerator():
    imagePaths = [f for f in os.listdir('.') if os.path.isfile(f)]
    while True:
        yield random.choice(imagePaths)

if __name__ == "__main__":
    gen = imageGenerator()
    with open(next(gen), 'rb') as f:
        picture = discord.File(f)
        await channel.send(channel, picture)

【讨论】:

  • 非常感谢您的回复!导入os的第一部分,“[f for f in os.listdir('.') if os.path.isfile(f)]”代表什么?
  • 当然,os.listdir 将列出目录"." 中的所有内容,这是您的工作目录。 os.path.isfile 所做的是检查它们是否确实是正在添加的文件(listdir 也会添加它找到的任何目录,此过滤器因此只有文件在您的列表中)
  • 我明白了!所以我正在查看您定义函数 imageGenerator 的测试脚本。我使用await ctx.send(file=discord.File( file name) in 的方法发送图片。那么,理论上,我是否可以调用 imageGenerator 函数来代替文件名,因为它包含随机图像?
  • 您应该使用next(gen) 作为文件名。它是一个生成器,而不是一个函数。我也可以实现一个函数实现,但我觉得生成器更适合你的情况
  • 我明白了!那么在 if 语句中,Namemain 将代表什么作为变量以及 'rb'?
【解决方案2】:
import random
import glob

image_paths = glob.glob("Plate_examples/*.jpg") #load all the jpg file from this directory
img = []
for images in image_paths: #loop through the list of image path
    img.append(images)   # append each image path into this list 
    
randomImagePath = random.choice(img) # select each path at random

【讨论】:

  • imgimage_paths 不一样吗?复制变量的目的是什么。
猜你喜欢
  • 2011-02-01
  • 2013-07-07
  • 2019-08-22
  • 1970-01-01
  • 2013-07-09
  • 2010-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多