Cloud AI - 5. 최종 프로젝트: 클라우드 AI를 활용한 나만의 AI 서비스 만들기 (AI 기반 이미지 분류 앱 개발)

2025. 3. 18. 22:30AI/AI

📌 AI 기반 이미지 분류 앱 개발

AI 기반 이미지 분류(Image Classification)는 컴퓨터 비전(Computer Vision) 기술 중 하나로, 주어진 이미지가 특정 클래스(카테고리)에 속하는지를 자동으로 판별하는 기능을 수행한다.
이 앱에서는 딥러닝 모델을 활용하여 이미지 데이터를 분석하고, 자동으로 분류하는 시스템을 구축한다.


🔹 1️⃣ AI 기반 이미지 분류 개요

✅ 이미지 분류란?

이미지 분류는 컴퓨터가 이미지를 보고 해당 이미지가 어떤 범주(Category)에 속하는지 판별하는 AI 기술이다.
일반적으로 CNN(Convolutional Neural Network)과 같은 딥러닝 모델이 사용되며, AI 모델이 훈련된 데이터를 기반으로 이미지의 특성을 분석하여 클래스(class)를 예측한다.

이미지 분류의 주요 활용 사례

분야  활용 예시
의료 X-ray, MRI 이미지 분석하여 질병 진단
자율주행 도로 표지판 및 보행자 감지
보안 및 감시 얼굴 인식 및 이상 행동 감지
전자상거래 제품 이미지 기반 자동 카테고리 분류
농업 작물 질병 감지 및 농산물 품질 판별

이미지 분류 시스템의 기본 원리
1️⃣ 데이터 수집: 이미지 데이터를 수집 및 라벨링 (예: 고양이 vs 강아지)
2️⃣ 데이터 전처리: 이미지 크기 조정, 정규화, 데이터 증강(Data Augmentation)
3️⃣ 모델 학습: CNN, ResNet, MobileNet 등 모델을 사용하여 학습
4️⃣ 모델 배포: 클라우드 또는 로컬 환경에서 API 서비스로 제공
5️⃣ 예측 및 평가: 새로운 이미지 입력 시 적절한 클래스 예측


🔹 2️⃣ AI 이미지 분류 모델 구축 (TensorFlow & Google AutoML 활용)

✅ TensorFlow 기반 이미지 분류 모델 개발

TensorFlow 및 Keras를 사용하여 간단한 CNN 모델을 구축할 수 있다.

1️⃣ 필요한 라이브러리 설치

pip install tensorflow numpy matplotlib

2️⃣ CNN 모델을 사용한 이미지 분류 모델 코드

import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt

# 데이터셋 로드 (MNIST 손글씨 데이터)
mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# 데이터 전처리 (reshape 추가)
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1)
test_images = test_images.reshape(test_images.shape[0], 28, 28, 1)
train_images, test_images = train_images / 255.0, test_images / 255.0

# CNN 모델 정의
model = keras.Sequential([
    keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)),
    keras.layers.MaxPooling2D(2,2),
    keras.layers.Flatten(),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10, activation='softmax')
])

# 모델 컴파일
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# 모델 학습
model.fit(train_images, train_labels, epochs=5)

# 모델 평가
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f"Test Accuracy: {test_acc}")

이 코드를 실행하면 CNN 기반 이미지 분류 모델을 학습할 수 있다.


✅ Google AutoML Vision을 활용한 이미지 분류 모델 구축

Google AutoML Vision은 코드 없이 이미지 분류 모델을 쉽게 학습 및 배포할 수 있는 Google Cloud AI 서비스이다.

1️⃣ Google Cloud AutoML Vision 활성화

gcloud auth login
gcloud config set project [PROJECT_ID]
gcloud services enable automl.googleapis.com

2️⃣ AutoML Vision 데이터셋 업로드 및 모델 학습

from google.cloud import automl_v1

# AutoML Vision 클라이언트 생성
client = automl_v1.AutoMlClient()

# 데이터셋 생성
project_id = "your-project-id"
location = "us-central1"
dataset_display_name = "image_classification_dataset"

dataset = client.create_dataset(
    parent=f"projects/{project_id}/locations/{location}",
    dataset=automl_v1.Dataset(
        display_name=dataset_display_name,
        image_classification_dataset_metadata=automl_v1.ImageClassificationDatasetMetadata(),
    ),
)
print(f"Dataset name: {dataset.name}")

Google AutoML Vision을 사용하면 모델 학습을 자동으로 진행할 수 있다.


🔹 3️⃣ AI 모델 배포 및 앱 개발

✅ Google Cloud Functions를 활용한 AI API 자동화

모델을 학습한 후, Google Cloud Functions를 활용하여 API로 배포할 수 있다.

1️⃣ Google Cloud Functions 활성화

gcloud services enable cloudfunctions.googleapis.com

2️⃣ AutoML Vision 모델을 호출하는 API 생성

from google.cloud import automl_v1
import functions_framework

project_id = "your-project-id"
model_id = "your-model-id"
prediction_client = automl_v1.PredictionServiceClient()
model_name = f"projects/{project_id}/locations/us-central1/models/{model_id}"

@functions_framework.http
def predict(request):
    """Google AutoML Vision을 호출하는 API"""
    request_json = request.get_json()
    image_content = request_json.get("image_bytes")

    # AutoML 예측 요청
    payload = {"image": {"image_bytes": image_content}}
    response = prediction_client.predict(name=model_name, payload=payload)

    return {"prediction": response.payload}

Cloud Functions를 활용하면 모델을 쉽게 API로 배포 가능

3️⃣ Google Cloud Functions 배포

gcloud functions deploy predict \
  --runtime python39 \
  --trigger-http \
  --allow-unauthenticated

📌 최종 정리: AI 기반 이미지 분류 앱 개발

✅ 이미지 분류 모델 구축

1️⃣ CNN 기반 TensorFlow 모델 구축 (MNIST 데이터 reshape 추가)
2️⃣ Google AutoML Vision을 활용한 모델 학습 및 배포

✅ AI 모델 배포 및 운영

1️⃣ Google Cloud Functions를 활용하여 서버리스 배포
2️⃣ AutoML Vision API를 호출하여 이미지 분류 실행

AI 기반 이미지 분류 앱을 개발하면, 의료, 자율주행, 보안, 전자상거래 등 다양한 산업에서 활용 가능! 🚀