只需要修改png的文件夹地址和转换后jpg的保存地址即可使用。
# png -> jpg
import os
import cv2
from PIL import Image
from tqdm import tqdm
def PNG_JPG(png_path, jpg_path):
img = cv2.imread(png_path, 0)
w, h = img.shape[::-1]
img = Image.open(png_path)
try:
if len(img.split()) == 4:
# prevent IOError: cannot write mode RGBA as BMP
r, g, b, a = img.split()
img = Image.merge("RGB", (r, g, b))
img.convert('RGB').save(jpg_path, quality=100)
else:
img.convert('RGB').save(jpg_path, quality=100)
return True
except Exception as e:
print("Error: ", e)
return False
image_png_dir = "E:/Primitive_Arguments/flag/organization/"
image_jpg_dir = "E:/Primitive_Arguments/flag/jpg/"
pbar = tqdm(os.listdir(image_png_dir))
for image in pbar:
pbar.set_description("Processing {}".format(image))
if image.endswith('.png'):
png_path = os.path.join(image_png_dir, image)
jpg_path = os.path.join(image_jpg_dir, os.path.splitext(image)[0] + ".jpg")
PNG_JPG(png_path, jpg_path)