Tools:
png文件较大,用于网络训练占用内存过大,可以转换为占用内存较小的有损压缩格式jpg
从指定csv读取png文件,然后将其保存到其他路径下同名jpg文件
import cv2 as cv
from PIL import Image
import os
import csv
import re
filePath ="/test/DataAnnotation/test.csv"
def PNG_JPG(PngPath,outFilepath):
img = cv.imread(PngPath, 0)
#print(img.shape)
w, h = img.shape[::-1]
infile = PngPath
#os.path.splitext(“文件路径”) 分离文件名与扩展名
outfile = os.path.splitext(outFilepath)[0] + ".jpg"
img = Image.open(infile)
# Image.NEAREST :低质量
# Image.BILINEAR:双线性
# Image.BICUBIC :三次样条插值
# Image.ANTIALIAS:高质量
#img = img.resize((int(w / 2), int(h / 2)), Image.ANTIALIAS)
try:
##img.split() Return Value: It returns a tuple containing bands.
if len(img.split()) == 4:
# prevent IOError: cannot write mode RGBA as BMP
r, g, b, a = img.split()
#将提取的rgb组合新图片
img = Image.merge("RGB", (r, g, b))
img.convert('RGB').save(outfile, quality=70)
#os.remove(PngPath)
else:
img.convert('RGB').save(outfile, quality=70)
#os.remove(PngPath)
return outfile
except Exception as e:
print("Transform error!", e)
if __name__ == "__main__":
csvFile = open(filePath, "r")
reader = csv.reader(csvFile)
##ssave to dict
#result={}
for item in reader:
if reader.line_num ==1:
continue
#result[item[0]]=item[1]
####保存到新路径
new_dir = re.sub("DataAnnotation","DataAnnotation_jpg",item[0])
if not os.path.exists(new_dir):
os.makedirs(new_dir)
png_path = os.path.join(item[0],item[1])
new_filepath = os.path.join(new_dir,item[1])
print(png_path,new_filepath,sep="\n")
PNG_JPG(png_path,new_filepath)