在制作Pascal VOC数据集时,需要对图片重命名。
图片数量比较多,都放在一个文件夹下面,而且在Mac下会有隐藏文件夹,比如.DS_Store
。
也有可能文件夹包含子文件夹,子文件夹中也包含多个图片。
针对这种情况写了以下一段Python
代码。
利用递归调用,实现了多层级目录读取文件,并判断文件是不是图片文件,以便针对图片文件进行重命名。
这段代码严格来说不是重命名,而是复制原图片文件。
利用``opencv2```,把原图片文件写到一个新的目录下,并重新命名。
# -*- coding: utf-8 -*-
import cv2
import os
# count
img_count = 1
# 递归调用方法,读取目录文件
def recyle_read(path, dst_path):
# 图片重命名计数
global img_count
# 判断是不是目录
if os.path.isdir(path):
# file list
file_list = os.listdir(path)
# 读取子文件,递归调用
for idx, file in enumerate(file_list):
print(path)
print(file)
sub_path = os.path.join(path, file)
recyle_read(sub_path, dst_path)
elif os.path.isfile(path):
img = cv2.imread(path)
# 判断是不是图片
if img is not None:
img_dst_path = os.path.join(dst_path, "gesture_voc_%06d.jpg" % img_count)
cv2.imwrite(img_dst_path, img)
img_count += 1
print('image count %d' % img_count)
else:
print(path + ' is empty')
pass
else:
print(path + ' is not image!')
pass
def main():
# object dir
dst_path = '/Users/ll/Desktop/obj/VOC2020/JPEGImages/'
# make dst dir
if os.path.exists(dst_path) is False:
os.makedirs(dst_path)
pass
# org dir
org_path = '/Users/ll/Desktop/src/'
# cp
recyle_read(org_path, dst_path)
pass
if __name__ == '__main__':
main()
pass
主要方法有两个
1、def main():
主要定义图片来源路径,这个路径可以是文件夹、也可以是单个图片文件。
也定义了新的写入路径,这个必须是文件夹。
2、def recyle_read(path, dst_path):
主要定义了递归读取图片文件,并写入新的目录下。
网友评论