본문 바로가기

명사 美 비격식 (무리 중에서) 아주 뛰어난[눈에 띄는] 사람[것]

Personal/SK 네트웍스 AI 캠프

SK 네트웍스 AI 캠프 - 3_초거대언어모델(LLM) - Day55_멀티모달 AI Image Captioning과 Stable Diffusion

이미지 캡셔닝 Image Captioning

컴퓨터가 이미지를 이해하고 자연어 문장으로 설명하는 인공지능 기술

대표모델로는 Show and Tell, Show Attend and Tell, ViT-GPT2, BLIP, BLIP-2, Florence, GPT-4o Vision 이있다. 

 

 

Show and Tell

CNN + LSTM 구조의 가장 대표적인 이미지 캡셔닝 모델 CNN이 이미지를 특정 벡터로 변환하고 LSTM이 한단어씩 문장을 생성한다.

import torch
import torch.nn as nn

# CNN이 추출한 이미지 특징
image_feature = torch.randn(1, 2048)

# LSTM
lstm = nn.LSTM(
    input_size=2048,
    hidden_size=512,
    batch_first=True
)

# 문장 생성 시작
output, _ = lstm(image_feature.unsqueeze(1))

print(output.shape)

https://standout.tistory.com/1744

 

CNN 이란?: CNN Concolutional Neural Network 합성곱 신경망, 이미지의 특징을 자동으로 찾자!

CNN Concolutional Neural Network 합성곱 신경망이미지, 영상, 패턴인식에 사용된다. 기존 신경망은 이미지 처리에 비효율적이었다 .고양이 사진을 숫자로 펼치면 수십만개 픽셀이 되고 일반신경망은 파

standout.tistory.com

https://standout.tistory.com/1842

 

