1.批量重命名
import os
# 对文件夹进行重命名,从1开始
path = 'G:\\video_to_picture\\空气滤芯器1\\4' #文件所在位置
filelist = os.listdir(path)
count = 794
for file in filelist:
print(file)
for file in filelist:
Olddir = os.path.join(path, file)
if os.path.isdir(Olddir):
continue
filename = os.path.splitext(file)[0]
filetype = os.path.splitext(file)[1]
Newdir = os.path.join(path, str(count).zfill(1) + filetype)
os.rename(Olddir, Newdir)
count += 1
2.视频帧截取图片
import cv2
path = 'G:\\video_to_picture\\video9\\00045.MTS'
# path = 'G:\\video_to_picture\\4.mp4'
vc = cv2.VideoCapture(path) # 读入视频文件
c = 1 # 设置间隔多少帧取一张图片
# 0i = 0
if vc.isOpened(): # 判断是否正常打开
rval, frame = vc.read()
else:
rval = False
print('打开失败')
timeF = 100 # 视频帧计数间隔频率
while rval: # 循环读取视频帧
rval, frame = vc.read()
if (c % timeF == 0): # 每隔timeF帧进行存储操作
# i = i + 1
savepath = 'G:\\video_to_picture\\video9\\lvxin' #命名格式
cv2.imwrite(savepath +'a'+ str(c) + '.jpg', frame) # 存储为图像
print('保存地址', savepath + str(c) + '.jpg')
c = c + 1
cv2.waitKey(1)
vc.release()
3.图片合成视频
import cv2
import os
import os.path as osp
# 利用python将一个包含图片序列的文件夹下的所有图片转成avi视频形式
# 程序运行的过程中务必记得修改像素点,并且路径中不能出现中文!!!
def img2video(img_dir, img_size, video_dir, fps):
fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') # opencv3.0
videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size)
for idx in sorted(os.listdir(img_dir)):
img = osp.join(img_dir, idx)
frame = cv2.imread(img)
# print(frame.shape) # h, w, c (480, 640, 3)
videoWriter.write(frame)
videoWriter.release()
print('Finish changing!')
if __name__ == '__main__':
img_dir = 'D:\\air-filter\\train\\images\\' # 图片存放地址
par_dir = osp.dirname(img_dir)
video_path = osp.join(par_dir, 'output.avi')
fps = 24
img_size = (1920, 1080) # w, h
img2video(img_dir=img_dir, img_size=img_size, video_dir=video_path, fps=fps)
4.jpg文件批量读取绝对路径
import os
def writejpg2txt(images_path, txt_name):
# 打开图片列表清单txt文件
file_name = open(txt_name, "w")
# 将路径改为绝对路径
images_path = os.path.abspath(images_path)
# 查看文件夹下的图片
images_name = os.listdir(images_path)
count = 0
# 遍历所有文件
for eachname in images_name:
# 按照需要的格式写入目标txt文件
file_name.write(os.path.join(images_path,eachname) + '\n')
count += 1
print('Congratulations,txt success!')
print('{} image addresses has been written!!!!!'.format(count))
file_name.close()
if __name__ == "__main__":
images_path = 'D://needed//air-filter//valid//images'# 图片存放目录
txt_name = 'D://needed//air-filter//valid//valid.txt' # # 图片txt文件命名
txt_name = os.path.abspath(txt_name)
if not os.path.exists(txt_name):
os.system(r"touch {}".format(txt_name)) # 调用系统命令行来创建文件
# 将jpg绝对地址写入到txt中
writejpg2txt(images_path, txt_name)