0

I have two directories:

dir1 = path/to/original/imgs

and

dir2 = path/to/subset/imgs

dir1 contains images from COCO dataset, and dir2 is currently empty. I also have a list which contains the names of some images (extracted from dir1):

list1 = ['img1', 'img2', 'img3', 'img4', 'img5'] 

What I need to do is compare the names of the images from list1 to the names of images in dir1 and save the matching images into dir2. Following is what I have until now:

import os
path_to_imgs = "/path/to/dir1"
path_to_subset_imgs = "/path/to/dir2"
file_list = os.listdir(path_to_imgs)
for img_name in list1:
    for filename in file_list:
        if img_name == filename:

I am unable to understand how to proceed with saving the identical images into dir2. I checked this link and this one. Any help is highly appreciated. Thank You.

Rahul Bohare
  • 762
  • 2
  • 11
  • 31
  • os.listdir returns filenames with extension, maybe you need to extract only the name ? `os.path.splitext()` can help – PRMoureu Oct 24 '17 at 06:19
  • I only need to compare two images based on their names, yes; I will give `os.path.splitext()` a try. But I still need to save the images with matching names in dir2. – Rahul Bohare Oct 24 '17 at 06:23

2 Answers2

1

You could consider using shutil

import shutil

image_list = ['img1', 'img2', 'img3', 'img4', 'img5'] 
dirs_list = [("/path/to/dir1/", "/path/to/dir2/")]

for img in image_list:
    for source_folder, destination_folder in dirs_list:
        shutil.copy(source_folder+img, destination_folder+img)
Van Peer
  • 2,127
  • 2
  • 25
  • 35
ayrusme
  • 506
  • 5
  • 17
1

first check if the image exists in the folder dir1 and the if it exists copy the image from the dir1 to dir2.

for img in list1:
    if os.path.exists(dir1+img):
        shutil.copy(dir1+img, dir2+img)
    else:
        print "Image %s doesn't exist"%img