Automatic image extraction from bulk folders with Python

This script is used to extract images from a bulk image folder using the image paths. The main objective of the script is to pick images listed in a text file and move them to a different folder.

Importing the required libraries, os, and shutil, which are used for creating directories and copying files, respectively. Then, it creates a directory named “outimg” using os.makedirs() method.

Fetch image.py

import os
import shutil

out_folder = "outimg"
os.makedirs(out_folder, exist_ok=True)

def list_using_move_required_image(imglist):
    for il in imglist:
        shutil.copy(il, out_folder)

def fetch_image_list(txtfile):
    with open(txtfile, "r") as file:
        list = file.read()
        list = list.split("\n")
        new_imglist = []
        for li in list:
            li = li.split(" ")
            new_imglist.append(li[0])
        list_using_move_required_image(new_imglist)

if __name__ == "__main__":
    image_list_txt = "../assets/train.txt"
    fetch_image_list(image_list_txt)


train.txt Example

/media/y/dataset/person/WIN_20220228_16_51_25_Pro240.jpg 273,54,670,713,0
....
....

The script defines two functions:

  • This code is a useful script that helps to extract specific images from a large folder of images. The script has two functions: “list_using_move_required_imge” and “fetch_image_list.”
  • The first function, “list_using_move_required_imge,” takes a list of image paths as input and copies the images to a designated directory named “outimg” using the “shutil.copy()” method.
  • The second function, “fetch_image_list,” reads a text file that contains a list of required images. It then separates the contents of the file by newline characters and removes any unnecessary spaces between the image paths and corresponding labels.
  • The list of image paths is then passed to the “list_using_move_required_imge” function, which copies the required images to the designated directory.

Conclusion :

In summary, this script is a handy tool for extracting required images from a large collection of images. The user can create a list of required images in a text file and run the script to copy only those images to a different directory, thus saving time and effort in manually searching and copying images.

Reference links:

https://docs.python.org/3/library/shutil.html#

Leave a Reply