小案例:利用python转换图片格式
前言常见的图像任务通常需要把照片统一成相同的格式,所以此文章正是为了统一格式而生,常见的主要有cv2和PIL.Image的相关操作,照片格式是一串数字加上后缀名
工具一:cv2
pip install opencv-python
之后就可以
import cv2
1.1 导包
import os
import cv2
import sys
import numpy as np
1.2 路径设置
path = r"C:\\Users\\86775\\test_change\\"
path2 = r"C:\\Users\\86775\\test_change2\\"
1.3 改格式重新传
1.3.1 用os.path.splitext()来判断
images = os.listdir(path)
for i in os.listdir(path):
print(os.path.splitext(i))# ('34474006827920603', '.png')
if os.path.splitext(i) == ".jpeg":
img = cv2.imread(path + i)
# print(img)
new_imagename = i.replace(".jpeg", ".jpg")
cv2.imwrite(path2 + new_imagename, img)
elif os.path.splitext(i) == ".png":
img = cv2.imread(path + i)
# print(img)
new_imagename = i.replace(".png", ".jpg")
cv2.imwrite(path2 + new_imagename, img)
elif os.path.splitext(i) == ".JPG":
img = cv2.imread(path + i)
# print(img)
new_imagename = i.replace(".JPG", ".jpg")
cv2.imwrite(path2 + new_imagename, img)
elif os.path.splitext(i) == ".PNG":
img = cv2.imread(path + i)
# print(img)
new_imagename = i.replace(".PNG", ".jpg")
cv2.imwrite(path2 + new_imagename, img)
elif os.path.splitext(i) == ".jpg":
img = cv2.imread(path + i)
# print(img)
cv2.imwrite(path2 + i, img)
1.3.2 用split()来判断
images = os.listdir(path)
for i in os.listdir(path):
print(i.split("."))
if i.split(".") == "jpeg":
img = cv2.imread(path + i)
# print(img)
new_imagename = i.replace(".jpeg", ".jpg")
cv2.imwrite(path2 + new_imagename, img)
elif i.split(".") == "png":
img = cv2.imread(path + i)
# print(img)
new_imagename = i.replace(".png", ".jpg")
cv2.imwrite(path2 + new_imagename, img)
elif i.split(".") == "JPG":
img = cv2.imread(path + i)
# print(img)
new_imagename = i.replace(".JPG", ".jpg")
cv2.imwrite(path2 + new_imagename, img)
elif i.split(".") == "PNG":
img = cv2.imread(path + i)
# print(img)
new_imagename = i.replace(".PNG", ".jpg")
cv2.imwrite(path2 + new_imagename, img)
elif i.split(".") == "jpg":
img = cv2.imread(path + i)
# print(img)
cv2.imwrite(path2 + i, img)
1.4 查看结果
感谢楼主分享经验,学习了。 IF写得有点多,放到列表里面可能好些
images = os.listdir(path)
for i in os.listdir(path):
print(os.path.splitext(i))# ('34474006827920603', '.png')
houzhui = os.path.splitext(i)
if houzhui.lower() in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
img = cv2.imread(os.path.join(path, i))
if houzhui == ".jpg":
cv2.imwrite(os.path.join(path2, i), img)
else:
new_imagename = i.replace(houzhui, ".jpg")
cv2.imwrite(os.path.join(path2, new_imagename), img) 东西不错,感觉ps还是省事哪 学到了。。。感谢分享 感谢楼主分享经验,学习了。 厉害,学习了 感谢楼主分享经验,学习了。 又学到了一个技能 wkdxz 发表于 2022-11-17 15:19
IF写得有点多,放到列表里面可能好些
images = os.listdir(path)
学习一下
页:
[1]
2