RNN 순환신경망의 한 종류, LSTM이란?: 장기 의존성 문제를 해결하기 위해 개발된 딥러닝 모델 (feat.

LSTM(Long Short-Term Memory)RNN(Recurrent Neural Network, 순환 신경망)의 한 종류장기 의존성(Long-Term Dependency) 문제를 해결하기 위해 개발된 딥러닝 모델from tensorflow.keras.models import Sequentialfrom tensorflow.keras.laye

standout.tistory.com

 

 

Show Attend and Tell

Attention을 추가해 이미지의 중요한 영역을 보면서 문장을 생성

import torch
import torch.nn as nn

image_feature = torch.randn(1, 196, 512)

attention = nn.MultiheadAttention(
    embed_dim=512,
    num_heads=8,
    batch_first=True
)

query = torch.randn(1, 1, 512)

context, weights = attention(
    query=query,
    key=image_feature,
    value=image_feature
)

print(context.shape)
print(weights.shape)

https://standout.tistory.com/1846

 

Attention 메커니즘만을 이용하여 문장을 처리하는 딥러닝 모델 Transformer (feat.Self-Attention, Multi-Head A

Attention기계번역에서 현재 단어 하나만 보는게 아니라 주변 단어 전체를 함께 고려해 번역하는것이 Seq2Seq 모델의 가장 큰 개선점이었다. Query, Key, Value 세가지 벡터를 이용해 현재 필요한 정보가

standout.tistory.com

 

 

 

ViT-GPT2

Vision Transformer와 GPT-2를 결합한 Transformer 기반 캡셔닝 모델

from transformers import VisionEncoderDecoderModel
from transformers import ViTImageProcessor
from transformers import AutoTokenizer
from PIL import Image

model = VisionEncoderDecoderModel.from_pretrained(
    "nlpconnect/vit-gpt2-image-captioning"
)

processor = ViTImageProcessor.from_pretrained(
    "nlpconnect/vit-gpt2-image-captioning"
)

tokenizer = AutoTokenizer.from_pretrained(
    "nlpconnect/vit-gpt2-image-captioning"
)

image = Image.open("dog.jpg")

pixel_values = processor(
    images=image,
    return_tensors="pt"
).pixel_values

output = model.generate(pixel_values)

caption = tokenizer.decode(
    output[0],
    skip_special_tokens=True
)

print(caption)

https://standout.tistory.com/1846

 

Attention 메커니즘만을 이용하여 문장을 처리하는 딥러닝 모델 Transformer (feat.Self-Attention, Multi-Head A

Attention기계번역에서 현재 단어 하나만 보는게 아니라 주변 단어 전체를 함께 고려해 번역하는것이 Seq2Seq 모델의 가장 큰 개선점이었다. Query, Key, Value 세가지 벡터를 이용해 현재 필요한 정보가

standout.tistory.com

https://standout.tistory.com/1877

 

GPT (Generative Pre-trained Transformer) , Decoder-Only Transformer: Transformer의 Decoder만 사용하는 언어모델, GPT-1

GPT (Generative Pre-trained Transformer)GPT는 언어모델에 속하는 인공지능 모델이다 OpenAI 는 GPT 를 지속적으로 발전시켜 더욱 뛰어난 모델을 출시하고 있다. 이미지를 이해하는 멀티모달기능, 인식능력향

standout.tistory.com

 

 

BLIP

Vision Transformer과 Text Transformer를 함께 사전학습한 멀티모달 모델

from transformers import BlipProcessor
from transformers import BlipForConditionalGeneration
from PIL import Image

processor = BlipProcessor.from_pretrained(
    "Salesforce/blip-image-captioning-base"
)

model = BlipForConditionalGeneration.from_pretrained(
    "Salesforce/blip-image-captioning-base"
)

image = Image.open("dog.jpg")

inputs = processor(
    image,
    return_tensors="pt"
)

output = model.generate(**inputs)

caption = processor.decode(
    output[0],
    skip_special_tokens=True
)

print(caption)

 

 

BLIP-2

Vision Encoder + Q-Former + LLM 구조

Query Transformer 가 추가된것이 가장 큰 차이

Q-Forlmer는 이미지 특징을 LLM이 이해하기 쉬운 형태로 변환하는 역할을한다. 

from transformers import Blip2Processor
from transformers import Blip2ForConditionalGeneration
from PIL import Image

processor = Blip2Processor.from_pretrained(
    "Salesforce/blip2-opt-2.7b"
)

model = Blip2ForConditionalGeneration.from_pretrained(
    "Salesforce/blip2-opt-2.7b"
)

image = Image.open("dog.jpg")

inputs = processor(
    images=image,
    return_tensors="pt"
)

generated_ids = model.generate(**inputs)

caption = processor.decode(
    generated_ids[0],
    skip_special_tokens=True
)

print(caption)

 

 

 

Florence

Microsoft의 범용 Vision Foundation Model 캡셔닝, OCR, 객체탐지, VQA 등 다양한 작업을 하나의 모델로 수행할 수 있다.

from transformers import AutoProcessor
from transformers import AutoModelForCausalLM
from PIL import Image

processor = AutoProcessor.from_pretrained(
    "microsoft/Florence-2-base"
)

model = AutoModelForCausalLM.from_pretrained(
    "microsoft/Florence-2-base"
)

image = Image.open("dog.jpg")

inputs = processor(
    text="<CAPTION>",
    images=image,
    return_tensors="pt"
)

generated = model.generate(**inputs)

caption = processor.batch_decode(
    generated,
    skip_special_tokens=True
)[0]

print(caption)

 

 

 

GPT-4o Vision

LLM 기반 멀티모델로 이미지를 이해하고 자연어로 설명한다.

from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-4.1",
    input=[{
        "role": "user",
        "content": [
            {
                "type": "input_text",
                "text": "이 이미지를 설명해줘."
            },
            {
                "type": "input_image",
                "image_url": "https://example.com/dog.jpg"
            }
        ]
    }]
)

print(response.output_text)

 

 

 

모델핵심 구조특징

Show and Tell CNN + LSTM 이미지 특징으로 문장을 순차 생성하는 초기 캡셔닝 모델
Show Attend and Tell CNN + Attention + LSTM Attention으로 중요한 이미지 영역을 선택하며 문장 생성
ViT-GPT2 ViT + GPT-2 Transformer 기반으로 CNN/LSTM을 대체한 구조
BLIP ViT + Text Transformer + Fusion 이미지와 텍스트를 함께 사전학습하여 다양한 멀티모달 작업 수행
BLIP-2 Vision Encoder + Q-Former + LLM Q-Former가 이미지 특징을 LLM에 연결하여 효율적으로 활용
Florence Vision Foundation Model 하나의 모델로 캡셔닝, OCR, 객체 탐지, VQA 등 다양한 비전 작업 수행
GPT-4o Vision Multimodal LLM 이미지 이해와 자연어 생성이 통합되어 대화형 이미지 설명, 추론, 질의응답까지 지원

 

 

 

Stable Diffution

텍스트 프롬프트를 입력받아 새로운 이미지를 생성하는 생성형 AI 모델이다 .

from diffusers import StableDiffusionPipeline
import torch

pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16
)

pipe = pipe.to("cuda")

image = pipe(
    "A cute cat wearing glasses"
).images[0]

image.save("cat.png")

 

 

주요구성 요소로 Text Encoder, Latent Space, UNet, VAE가 있다. 

고품질 이미지를 생성하고 다양한 스타일을 표현하는 텍스트 기반 생성 이미지 편집, 인페이팅, 아웃페인팅 모델이며 로컬 환경에서도실행이 가능하다. 다양한 오픈소스 모델과 확장성이 좋다. 

핵심은 이미지를 직접 생성하지 않고, 잠재 공간(Latent Space)에서 노이즈를 제거(Denoising)하여 이미지를 생성한다

#Text Encoder 텍스트 프롬프트를 의미 벡터(Embedding)로 변환

from transformers import CLIPTokenizer
from transformers import CLIPTextModel

tokenizer = CLIPTokenizer.from_pretrained(
    "openai/clip-vit-large-patch14"
)

text_encoder = CLIPTextModel.from_pretrained(
    "openai/clip-vit-large-patch14"
)

prompt = "A cute cat wearing glasses"

inputs = tokenizer(
    prompt,
    return_tensors="pt"
)

embedding = text_encoder(**inputs).last_hidden_state

print(embedding.shape)
# UNet 노이즈 제거
from diffusers import UNet2DConditionModel
import torch

unet = UNet2DConditionModel.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    subfolder="unet"
)

