[팀프로젝트] 이미지의 경로와 json 소분류 카테고리를 따로 저장해보자

반응형

라벨링 파일 JSON -> numpy array 

 

지난번에 다운받은 데이터들 중에서 sketch 데이터만 사용하기로 했다.

데이터의 크기가 너무 크기 때문에 카테고리가 '동식물'인 스케치 데이터로 범위를 축소했다.

 

training 이미지 데이터(.jpg), training 라벨링 데이터(.json), validation 이미지 데이터 , validation 라벨링 데이터

 

각 폴더에는 중분류 , 소분류로 나눠진 폴더가 세 겹으로 쌓여있다.

각 폴더들을 모두 탐색하여 json 파일의 소분류만 추출하여 데이터 프레임으로 만들었다.

 

이후에 모델링을 할 때 사용해야 하므로 데이터 프레임을 넘파이 배열로 저장했다.

import os
import json
import pandas as pd

# define the root directory where your folders are located
root_dir = '/home/minyoungxi/project/training_labels_L1_4/'

# initialize an empty list to store the category information
category_list = []

# iterate through each subdirectory in the root directory
for dir1 in os.listdir(root_dir):
    for dir2 in os.listdir(os.path.join(root_dir, dir1)):
        for dir3 in os.listdir(os.path.join(root_dir, dir1, dir2)):
            # check if the file is a json file
            if dir3.endswith('.json'):
                # load the json file
                with open(os.path.join(root_dir, dir1, dir2, dir3), encoding='utf-8-sig') as f:
                    data = json.load(f)
                # extract the category information
                category = data['category']['ctg_nm_level3']
                # add the category information to the list
                category_list.append(category)

# convert the list to a pandas DataFrame
df = pd.DataFrame({'category': category_list})

array = df.values

np.save = np.save('target_encoded_np', array)


이미지 파일 경로 -> numpy array

training 이미지 파일들의 경로를 추출하여 numpy array로 변환 후 저장하였다.

 

# Define the root path of the overlapping folders
root_path = "/home/minyoungxi/project/training_L1_4"

# Define a list to store the paths of the image files
image_paths = []

for folder1_name in os.listdir(root_path):
    folder1_path = os.path.join(root_path, folder1_name)
    if os.path.isdir(folder1_path):
        # Loop over each middle-level folder
        for folder2_name in os.listdir(folder1_path):
            folder2_path = os.path.join(folder1_path, folder2_name)
            if os.path.isdir(folder2_path):
                # Loop over each bottom-level folder
                for folder3_name in os.listdir(folder2_path):
                    file_path = os.path.join(folder2_path, folder3_name)
                    image_paths.append(file_path)
                    
                    
image_paths_array = np.array(image_paths)
np.save("/home/minyoungxi/project/train_np.npy", image_paths_array)

 

반응형