在做图片筛选的时候,需要把图片打开然后复制粘贴到相应文件夹,打开再复制粘贴的过程十分繁琐,这里通过opencv
和shutil
库进行操作,打开图片显示,点击相应按键将图片复制或移动至相应文件夹,十分方便,适合摄影师或深度学习搞图片分类的小伙伴使用.
Python代码如下:
keyNum
对应的是q,w,e,r四个按键,每个按键将图片复制(shutil.copy(img_path, destination)
)或移动(shutil.copy(img_path, destination)
)至相应文件夹,有多少个类别就设置多少个按键.
import cv2
import shutil
import os
def main():
base_path = '/dataset/choosed_data'
copy_files = os.listdir(base_path)
new_path0 = '/img_type0'
new_path1 = '/img_type1'
new_path2 = 'img_type2'
new_path3 = 'img_type3'
for file in copy_files:
file_path = os.path.join(os.path.join(base_path, file), 'png')
img_names = os.listdir(file_path)
x = 0
for img_name in img_names:
img_path = os.path.join(file_path, img_name)
img = cv2.imread(img_path)
cv2.imshow('windows', img)
keyNum = cv2.waitKey(0)
if keyNum == ord('q'):
destination=os.path.join(new_path0,img_name)
shutil.copy(img_path,destination)
elif keyNum == ord('w'):
destination = os.path.join(new_path1, img_name)
shutil.copy(img_path, destination)
elif keyNum == ord('e'):
destination = os.path.join(new_path2, img_name)
shutil.copy(img_path, destination)
elif keyNum == ord('r'):
destination = os.path.join(new_path3, img_name)
shutil.copy(img_path, destination)
else:
continue
cv2.destroyAllWindows()
print(x)
x += 1
print('完成{}文件筛选'.format(file))
if __name__ == '__main__':
main()