自定义像素尺寸:
path1='D:/size/2.jpg'
path2='D:/resize/2.jpg'
img = cv2.imread(path1)
size = (400,500) #注意排序是反的,出来顺序是500*400
img = cv2.resize(img, size)
#cv2.imshow('image',img)
cv2.imwrite(path2,img)
以下将读取文件夹中图片最大宽、高,并统一将文件夹下所有图片的尺寸修改成最大;
命令:python Size.py inputFilePath outputFilePath
Size.py
#coding:utf-8
import os
import numpy as np
import pandas as pd
import cv2
import sys #使用sys 模块从外部调用参数
#from make_transparent import *
from matplotlib import pyplot as plt
inputFilePath = sys.argv[1]
outputFilePath = sys.argv[2]
def run_size(path):
for root, dirs, files in os.walk(path):
#print(root) #当前目录路径
#print(dirs) #当前路径下所有子目录
#print(files) #当前路径下所有非目录子文件
files.sort(key=lambda x: int(x[:-4])) #文件名按数字顺序排序;从倒数第4个字符开始;
print('ImageName:\n', files, '\n')
lenfile = len(files)
for i in range(lenfile):
files[i] = path + files[i] #每个子文件路径
newList = files
print('ImagePath:\n', newList, '\n')
lslen=len(newList)
print('ImageNum:\n', lslen, '\n')
imge = {}
height = []
width = []
for i in range(lslen):
imge[i] = cv2.imread(newList[i], cv2.IMREAD_UNCHANGED)
(h,w,c) = imge[i].shape
height.append(h)
width.append(w)
target_height = max(height)
target_width = max(width)
target_height = np.array(target_height)
target_width = np.array(target_width)
delta_height = target_height - height
delta_width = target_width - width
left = np.zeros(lslen)
right = np.zeros(lslen)
top = np.zeros(lslen)
bottom = np.zeros(lslen)
for i in range(lslen):
if (delta_width[i] % 2) == 0:
left[i] = int(delta_width[i]//2)
right[i] = left[i]
else:
left[i] = int(delta_width[i]/2)
right[i] = left[i]+1
if (delta_height[i] % 2) == 0:
top[i] = int(delta_height[i]//2)
bottom[i] = top[i]
else:
top[i] = int(delta_height[i]/2)
bottom[i] = top[i]+1
processedImage = {}
for i in range(lslen):
processedImage[i] = cv2.copyMakeBorder(imge[i], int(top[i]), int(bottom[i]),int(left[i]), int(right[i]), cv2.BORDER_CONSTANT,(0,0,0,0) )
#输出图片到文件夹
for i in range(lslen):
cv2.imwrite((outputFilePath+'/%s.png'%(i+1)),processedImage[i])
run_size(inputFilePath)
print("done!\n")