본문 바로가기

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

이론

이미지 캡셔닝 Image Captioning: Show and Tell, Show Attend and Tell, ViT-GPT2, BLIP, BLIP-2, Florence, GPT-4o Vision

이미지 캡셔닝 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 이미지 이해와 자연어 생성이 통합되어 대화형 이미지 설명, 추론, 질의응답까지 지원