很多时候我们需要用到灰度图像,比如说在深度学习的训练中,有时候我们并不需要图片的颜色信息,然而我们日常环境下获得的通常都是彩色图像,所以需要将彩色图像转换成灰度图像,也就是从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)