Home > Net >  create a list of images and text files in Python
create a list of images and text files in Python

Time:11-06

I have a folder (exp) that has 800 images and 800 text files inside another folder (labels). Each image has text file. How to create a list that has an image and a corresponding text file?

the folder looks like this:

-exp
  -labels
      FrameVid2_178.txt
      Frame_1103.txt
      Frame_856.txt
      ...
      ...
  FrameVid2_178.JPG
  Frame_1103.JPG
  Frame_856.JPG
  ...
  ...

The list should look like this:

[['../exp/FrameVid2_178.JPG', 'FrameVid2_178.txt'],
 ['../exp/Frame_1103.JPG', 'Frame_1103.txt'],
 ['../exp/Frame_856.JPG', 'Frame_856.txt'],
  .....]

My code:

def __init__(self):
        self.imgs_path = "../exp/"
        file_list = glob.glob(self.imgs_path   "*")
        self.data = []     
        for class_path in file_list:
            class_name = class_path.split("/")[-1]
            for img_path in glob.glob(class_path):
                self.data.append([img_path, class_name])
        print(self.data)
        self.img_dim = (416, 416)

CodePudding user response:

Your code should work, not sure where you ran into trouble, but it could use a little checking/handling (note: you could do a lot more path validation/checking too, pathlib.Path is great for that).

def __init__(self, img_path):
        self.imgs_path = "../exp/"
        file_list = glob.glob(self.imgs_path   "*.JPG")
        self.data = []     
        for class_path in file_list:
            class_name = class_path.split("/")[-1]
            matching_labels = list(glob.glob(class_path   "/labels/"   class_name[:-3]   "*"))
            if len(matching_labels) != 1:
                raise IOError("Matching issue", len(matching_labels))
            self.data.append([img_path, matching_labels[0].split("/")[-1])
        print(self.data)
        self.img_dim = (416, 416)
  • Related