各種画像処理

import os
from PIL import Image
import glob


# jpg图像resize成256,256大小
def Resize(file, outdir, width, height):
    imgFile = Image.open(file)
    try:
        newImage = imgFile.resize((width, height), Image.BILINEAR)
        newImage.save(os.path.join(outdir, os.path.basename(file)))
    except Exception as e:
        print(e)


for file in glob.glob("./1_jpg/*.jpg"):  # 图片所在的目录
    Resize(file, "./2_jpgResize", 256, 256)  # 新图片存放的目录


# jpg彩色图像转为灰度图像
def jpgToGray(input_dir):
    for i in a:
        print(i)
        I = Image.open(input_dir + i)
        L = I.convert('L')
        L.save(out_dir + i)


input_dir = './dataprocess_result/2_jpgResize/'
out_dir = './dataprocess_result/3_jpg2gray/'
a = os.listdir(input_dir)
jpgToGray(input_dir)


# jpg图像转为bmp图像
def jpgToBmp(imgFile):
  dst_dir = "./dataprocess_result/4_jpg2bmp"

  for fileName in os.listdir(imgFile):
    if os.path.splitext(fileName)[1] == '.jpg':
      name = os.path.splitext(fileName)[0]
      newFileName = name + ".bmp"

      img = Image.open(imgFile + "/" + fileName)
      img.save(dst_dir+"/"+newFileName)


imgFile = "./dataprocess_result/3_jpg2gray"
jpgToBmp(imgFile)


# png图像转为bmp图像
def pngToBmp(imgFile):
  dst_dir = "./dataprocess_result/5_png2bmp"

  for fileName in os.listdir(imgFile):
    if os.path.splitext(fileName)[1] == '.png':
      name = os.path.splitext(fileName)[0]
      newFileName = name + ".bmp"

      img = Image.open(imgFile + "/" + fileName)
      img.save(dst_dir+"/"+newFileName)


imgFile = "./result_png"
pngToBmp(imgFile)

おすすめ

転載: blog.csdn.net/everyxing1007/article/details/128073137