1. 旋转图像操作(90°、180°、270°)
from PIL import Image
import os
filePath = 'F:/1213bag/test_transforms/0912/2/'
filenames = os.listdir(filePath)
outputPath = 'F:/1213bag/test_transforms/0912/3/'
for filename in filenames:
im = Image.open(filePath + filename)
im_rotate = im.transpose(Image.ROTATE_90)
im_rotate.save(outputPath + filename)
2. jpg 和png相互转换、resize尺寸大小
import os
import cv2
import sys
import numpy as np
path1 = r'F:\1213bag\test_transforms\0912\3'
path2 = r'F:\1213bag\test_transforms\0912\4'
for filename in os.listdir(path1):
if os.path.splitext(filename)[1] == '.jpg':
sas = os.path.join(path1, filename)
img = cv2.imread(sas)
tem = cv2.resize(img, (256, 512))
newfilename = filename.replace(".jpg", ".png")
dst = os.path.join(path2, newfilename)
cv2.imwrite(dst, tem)
3. padding 补黑边,长方形保持长宽比最后补黑边padding成正方形
import os
import numpy as np
import cv2
from PIL import Image
def img_pad(pil_file):
h, w, c = pil_file.shape
fixed_size = 512
if h >= w:
factor = h / float(fixed_size)
new_w = int(w / factor)
if new_w % 2 != 0:
new_w -= 1
pil_file = cv2.resize(pil_file, (new_w, fixed_size))
pad_w = int((fixed_size - new_w) / 2)
array_file = np.array(pil_file)
# array_file = np.pad(array_file, ((0, 0), (pad_w, fixed_size-pad_w)), 'constant')
array_file = cv2.copyMakeBorder(array_file, 0, 0, pad_w, fixed_size - new_w - pad_w, cv2.BORDER_CONSTANT,
value=(0, 0, 0))
else:
factor = w / float(fixed_size)
new_h = int(h / factor)
if new_h % 2 != 0:
new_h -= 1
pil_file = cv2.resize(pil_file, (fixed_size, new_h))
pad_h = int((fixed_size - new_h) / 2)
array_file = np.array(pil_file)
# array_file = np.pad(array_file, ((pad_h, fixed_size-pad_h), (0, 0)), 'constant')
array_file = cv2.copyMakeBorder(array_file, pad_h, fixed_size - new_h - pad_h, 0, 0, cv2.BORDER_CONSTANT,
value=(0, 0, 0))
output_file = Image.fromarray(array_file)
return output_file
if __name__ == "__main__":
dir_image = r'F:\1213bag\test_transforms\0912\4'
dir_output = r'F:\1213bag\test_transforms\0912\666'
if not os.path.exists(dir_output):
os.makedirs(dir_output)
i = 0
list_image = os.listdir(dir_image)
for file in list_image:
path_image = os.path.join(dir_image, file)
path_output = os.path.join(dir_output, file)
pil_image = cv2.imread(path_image)
b, g, r = cv2.split(pil_image)
pil_image = cv2.merge([r, g, b])
output_image = img_pad(pil_image)
output_image.save(path_output)
i += 1
if i % 1000 == 0:
print('The num of processed images:', i)
4. 处理过曝数据
import cv2
import os
import numpy as np
def read_path(file_pathname):
for filename in os.listdir(file_pathname):
print(filename)
img = cv2.imread(file_pathname+'/'+filename)
image = np.power(img, 0.95)
cv2.imwrite(r"F:\1213bag\test_transforms\0912\add1" + "/" + filename, image)
read_path(r"F:\1213bag\test_transforms\0912\add")