import os 如果报错的话,在下面添加
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
import os
import re
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
import glob
import cv2
import numpy as np
from PIL import Image
# 读取文件夹中图片
Image_dir = r''# 添加绝对路径
Image_glob = os.path.join(Image_dir, "*.png")
Image_name_list = []
# 将符合条件的 png 文件路径读取到 Image_list 中去
Image_name_list.extend(glob.glob(Image_glob))
# print(Image_name_list[::])
len_Image_name_list = len(Image_name_list)
print(len_Image_name_list)
图片路径可以绝对路径,也可以相对路径。
我这里读取的是*png格式的图片。
遍历读取的图片,用cv2展示。
for i in range(len_Image_name_list):
image_path = Image_name_list[i]
# print(image_path)
image = cv2.imread(image_path)
# cv2.imshow("",image)
# cv2.waitKey(100)
# print(type(image_path))
如果对图片大小进行处理,可以用cv2.resize()
dst_size = (224, 224)
# img_resize = cv2.resize(image, dst_size, interpolation=cv2.INTER_AREA)
img_resize = cv2.resize(image, dst_size)
# print(img_resize.shape)
保存图片时要注意图片文件名的话,我用的是正则表达式来去除图片路径名称的前后缀,保证和原图片数据集文件名一致。
suffix = '.PNG'
prefix = ''
image_name = re.sub('^' + re.escape(prefix), '', image_path) # 删前缀
image_name = re.sub(re.escape(suffix) + '$', '', image_name) # 删后缀
print(image_name)
cv2.imwrite("{}.png".format(image_name), img_resize)
最后是全部的完整代码:
import os
import re
# re.sub('^' + re.escape(prefix), '', s) # 删前缀
# re.sub(re.escape(suffix) + '$', '', s) # 删后缀
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
import glob
import cv2
import numpy as np
from PIL import Image
# 读取文件夹中图片
# Image_dir = r''
Image_dir = r''
Image_glob = os.path.join(Image_dir, "*.png")
Image_name_list = []
# 将符合条件的 png 文件路径读取到 Image_list 中去
Image_name_list.extend(glob.glob(Image_glob))
# print(Image_name_list[::])
len_Image_name_list = len(Image_name_list)
print(len_Image_name_list)
for i in range(len_Image_name_list):
image_path = Image_name_list[i]
# print(image_path)
image = cv2.imread(image_path)
# cv2.imshow("",image)
# cv2.waitKey(100)
# print(type(image_path))
dst_size = (224, 224)
# img_resize = cv2.resize(image, dst_size, interpolation=cv2.INTER_AREA)
img_resize = cv2.resize(image, dst_size)
# print(img_resize.shape)
suffix = '.PNG'
prefix = ''
image_name = re.sub('^' + re.escape(prefix), '', image_path) # 删前缀
image_name = re.sub(re.escape(suffix) + '$', '', image_name) # 删后缀
print(image_name)
cv2.imwrite("{}.png".format(image_name), img_resize)
# width, height, channel = img.shape
# print('width={},height={},channel={}'.format(width, height, channel))
# # 计算长和宽的差值
# dim_diff = np.abs(height - width)
# # 计算上下左右分别需要填充多少个维度
# pad1, pad2 = dim_diff // 2, dim_diff - dim_diff // 2
# pad = (0, 0, pad1, pad2) if height <= width else (pad1, pad2, 0, 0)
# top, bottom, left, right = pad
# # 使用opencv的copyMakeBorder函数进行填充
# pad_value = 0
# img_pad = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, None, pad_value)
# dst_size = (128, 128)
# img_resize = cv2.resize(img_pad, dst_size, interpolation=cv2.INTER_AREA)