[Python] import 기능, os 모듈

미남로그·2021년 10월 18일
1
post-thumbnail

os 부분은 해당 교재를 참고하여 정리했습니다.

교재 바로보기

import

  1. 모듈을 가져오는 import
import os
print(os.listdir())
  1. os 모듈에서 listdir 함수 가져오는 것
from os import listdir
print(listdir())
  1. 모듈 내의 모든 것을 가져오는 것
from os import *
print(dir())

해당 방식은 가급적 사용을 추천하지 않는다고 한다. 여러 모듈을 위와 같은 방식으로 가져오면 동일한 이름을 가진 함수에서 충돌이 발생하기도 한다.

os

os 모듈은 Operating System의 약자로서 운영체제에서 제공되는 여러 기능을 파이썬에서 수행할 수 있게 해줍니다.

예를 들어, 파이썬을 이용해 파일을 복사하거나 디렉터리를 생성하고 특정 디렉터리 내의 파일 목록을 구하고자 할 때 os 모듈을 사용하면 됩니다. os 모듈은 다양한 기능을 제공하는데 이 중 자주 사용되는 몇 가지만 살펴보겠습니다.

  1. 현재 경로 구하기 - getcwd
import os
os.getcwd()
  1. 특정 경로에 존재하는 파일과 디렉터리 목록 구하기 - listdir
os.listdir()
  • listdir 함수의 인자로 'c:/Anaconda3'을 전달
os.listdir('c:/Anaconda3')

listdir 함수의 인자로 특정 경로를 지정하는 경우 해당 경로에 있는 파일과 디렉터리 목록이 반환됩니다.

폴더 생성하기 - os 응용

os.path.exists 메서드로 해당 Directory가 없으면 Directory를 생성

import os

def createFolder(directory):
	try:
    		if not os.path.exists(directory):
            		os.mkdir(directory)
   	 except OSError:
     		print('Error: Creating directory.' + directory)
            
createFolder('/Users/....')

함수 구현

def parse_dataset(dataset, img_dir, total=0):
    if not os.path.exists(img_dir):
        os.mkdir(img_dir)
    # Dataset의 claas를 확인하여 class에 따른 index를 확인해둡니다.
    # 저는 기존의 class를 차와 사람으로 나누었습니다.
    type_class_map = {
        0: "car",
        1: "car",
        2: "car",
        3: "person",
        4: "person",
        5: "person",
    }
    # Keras retinanet을 학습하기 위한 dataset을 csv로 parsing하기 위해서 필요한 column을 가진 pandas.DataFrame을 생성합니다.
    df = pd.DataFrame(columns=["img_path", "x1", "y1", "x2", "y2", "class_name"])
    for item in tqdm(dataset, total=total):
        filename = item['image/file_name'].numpy().decode('utf-8')
        img_path = os.path.join(img_dir, filename)
        
        img = Image.fromarray(item['image'].numpy())
        img.save(img_path)
        object_bbox = item['objects']['bbox']
        object_type = item['objects']['type'].numpy()
        width, height = img.size
        
        # tf.dataset의 bbox좌표가 0과 1사이로 normalize된 좌표이므로 이를 pixel좌표로 변환합니다.
        x_min = object_bbox[:,1] * width
        x_max = object_bbox[:,3] * width
        y_min = height - object_bbox[:,2] * height
        y_max = height - object_bbox[:,0] * height
        
        # 한 이미지에 있는 여러 Object들을 한 줄씩 pandas.DataFrame에 append합니다.
        rects = np.stack([x_min, y_min, x_max, y_max], axis=1).astype(np.int)
        for i, _rect in enumerate(rects):
            _type = object_type[i]
            if _type not in type_class_map.keys():
                continue
            df = df.append({
                "img_path": img_path,
                "x1": _rect[0],
                "y1": _rect[1],
                "x2": _rect[2],
                "y2": _rect[3],
                "class_name": type_class_map[_type]
            }, ignore_index=True)
            
    return df

실전은 늘 어렵다...😑

profile
미남이 귀엽죠

0개의 댓글