python 图片按照固定大小批量裁剪及文件夹中文件名称的获取
程序员文章站
2022-04-09 13:08:52
...
图片裁剪部分
"""
@author: Jerry
@address: qingdao
"""
import cv2
import os
crop_size = 256
savepath = ''
if os.path.exists('image_crop'):
savepath = './' + 'image_crop'
else:
os.mkdir('image_crop')
savepath = './' + 'image_crop'
def image_crop(image_path, filename_prefix, filename_suffix):
img = cv2.imread(image_path)
rows = img.shape[0]
columns = img.shape[1]
rows_count = int(rows / crop_size)
columns_count = int(columns / crop_size)
flag2 = 0
for i in range(rows_count):
flag = 0
for j in range(columns_count):
cropped = img[i * crop_size:(i + 1) * crop_size, flag * crop_size:(flag + 1) * crop_size]
flag += 1
flag2 += 1
path = savepath + './' +filename_prefix + '_' + str(flag2) + '.' + filename_suffix
cv2.imwrite(path, cropped)
def image_acquire(directory_name):
for filename in os.listdir(directory_name):
print(filename)
image_path = directory_name + "/" + filename
filename_prefix = filename.split('.')[0]
filename_suffix = filename.split('.')[1]
image_crop(image_path, filename_prefix, filename_suffix)
if __name__ == '__main__':
filepath = 'E:\ISPRS_Tif_Lable\image'
image_acquire(filepath)
文件名称的获取
"""
@author: Jerry
@address: qingdao
"""
import os
import cv2
def read_directory(directory_name, savefilename):
array_of_img = []
for filename in os.listdir(r"./"+directory_name):
filename = filename.split('.')[0]
array_of_img.append(filename)
with open("%s.txt"%savefilename, "a") as f:
for i in range(len(array_of_img)):
f.write(array_of_img[i] + "\n")
f.close()
if __name__ == '__main__':
directory = "./image_crop"
savefilename = "savefilenames"
read_directory(directory, savefilename)
参考链接:
Python创建文件夹和子文件夹
python读取文件夹下所有图片
图片平均裁剪为固定大小以及运行python脚本时出现no module named cv2