目录
重命名,重新编号:
python 重命名 重新编号_jacke121的专栏-CSDN博客
批量改图片后缀
import os
import cv2
dir_path =r'F:\data_set\data_mangguo'
g = os.walk(dir_path)
img_files = ['%s/%s' % (i[0], j) for i in g for j in i[-1] if j.endswith('png')]
for file in img_files:
# os.remove(file)
img = cv2.imread(file)
file_new = file.replace(".png", ".jpg")
cv2.imwrite(file_new, img)
批量重新命名
dir_path=r'F:\project\jushi\data\crop\image'
dir_to=os.path.dirname(dir_path)+'/label/'
dir_path=dir_to
os.makedirs(dir_to,exist_ok=True)
files=glob.glob(dir_path+'/*.png')+glob.glob(dir_path+'/*.bmp')+glob.glob(dir_path+'/*.jpg')
index=0
for file in files:
img=cv2.imread(file)
timestr = datetime.datetime.now().strftime('/%H%M%S_')
print(timestr)
index+=1
name_new=os.path.dirname(file)+timestr+str(index)+".jpg"
cv2.imwrite(name_new,img)
批量复制图片:
dir_path = r'E:\image-2'
# dir_to = os.path.dirname(dir_path) + '/label/'
# dir_path = dir_to
# os.makedirs(dir_to, exist_ok=True)
files = glob.glob(dir_path + '/*.png') + glob.glob(dir_path + '/*.bmp') + glob.glob(dir_path + '/*.jpg')
index = 0
for file in files:
img = cv2.imread(file)
label_file=file.replace("image","label")
img_label = cv2.imread(label_file)
for i in range(50):
timestr = datetime.datetime.now().strftime('/%H%M%S_')
print(timestr)
index += 1+i*10
name_new = os.path.dirname(file) + timestr + str(index) + ".jpg"
cv2.imwrite(name_new, img)
name_new = os.path.dirname(label_file) + timestr + str(index) + ".jpg"
cv2.imwrite(name_new, img_label)
time.sleep(0.1)
python批量缩放,批量图片改名
# -*- coding: utf-8 -*-
import glob
import os.path
import cv2
import numpy as np
if __name__ == '__main__':
padding=False
dir_path=r'F:\project\wendu\zengqiang\train'
dir_to=r'F:\project\wendu\zengqiang_s\train'
img_files = ['%s/%s' % (i[0].replace("\\", "/"), j) for i in os.walk(dir_path) for j in i[-1] if
j.endswith(('jpg', 'png', 'jpeg', 'JPG'))]
for file in img_files:
src_img = cv2.imread(file)
if max(src_img.shape[:2]) > 1000:
x_scale = 1000 / max(src_img.shape[:2])
src_img = cv2.resize(src_img, None, fx=x_scale, fy=x_scale, interpolation=cv2.INTER_AREA)
if padding:
to_w = 640
to_h = 640
t_h, t_w = src_img.shape[:2]
if t_h / t_w > to_h / to_w:
t_w_new = round(to_w / to_h * t_h)
t_h_new = t_h
else:
t_h_new = round(to_h / to_w * t_w)
t_w_new = t_w
img_b = np.zeros((t_h_new, t_w_new, 3), dtype=np.uint8)
img_b[:t_h, : t_w, :] = src_img
else:
img_b=src_img
file_to=file.replace(dir_path.replace("\\","/"),dir_to.replace("\\","/"))[:-4]+".jpg"
os.makedirs(os.path.dirname(file_to), exist_ok=True)
cv2.imwrite(file_to, img_b)
批量删除目录
import os
import shutil
import shutil
dir_a=r'/lpai/volumes/ad-op-ga/code/exp'
dir_names = ['%s' % (i[0]) for i in os.walk(dir_a) if i[0].endswith('pytorch_model')]
# dir_names = ['%s' % (i[0]) for i in os.walk(dir_a) if i[0].startswith('checkpoint_epoch_6')]
for dir_name in dir_names:
try:
shutil.rmtree(dir_name)
print("目录删除成功",dir_name)
except OSError as e:
print("目录删除失败:", e)
print(dir_name)