import os
import glob
import numpy as np
from PIL import Image
import os.path
path = '图片文件夹地址'
index = 1
# error1 = Image.open('1.jpg')
# error2 = Image.open('2.jpg')
# image = np.array(error2)
# print(error2.mode, image.shape)
for file in os.listdir(path):
if os.path.isfile(os.path.join(path, file)):
# 重命名模块
# if file.find('.') > 0:
# newname = 'towercrane' + str(index) + '.jpg'
# index += 1
# os.rename(os.path.join(path, file), os.path.join(path, newname))
# print('ok')
img_path = os.path.join(path, file)
im = Image.open(img_path)
image = np.array(im)
# 防止图片标注的时候出现bug
if im.mode == "P":
im = im.convert('RGB')
os.remove(img_path)
im.save(img_path[:-4] + ".jpg")
print('p removed') # 8位像素,使用调色板映射到任何其他模式
continue
if im.mode == "L":
im = im.convert('RGB')
os.remove(img_path)
im.save(img_path[:-4] + ".jpg")
print('l removed') # 8位像素,黑白
continue
print(image.shape, img_path)
if image.shape[2] == 4:
r, g, b, a = im.split()
im = Image.merge("RGB", (r, g, b))
os.remove(img_path)
im.save(img_path[:-4] + ".jpg")
print('png removed')
print('only have jpg!')
# 参考链接:https://www.jianshu.com/p/e8d058767dfa
# 模式
# 1 1位像素,黑和白,存成8位的像素
# L 8位像素,黑白
# P 8位像素,使用调色板映射到任何其他模式
# RGB 3×8位像素,真彩
# RGBA 4×8位像素,真彩+透明通道
# CMYK 4×8位像素,颜色隔离
# YCbCr 3×8位像素,彩色视频格式
# I 32位整型像素
# F 32位浮点型像素
出现的错误:
OSError: cannot write mode XX as JPEG