본문 바로가기
소프트웨어/자바스크립트

[자바스크립트] Node.js - 하위경로 이미지 파일의 경로 읽기

by 만들오 2021. 1. 23.

Tensorflow.js를 이용한 이미지 분류기를 학습시키기 위해서는 가장 먼저 데이터셋을 만들어야 합니다.

저는 사용할 스크립트(index.js)와 동일한 위치에 shapes 라는 이름의 폴더를 만들고,

다음과 같이 디렉토리를 구성하여 학습 자료로 사용했습니다.

 

- ./shapes/circle/circle001~020.png

- ./shapes/triangle/triangle001~020.png

- ./shapes/rectangle/rectangle001~020.png

 

총 3종류의 클래스(circle, triangle, rectangle)가 있고 각각 20개의 이미지 파일을 가지고 있습니다.

제가 사용한 스크립트는 시작할 폴더위치(shapes)를 지정하면 하위 폴더(circle, triangle, rectangle)를 찾고,

그 안에 있는 .png 파일의 경로를 저장하는 스크립트 입니다.

하위 폴더(circle, triangle, rectangle)의 갯수는 적거나 많아도 상관이 없지만, 모두 shapes 안의 폴더여야만 합니다.

const path = require('path')
const fs = require('fs')

function getImgPath(startPath, fileExt) {
    const dirName = fs.readdirSync(startPath, { withFileTypes: true }).filter(dirent => dirent.isDirectory()).map(dirent => dirent.name);
    const imgPath = [];
    dirName.forEach(name => {
        const filePath = path.join(startPath, name);
        const fileName = fs.readdirSync(filePath).filter((file) => file.endsWith(fileExt));
        fileName.forEach(file => {
            const fullPath = path.join(startPath, name, file);
            imgPath.push(fullPath);
        });
    });
    return imgPath;
}

async function run(){
    const imagePath = getImgPath('shapes', 'png')
    imagePath.forEach(path => console.log(path))
}
run()

* 이 글은 티스토리 카카오계정 연동정책으로 인해 이전 블로그(오코취) 글을 옮겨왔습니다.

[].

728x90

댓글