본문 바로가기
Python for Beginners

15.3 컴퓨터 비전(CNN)

by Andrew's Akashic Records 2023. 5. 2.
728x90

컴퓨터 비전은 이미지와 비디오에서 유용한 정보를 자동으로 추출하는 기술입니다. 컨볼루션 신경망(Convolutional Neural Networks, CNN)은 이미지 인식 및 분류와 같은 컴퓨터 비전 작업에 탁월한 성능을 보이는 딥러닝 모델입니다. CNN은 지역적인 정보를 인식하고 학습하는 데 효과적인 컨볼루션 레이어와 풀링 레이어를 사용하여 이미지의 특징을 추출합니다.

다음은 TensorFlow와 Keras를 사용하여 간단한 CNN 모델을 구성하고 학습시키는 예제 코드입니다. 이 예제에서는 CIFAR-10 데이터셋을 사용하여 이미지 분류를 수행합니다.

import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical

# 데이터 불러오기 및 전처리
(train_images, train_labels), (test_images, test_labels) = cifar10.load_data()
train_images = train_images / 255.0
test_images = test_images / 255.0
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

# CNN 모델 구성
model = models.Sequential([
    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.Flatten(),
    layers.Dense(64, activation='relu'),
    layers.Dense(10, activation='softmax')
])

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

# 모델 학습
model.fit(train_images, train_labels, epochs=10, batch_size=32)

# 모델 평가
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)

이 코드는 다음과 같은 작업을 수행합니다:

1. CIFAR-10 데이터셋을 불러오고 정규화합니다.
2. 컨볼루션 레이어(Conv2D)와 풀링 레이어(MaxPooling2D)를 사용하여 CNN 모델을 구성합니다.
3. 모델을 컴파일하고 학습시킵니다.
4. 학습된 모델을 테스트 데이터셋으로 평가합니다.

CNN은 다양한 컴퓨터 비전 작업에 적용될 수 있습니다. 예를 들어, 객체 인식, 이미지 세분화, 이미지 생성 등과 같은 다양한 문제를 해결할 수 있습니다. CNN을 사용하면 이미지의 복잡한 패턴과 구조를 효과적으로 학습할 수 있으며, 이를 통해 컴퓨터 비전 작업의 성능을 크게 향상시킬 수 있습니다.

다음은 Keras와 TensorFlow를 사용하여 이미지 세분화(Image Segmentation)를 수행하는 U-Net 모델을 구성하는 예제입니다.

import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical

def unet_model(input_shape):
    inputs = layers.Input(input_shape)
    conv1 = layers.Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(inputs)
    conv1 = layers.Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv1)
    pool1 = layers.MaxPooling2D(pool_size=(2, 2))(conv1)

    # ... 중간 생략 ...

    conv9 = layers.Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv8)
    conv9 = layers.Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv9)
    conv10 = layers.Conv2D(1, 1, activation='sigmoid')(conv9)

    model = models.Model(inputs=inputs, outputs=conv10)

    return model

# U-Net 모델 생성 및 컴파일
model = unet_model(input_shape=(256, 256, 3))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

U-Net 모델은 일반적으로 의료 영상 및 위성 영상 등에서 세분화 작업에 사용되며, 컨볼루션 레이어와 업샘플링 레이어를 사용하여 이미지의 픽셀 수준에서 클래스 레이블을 예측합니다. 이 모델은 U자 형태의 구조를 갖고 있으며, 이를 통해 이미지의 전역적인 정보와 지역적인 정보를 모두 활용하여 세분화를 수행합니다.

이와 같이, CNN은 다양한 컴퓨터 비전 작업에서 사용할 수 있는 강력한 도구입니다. 딥러닝 프레임워크인 TensorFlow와 Keras를 사용하여 여러 가지 CNN 구조를 구성하고 학습시킬 수 있으며, 이를 통해 컴퓨터 비전 관련 문제를 효과적으로 해결할 수 있습니다.

728x90

'Python for Beginners' 카테고리의 다른 글

15.5 강화학습 기반 딥러닝(DQN, A3C 등)  (0) 2023.05.02
15.4 자연어 처리(NLP, RNN, LSTM, Transformer)  (0) 2023.05.02
15.2 텐서플로와 케라스  (0) 2023.05.02
15.1 딥러닝 소개  (0) 2023.04.27
14.5 강화학습  (0) 2023.04.25