#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
问题:当使用cv2.imread()读取图像时,出现:libpng warning: iCCP: known incorrect sRGB profile警告
原因:因为图像文件中包含了一个色彩配置文件color profile
问题:在尝试保存图像时出现OSError: cannot write mode RGBA as JPEG错误
原因:因为图像本身可能是RGBA模式(带有透明通道),而JPEG格式不支持透明通道。
问题:在处理其他格式的图像时出现ignoring corrupt image/label: invalid image format GIF警告
原因:如果处理的图像中有GIF格式,GIF格式通常不用于训练模型,您可能需要跳过或转换这些图像。
为了解决这些问题,您可以采取以下步骤:
1. 读取图像:使用PIL(Pillow)库读取图像,这样可以保留图像的所有元数据。
2. 处理色彩配置文件:如果图像包含色彩配置文件,则删除或替换它。
3. 转换图像模式:如果图像模式是RGBA,将其转换为RGB模式。
4. 跳过或转换非JPEG格式的图像:对于非JPEG格式的图像,您可以选择跳过它们或转换为JPEG格式。
5. 保存图像:使用PIL保存图像到原路径下,确保使用正确的格式。
下面是一个示例脚本,用于处理这些问题:
'''
import glob
import os
from tqdm import tqdm
import cv2
import warnings
from PIL import Image
def process_and_save_image(image_file):
# 使用PIL打开图像
img_pil = Image.open(image_file)
# 删除ICC配置文件
if "icc_profile" in img_pil.info:
img_pil.info.pop("icc_profile")
# 如果图像模式是RGBA,则转换为RGB
if img_pil.mode == 'RGBA':
img_pil = img_pil.convert('RGB')
# 如果图像不是JPEG格式,可以选择跳过或转换为JPEG
if img_pil.format.lower() != 'jpeg':
print(f"Warning: Skipping non-JPEG image: {image_file}")
return
# 保存图像
img_pil.save(image_file)
def read_and_process_images(image_files):
# 忽略警告
with warnings.catch_warnings():
warnings.simplefilter("ignore")
for image_file in image_files:
# 使用OpenCV读取图像
img = cv2.imread(image_file)
# 如果读取成功
if img is not None:
# 处理并保存图像
process_and_save_image(image_file)
print(f"Image {image_file} has been processed and saved.")
else:
print(f"Failed to read {image_file}.")
# 使用示例
image_dir = "./imgs"
image_files = glob.glob(os.path.join(image_dir, "*.jpg"))
for image_file in tqdm(image_files):
read_and_process_images(image_file)
如何解决libpng warning: iCCP: known incorrect sRGB profile、OSError: cannot write mode RGBA as JPEG
于 2024-08-26 10:13:13 首次发布