latent = torch.randn(1, 4, 64, 64)

text_embedding = torch.randn(1, 77, 768)

noise_pred = unet(
    latent,
    timestep=500,
    encoder_hidden_states=text_embedding
).sample

print(noise_pred.shape)
# VAE (Variational AutoEncoder) 잠재 공간(Latent)을 실제 이미지로 복원
from diffusers import AutoencoderKL

vae = AutoencoderKL.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    subfolder="vae"
)

latent = torch.randn(1, 4, 64, 64)

image = vae.decode(latent).sample

print(image.shape)

 

Text Encoder (CLIP) 프롬프트를 의미 벡터로 변환 텍스트 Text Embedding
Latent Space 이미지를 압축된 잠재 표현으로 저장하고 생성 수행 노이즈 또는 잠재 벡터 Latent Feature
UNet 노이즈를 반복적으로 제거하며 잠재 이미지를 생성 Latent + Text Embedding Denoised Latent
VAE (Encoder/Decoder) 이미지↔잠재 공간 변환 Latent 또는 이미지 이미지 또는 Latent

 

 

핵심 아이디어는 픽셀 공간에서 직접 이미지를 생성하지 않고, 압축된 잠재 공간(Latent Space)에서 UNet이 노이즈를 점진적으로 제거한 뒤, 마지막에 VAE Decoder가 이를 고해상도 이미지로 복원한다는 것입니다. 이는 계산량을 크게 줄이면서도 높은 품질의 이미지를 생성할 수 있게 해주는 Stable Diffusion의 핵심 원리