Обрезать несколько изображений из папки, если имя изображения соответствует image_id в CSV-файле в Python - PullRequest
0 голосов
/ 27 сентября 2019

У меня есть список из примерно 300 image_id и положения ограничительной рамки в CSV-файле.У меня также есть папка, содержащая около 300 изображений, каждый из которых соответствует имени каждого изображения.Как мне сравнить имя изображения и image_id, если оно мне подходит, я его обрежу.

Я использую язык Python и Ubuntu OS.

Мое имя изображения в папке:

1693884003.jpg
1693884030.jpg
1735837028.jpg
1740301012.jpg
1779624112.jpg

Мои данные в CSV-файле:

image_id    bounding_box
1693884003  {'right': 0.6428571428571429, 'bottom': 0.9761904761904762, 'top': 0.38095238095238093, 'left': 0.22857142857142856}
1693884030  {'right': 0.6571428571428571, 'bottom': 0.9285714285714286, 'top': 0.38095238095238093, 'left': 0.3142857142857143}
1735837028  {'right': 0.68, 'bottom': 0.9, 'top': 0.4, 'left': 0.34}
1740301012  {'right': 0.6142857142857143, 'bottom': 0.9523809523809523, 'top': 0.38095238095238093, 'left': 0.35714285714285715}
1779624112  {'right': 0.7142857142857143, 'bottom': 0.9047619047619048, 'top': 0.5357142857142857, 'left': 0.21428571428571427}

Ответы [ 2 ]

0 голосов
/ 27 сентября 2019

По моему мнению, вы могли бы использовать метод json.loads

In [23]: from json import loads 
    ...:  
    ...: data = '''\ 
    ...: 1693884003  {'right': 0.6428571428571429, 'bottom': 0.9761904761904762, 'top': 0.38095238095238093, 'left': 0.22857142857142856} 
    ...: 1693884030  {'right': 0.6571428571428571, 'bottom': 0.9285714285714286, 'top': 0.38095238095238093, 'left': 0.3142857142857143} 
    ...: 1735837028  {'right': 0.68, 'bottom': 0.9, 'top': 0.4, 'left': 0.34} 
    ...: 1740301012  {'right': 0.6142857142857143, 'bottom': 0.9523809523809523, 'top': 0.38095238095238093, 'left': 0.35714285714285715} 
    ...: 1779624112  {'right': 0.7142857142857143, 'bottom': 0.9047619047619048, 'top': 0.5357142857142857, 'left': 0.21428571428571427}\ 
    ...: ''' 
    ...: images = {} 
    ...: for line in data.splitlines(): 
    ...:     image, bounds = line.split(' ', 1) 
    ...:     images[image] = loads(bounds.replace("'", '"')) 
    ...: from pprint import pprint 
    ...: pprint(images) 
{'1693884003': {'bottom': 0.9761904761904762,                                                                                             
                'left': 0.22857142857142856,                                                                                              
                'right': 0.6428571428571429,                                                                                              
                'top': 0.38095238095238093},                                                                                              
 '1693884030': {'bottom': 0.9285714285714286,                                                                                             
                'left': 0.3142857142857143,
                'right': 0.6571428571428571,
                'top': 0.38095238095238093},
 '1735837028': {'bottom': 0.9, 'left': 0.34, 'right': 0.68, 'top': 0.4},
 '1740301012': {'bottom': 0.9523809523809523,
                'left': 0.35714285714285715,
                'right': 0.6142857142857143,
                'top': 0.38095238095238093},
 '1779624112': {'bottom': 0.9047619047619048,
                'left': 0.21428571428571427,
                'right': 0.7142857142857143,
                'top': 0.5357142857142857}}

In [24]: 

Обратите внимание, что я читаю из строки, а вы будете читать из открытого файла,
обратите внимание также, что json.loads ожидает двойные кавычки только в качестве разделителя, поэтому мы должны replace одинарные кавычки в ваших данных с двойными кавычками перед использованием json.loads.

0 голосов
/ 27 сентября 2019
import os, pandas

data = pandas.read_csv(your_csv_file) #read csv file

# Get the directory of images
path = "path folder"

#Edit2 you may have to add dtype str, as pandas will assume int if you only have integers
dirs = os.listdir( path, dtype=str ) #get all files in folder

# Get all the files and split at '.' to get the names
listoffiles = []
for file in dirs:
    basename = os.path.splitext(file)[0] #this will get you the basename 
    listoffiles.append(basename)         #you will have a list of all filenames

matches = data[data['image_id'].isin(listoffiles)] #now in matches you have a table containing only rows that correspond to filenames
print(matches.head()) 

Надеюсь, это поможет.

Редактировать: позже вы можете повторять совпадения, чтобы фактически выполнить обрезку:

for index, row in matches.iterrows():
     print(row['image_id'], row['bounding_box'])
     # do cropping here
...