深度学习中的文件处理(一)
批量旋转图像并调整尺寸
import os
import cv2
import numpy as np
filename = os.listdir(r'C:\Users\xjj\Desktop\202009-35first\202009189d.114')
base_dir = r'C:\Users\xjj\Desktop\202009-35first\202009189d.114\'
new_dir = r'C:\Users\xjj\Desktop\202009-35first\202009189d.114\'
size_m = 640
size_n = 400
def rotate_bound(image, angle):
# grab the dimensions of the image and then determine the
# center
(h, w) = image.shape[:2]
(cX, cY) = (w // 2, h // 2)
# grab the rotation matrix (applying the negative of the
# angle to rotate clockwise), then grab the sine and cosine
# (i.e., the rotation components of the matrix)
M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
# compute the new bounding dimensions of the image
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
# adjust the rotation matrix to take into account translation
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY
# perform the actual rotation and return the image
return cv2.warpAffine(image, M, (nW, nH))
for img in filename:
src = os.path.join(base_dir, img)
image = cv2.imread(src)
h, w = image.shape[:2]
print(h)
print(w)
if h > w:
angle = 90
image = rotate_bound(image, angle)
#cv2.imwrite(new_dir+img, image)
image_size = cv2.resize(image, (size_m, size_n))
# 全部图片尺寸调整为640*400
cv2.imwrite(new_dir + img, image_size)
浙公网安备 33010602011771号