본문 바로가기
JavaScript

[JavaScript]TensorFlow.js로 고양이 이미지 판별 앱 만들기

by teamnova 2025. 2. 4.
728x90

안녕하세요!

오늘은 TensorFlow.js를 사용하여 이미지를 입력받고, 해당 이미지에 고양이가 있는지 판단하는 간단한 웹 애플리케이션을 만들어보겠습니다.

이 글에서는 사전학습된 MobileNet 모델을 사용하겠습니다.

 

Index.html

사용자 인터페이스를 만들기 위해 index.html 파일을 작성합니다.

이 파일은 사용자가 이미지를 업로드하고 결과를 확인할 수 있는 화면을 제공합니다.

TensorFlow.js와 MobileNet 라이브러리를 CDN 링크를 통해 가져옵니다.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>고양이 이미지 판별</title>
  <!-- TensorFlow.js 라이브러리 추가 -->
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet"></script>
  <style>
    /* 기본 스타일 */
    body {
      font-family: Arial, sans-serif;
      text-align: center;
      margin: 20px;
    }
    img {
      max-width: 300px;
      margin-top: 20px;
    }
    #result {
      font-size: 18px;
      margin-top: 20px;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <h1>고양이 이미지 판별</h1>
  <p>이미지를 업로드하면 해당 이미지에 고양이가 있는지 판단합니다.</p>

  <!-- 이미지 업로드 입력 -->
  <input type="file" id="imageUpload" accept="image/*">
  
  <!-- 업로드된 이미지를 표시할 공간 -->
  <div>
    <img id="uploadedImage" src="" alt="Uploaded Image">
  </div>
  
  <!-- 결과 출력 -->
  <div id="result">결과가 여기에 표시됩니다.</div>

  <!-- JavaScript 파일 연결 -->
  <script src="script.js"></script>
</body>
</html>

 

script.js

이제 TensorFlow.js를 활용하여 이미지를 분석하는 script.js 파일을 작성합니다. 이 파일은 업로드된 이미지를 MobileNet 모델로 분석하고 결과를 화면에 표시합니다.

// MobileNet 모델 변수
let model;

// 1. MobileNet 모델 로드
window.onload = async () => {
  // 결과 영역에 모델 로드 메시지 표시
  document.getElementById('result').innerText = '모델을 로드 중입니다...';

  // MobileNet 모델 로드
  model = await mobilenet.load();

  // 모델 로드 완료 메시지 표시
  document.getElementById('result').innerText = '모델이 로드되었습니다. 이미지를 업로드하세요!';
};

// 2. 이미지 업로드 이벤트 처리
document.getElementById('imageUpload').addEventListener('change', async (event) => {
  const file = event.target.files[0]; // 업로드된 파일 가져오기

  // 파일이 선택되지 않았을 경우
  if (!file) {
    document.getElementById('result').innerText = '이미지를 업로드해주세요.';
    return;
  }

  // 업로드된 이미지를 화면에 표시
  const imgElement = document.getElementById('uploadedImage');
  imgElement.src = URL.createObjectURL(file);

  // 이미지가 로드되면 모델로 예측
  imgElement.onload = async () => {
    // MobileNet 모델로 이미지 분류
    const predictions = await model.classify(imgElement);

    // 예측 결과 출력 (콘솔에서 확인 가능)
    console.log(predictions);

    // 고양이와 관련된 키워드
    const catKeywords = ['cat', 'kitten', 'feline'];

    // 예측 결과에 고양이 키워드가 포함되어 있는지 확인
    const isCat = predictions.some(prediction =>
      catKeywords.some(keyword => prediction.className.toLowerCase().includes(keyword))
    );

    // 결과를 화면에 표시
    const resultElement = document.getElementById('result');
    if (isCat) {
      resultElement.innerText = '고양이가 감지되었습니다! 🐱';
    } else {
      resultElement.innerText = '고양이가 감지되지 않았습니다. 😿';
    }
  };
});