agrobot_base/Python/yolov8-seg/convert.py

47 lines
1.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
from PIL import Image
# 🟢 CONFIGURA AQUI
PASTA_IMAGENS = r"images/convert" # troque pelo caminho da pasta
QUALIDADE_JPEG = 85 # 8090 costuma ser um bom equilíbrio
def converter_png_para_jpeg(pasta):
for nome_arquivo in os.listdir(pasta):
if not nome_arquivo.lower().endswith(".png"):
continue
caminho_png = os.path.join(pasta, nome_arquivo)
nome_base, _ = os.path.splitext(nome_arquivo)
caminho_jpeg = os.path.join(pasta, nome_base + ".jpg")
print(f"Convertendo: {caminho_png} -> {caminho_jpeg}")
with Image.open(caminho_png) as img:
# Garante que está em RGB (JPEG não suporta transparência)
if img.mode in ("RGBA", "LA"):
# Fundo branco; mude para (0, 0, 0) se quiser fundo preto
fundo = Image.new("RGB", img.size, (255, 255, 255))
fundo.paste(img, mask=img.split()[-1]) # usa o canal alpha como máscara
img = fundo
else:
img = img.convert("RGB")
# Salva como JPEG
img.save(
caminho_jpeg,
"JPEG",
quality=QUALIDADE_JPEG,
optimize=True,
progressive=True,
)
# ⚠️ Se quiser apagar o PNG depois de conferir que ficou ok, descomente:
# os.remove(caminho_png)
if __name__ == "__main__":
converter_png_para_jpeg(PASTA_IMAGENS)
print("Finalizado!")