python怎么读取文件夹的图片并打开_使用python一一打开文件夹中的图像?

本文介绍如何使用Python从文件夹中逐一读取图片,进行处理(如调整尺寸)后再保存到另一个文件夹。示例代码利用os模块列出文件夹中的图片,用PIL库打开图片,并通过多进程Pool进行并发处理。
摘要由CSDN通过智能技术生成

Hi all I need to open images from a folder one by one do some processing on images and save them back to other folder. I am doing this using following sample code.

path1 = path of folder of images

path2 = path of folder to save images

listing = os.listdir(path1)

for file in listing:

im = Image.open(path1 + file)

im.resize((50,50)) % need to do some more processing here

im.save(path2 + file, "JPEG")

Is there any best way to do this?

Thanks!

解决方案

Sounds like you want multithreading. Here's a quick rev that'll do that.

from multiprocessing import Pool

import os

path1 = "some/path"

path2 = "some/other/path"

listing = os.listdir(path1)

p = Pool(5) # process 5 images simultaneously

def process_fpath(path):

im = Image.open(path1 + path)

im.resize((50,50)) # need to do some more processing here

im.save(os.path.join(path2,path), "JPEG")

p.map(process_fpath, listing)

(edit: use multiprocessing instead of Thread, see that doc for more examples and information)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值