Python将图片转换为灰度图

  很多时候我们需要用到灰度图像,比如说在深度学习的训练中,有时候我们并不需要图片的颜色信息,然而我们日常环境下获得的通常都是彩色图像,所以需要将彩色图像转换成灰度图像,也就是从3个通道(RGB)转换成一个通道。

from PIL import Image
import os.path
import glob

def convertjpg(jpgfile,outdir):
    try:
        image_file = Image.open(jpgfile) # open colour image
        image_file = image_file.convert('L') # convert image to black and white
        image_file.save(os.path.join(outdir, os.path.basename(jpgfile)))
    except Exception as e:
        print(e)

for jpgfile in glob.glob(r"E:\z\*.jpg"):    ## 所有图片存放路径 png可以改成jpg
    # print(jpgfile)
    convertjpg(jpgfile,r"E:\z1")        ## 转换完后的保存路径

2021.8.9更改:将灰度化后的图片命名为g+原始图片名,并将对应的标签文件改成g+原始标签名

from PIL import Image
import os.path
import glob
import shutil

src_img = r"C:\Users\1\Desktop\test\1\images"  # 原始图片路径
dst_img = r"C:\Users\1\Desktop\test\1\g-images"  # 灰度图的保存路径
src_txt = r"C:\Users\1\Desktop\test\1\labels"  # 原始标签路径
dst_txt = r"C:\Users\1\Desktop\test\1\g-labels"  # 灰度图txt标签存放路径


def convertjpg(jpgfile, outdir):
    try:
        image_file = Image.open(jpgfile)  # open colour image
        image_file = image_file.convert('L')  # convert image to black and white
        image_file.save(os.path.join(outdir, ('g' + os.path.basename(jpgfile))))
    except Exception as e:
        print(e)


for jpgfile in glob.glob(os.path.join(src_img, '*.jpg')):  # jpg为原始图片格式
    convertjpg(jpgfile, dst_img)

dst_txt = os.path.join(dst_txt, 'g-labels')
if os.path.isdir(dst_txt):
    shutil.rmtree(dst_txt)
shutil.copytree(src_txt, dst_txt)
for txtfile in glob.glob(os.path.join(dst_txt, '*.txt')):  # txt为标签文件格式
    new = 'g' + os.path.basename(txtfile)
    newtxtfile = os.path.join(dst_txt, new)
    os.rename(txtfile, newtxtfile)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值