前言
常见的图像任务通常需要把照片统一成相同的格式,所以此文章正是为了统一格式而生,常见的主要有cv2和PIL.Image的相关操作,照片格式是一串数字加上后缀名
工具一:cv2
[Python] 纯文本查看 复制代码 pip install opencv-python
之后就可以
[Python] 纯文本查看 复制代码 import cv2
1.1 导包
[Python] 纯文本查看 复制代码 import os
import cv2
import sys
import numpy as np
1.2 路径设置
[Python] 纯文本查看 复制代码 path = r"C:\\Users\\86775\\test_change\\"
path2 = r"C:\\Users\\86775\\test_change2\\"
1.3 改格式重新传
1.3.1 用os.path.splitext()来判断
[Python] 纯文本查看 复制代码 images = os.listdir(path)
for i in os.listdir(path):
print(os.path.splitext(i)) # ('34474006827920603', '.png')
if os.path.splitext(i)[1] == ".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)[1] == ".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)[1] == ".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)[1] == ".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)[1] == ".jpg":
img = cv2.imread(path + i)
# print(img)
cv2.imwrite(path2 + i, img)
1.3.2 用split()来判断
[Python] 纯文本查看 复制代码 images = os.listdir(path)
for i in os.listdir(path):
print(i.split("."))
if i.split(".")[1] == "jpeg":
img = cv2.imread(path + i)
# print(img)
new_imagename = i.replace(".jpeg", ".jpg")
cv2.imwrite(path2 + new_imagename, img)
elif i.split(".")[1] == "png":
img = cv2.imread(path + i)
# print(img)
new_imagename = i.replace(".png", ".jpg")
cv2.imwrite(path2 + new_imagename, img)
elif i.split(".")[1] == "JPG":
img = cv2.imread(path + i)
# print(img)
new_imagename = i.replace(".JPG", ".jpg")
cv2.imwrite(path2 + new_imagename, img)
elif i.split(".")[1] == "PNG":
img = cv2.imread(path + i)
# print(img)
new_imagename = i.replace(".PNG", ".jpg")
cv2.imwrite(path2 + new_imagename, img)
elif i.split(".")[1] == "jpg":
img = cv2.imread(path + i)
# print(img)
cv2.imwrite(path2 + i, img)
1.4 查看结果
|