Gemini로 이미지 생성하기

Gemini 2.0 Flash는 텍스트, 이미지 등 다양한 형식의 대답 생성을 지원합니다.

이미지 생성

이미지 생성(gemini-2.0-flash-preview-image-generation)을 위한 Gemini 2.0 Flash의 공개 프리뷰는 텍스트 외에도 이미지를 생성하는 기능을 지원합니다. 이렇게 하면 Gemini의 기능이 다음을 포함하도록 확장됩니다.

  • 일관성과 맥락을 유지하면서 자연어 대화를 통해 이미지를 반복적으로 생성하여 이미지를 조정합니다.
  • 긴 고품질 텍스트 렌더링으로 이미지를 생성합니다.
  • 인터리브 처리된 텍스트-이미지 출력을 생성합니다. 예를 들어 한 번에 텍스트와 이미지가 표시되는 블로그 게시물입니다. 이전에는 여러 모델을 연결해야 했습니다.
  • Gemini의 전 세계 지식 및 추론 기능을 사용하여 이미지를 생성합니다.

이 공개 실험 버전을 통해 Gemini 2.0 Flash는 1, 024픽셀 이미지를 생성할 수 있고, 사람의 이미지 생성 및 수정을 지원하며, 더 유연하고 제한적이지 않은 사용자 환경을 제공하는 업데이트된 안전 필터를 포함합니다.

다음과 같은 형식과 기능을 지원합니다.

  • 텍스트 이미지 변환

    • 프롬프트 예시: '배경에 불꽃놀이가 있는 에펠탑 이미지를 생성해 줘.'
  • 텍스트 이미지 변환(텍스트 렌더링)

    • 프롬프트 예시: '대형 건물의 시네마틱 사진을 생성해 줘. 건물 전면에 거대한 텍스트 프로젝션 '이제 Gemini 2.0으로 긴 형식의 텍스트를 생성할 수 있습니다.'라고 적어줘.'
  • 텍스트 이미지 변환 및 텍스트(인터리브 처리)

    • 프롬프트 예시: '파에야에 관한 그림이 있는 레시피를 생성해 줘. 레시피를 생성할 때 텍스트와 함께 이미지를 만들어 줘."
    • 프롬프트 예시: '3D 만화 애니메이션 스타일로 강아지에 관한 이야기를 만들어 줘. 각 장면에서 이미지를 생성합니다.'
  • 이미지 및 텍스트 이미지 변환 및 텍스트(인터리브 처리)

    • 프롬프트 예시: (가구가 완비된 방의 이미지 포함) "내 공간에 어떤 색상의 소파가 어울릴까? 이미지를 업데이트해 줘."
  • 이미지 편집(텍스트 및 이미지 간)

    • 프롬프트 예시: '이 이미지를 만화처럼 보이도록 수정해 줘.'
    • 프롬프트 예시: [고양이 이미지] + [베개 이미지] + '이 베개에 내 고양이 십자수를 만들어 줘.'
  • 멀티턴 이미지 편집(채팅)

    • 프롬프트 예시: [파란색 자동차 이미지를 업로드하세요.] '이 차를 컨버터블로 바꿔 줘.' '이제 색상을 노란색으로 바꿔 줘.'

제한사항:

  • 최상의 성능을 위해 다음 언어를 사용하세요. EN, es-MX, ja-JP, zh-CN, hi-IN
  • 이미지 생성은 오디오 또는 동영상 입력을 지원하지 않습니다.
  • 이미지 생성이 항상 트리거되지는 않을 수 있습니다.
    • 모델은 텍스트만 출력할 수도 있습니다. 이미지 출력을 명시적으로 요청해 보세요. 예를 들어 '진행하면서 이미지를 제공해 줘.'
    • 모델은 텍스트를 이미지로 생성할 수 있습니다. 텍스트 출력을 명시적으로 요청해 보세요. 예를 들어 '삽화와 함께 서술 텍스트를 생성해 줘.'
    • 모델이 생성을 중단할 수 있습니다. 다시 시도하거나 다른 프롬프트를 사용해 보세요.

이미지 생성

다음 섹션에서는 Vertex AI Studio 또는 API를 사용하여 이미지를 생성하는 방법을 설명합니다.

프롬프트에 관한 안내 및 권장사항은 멀티모달 프롬프트 설계를 참고하세요.

콘솔

이미지 생성을 사용하려면 다음 단계를 따르세요.

  1. Vertex AI Studio > 프롬프트 만들기를 엽니다.
  2. 모델 전환을 클릭하고 메뉴에서 gemini-2.0-flash-preview-image-generation을 선택합니다.
  3. 출력 패널의 드롭다운 메뉴에서 이미지 및 텍스트를 선택합니다.
  4. 프롬프트 작성 텍스트 영역에 생성하려는 이미지의 설명을 작성합니다.
  5. 프롬프트() 버튼을 클릭합니다.

Gemini가 설명을 기반으로 이미지를 생성합니다. 이 프로세스는 몇 초 정도 걸리지만 용량에 따라 비교적 느릴 수 있습니다.

Gen AI SDK for Python

설치

pip install --upgrade google-genai

자세한 내용은 SDK 참고 문서를 참조하세요.

Vertex AI에서 Gen AI SDK를 사용하도록 환경 변수를 설정합니다.

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import GenerateContentConfig, Modality
from PIL import Image
from io import BytesIO

client = genai.Client()

response = client.models.generate_content(
    model="gemini-2.0-flash-exp",
    contents=(
        "Generate an image of the Eiffel tower with fireworks in the background."
    ),
    config=GenerateContentConfig(response_modalities=[Modality.TEXT, Modality.IMAGE]),
)
for part in response.candidates[0].content.parts:
    if part.text:
        print(part.text)
    elif part.inline_data:
        image = Image.open(BytesIO((part.inline_data.data)))
        image.save("example-image.png")
# Example response:
#   A beautiful photograph captures the iconic Eiffel Tower in Paris, France,
#   against a backdrop of a vibrant and dynamic fireworks display. The tower itself...

REST

터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${API_ENDPOINT}:generateContent \
  -d '{
    "contents": {
      "role": "USER",
      "parts": { "text": "Create a tutorial explaining how to make a peanut butter and jelly sandwich in three easy steps."},
    },
    "generation_config": {
      "response_modalities": ["TEXT", "IMAGE"],
     },
     "safetySettings": {
      "method": "PROBABILITY",
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
  }' 2>/dev/null >response.json

Gemini가 설명을 기반으로 이미지를 생성합니다. 이 프로세스는 몇 초 정도 걸리지만 용량에 따라 비교적 느릴 수 있습니다.

이미지 수정

콘솔

이미지를 수정하려면 다음 단계를 따르세요.

  1. Vertex AI Studio > 프롬프트 만들기를 엽니다.
  2. 모델 전환을 클릭하고 메뉴에서 gemini-2.0-flash-preview-image-generation을 선택합니다.
  3. 출력 패널의 드롭다운 메뉴에서 이미지 및 텍스트를 선택합니다.
  4. 미디어 삽입 ()을 클릭하고 메뉴에서 소스를 선택한 다음 대화상자의 안내를 따릅니다.
  5. 프롬프트 작성 텍스트 영역에 이미지에 적용할 수정사항을 작성합니다.
  6. 프롬프트() 버튼을 클릭합니다.

Gemini가 설명을 기반으로 제공된 이미지의 수정된 버전을 생성합니다. 이 프로세스는 몇 초 정도 걸리지만 용량에 따라 비교적 느릴 수 있습니다.

Gen AI SDK for Python

설치

pip install --upgrade google-genai

자세한 내용은 SDK 참고 문서를 참조하세요.

Vertex AI에서 Gen AI SDK를 사용하도록 환경 변수를 설정합니다.

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import GenerateContentConfig, Modality
from PIL import Image
from io import BytesIO

client = genai.Client()

# Using an image of Eiffel tower, with fireworks in the background.
image = Image.open("example-image.png")

response = client.models.generate_content(
    model="gemini-2.0-flash-exp",
    contents=[image, "Edit this image to make it look like a cartoon."],
    config=GenerateContentConfig(response_modalities=[Modality.TEXT, Modality.IMAGE]),
)
for part in response.candidates[0].content.parts:
    if part.text:
        print(part.text)
    elif part.inline_data:
        image = Image.open(BytesIO((part.inline_data.data)))
        image.save("bw-example-image.png")
# Example response:
#  Here's the cartoon-style edit of the image:
#  Cartoon-style edit:
#  - Simplified the Eiffel Tower with bolder lines and slightly exaggerated proportions.
#  - Brightened and saturated the colors of the sky, fireworks, and foliage for a more vibrant, cartoonish look.
#  ....

REST

터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${API_ENDPOINT}:generateContent \
  -d '{
    "contents": {
      "role": "USER",
      "parts": [
        {"file_data": {
          "mime_type": "image/jpg",
          "file_uri": "<var>FILE_NAME</var>"
          }
        },
        {"text": "Convert this photo to black and white, in a cartoonish style."},
      ]

    },
    "generation_config": {
      "response_modalities": ["TEXT", "IMAGE"],
    },
    "safetySettings": {
      "method": "PROBABILITY",
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
  }' 2>/dev/null >response.json

Gemini가 설명을 기반으로 이미지를 생성합니다. 이 프로세스는 몇 초 정도 걸리지만 용량에 따라 비교적 느릴 수 있습니다.

관련 이미지를 포함한 텍스트 생성

Gemini 2.0 Flash는 텍스트 대답과 함께 인터리브 이미지를 생성할 수 있습니다. 예를 들어 모델에 별도의 요청을 하지 않고도 생성된 레시피의 각 단계가 어떻게 표시되는지 이미지를 생성하여 해당 단계의 텍스트와 함께 표시할 수 있습니다.

콘솔

텍스트 응답과 함께 인터리브 처리된 이미지를 생성하려면 다음 단계를 따르세요.

  1. Vertex AI Studio > 프롬프트 만들기를 엽니다.
  2. 모델 전환을 클릭하고 메뉴에서 gemini-2.0-flash-preview-image-generation을 선택합니다.
  3. 출력 패널의 드롭다운 메뉴에서 이미지 및 텍스트를 선택합니다.
  4. 프롬프트 작성 텍스트 영역에 생성하려는 이미지의 설명을 작성합니다. 예를 들어 '땅콩버터와 젤리 샌드위치를 만드는 방법을 세 가지 간단한 단계로 설명하는 튜토리얼을 만들어 줘. 각 단계마다 단계 번호가 포함된 제목과 설명을 제공하고 이미지를 생성해 줘. 각 이미지는 1:1 비율로 생성해 줘.'
  5. 프롬프트() 버튼을 클릭합니다.

Gemini가 설명을 기반으로 대답을 생성합니다. 이 프로세스는 몇 초 정도 걸리지만 용량에 따라 비교적 느릴 수 있습니다.

Gen AI SDK for Python

설치

pip install --upgrade google-genai

자세한 내용은 SDK 참고 문서를 참조하세요.

Vertex AI에서 Gen AI SDK를 사용하도록 환경 변수를 설정합니다.

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import GenerateContentConfig, Modality
from PIL import Image
from io import BytesIO

client = genai.Client()

response = client.models.generate_content(
    model="gemini-2.0-flash-exp",
    contents=(
        "Generate an illustrated recipe for a paella."
        "Create images to go alongside the text as you generate the recipe"
    ),
    config=GenerateContentConfig(response_modalities=[Modality.TEXT, Modality.IMAGE]),
)
with open("paella-recipe.md", "w") as fp:
    for i, part in enumerate(response.candidates[0].content.parts):
        if part.text is not None:
            fp.write(part.text)
        elif part.inline_data is not None:
            image = Image.open(BytesIO((part.inline_data.data)))
            image.save(f"example-image-{i+1}.png")
            fp.write(f"![image](./example-image-{i+1}.png)")
# Example response:
#  A markdown page for a Paella recipe(`paella-recipe.md`) has been generated.
#   It includes detailed steps and several images illustrating the cooking process.

REST

터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${API_ENDPOINT}:generateContent \
  -d '{
    "contents": {
      "role": "USER",
      "parts": { "text": "Create a tutorial explaining how to make a peanut butter and jelly sandwich in three easy steps. For each step, provide a title with the number of the step, an explanation, and also generate an image, generate each image in a 1:1 aspect ratio."},
    },
    "generation_config": {
      "response_modalities": ["TEXT", "IMAGE"],
     },
     "safetySettings": {
      "method": "PROBABILITY",
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
  }' 2>/dev/null >response.json

Gemini가 설명을 기반으로 이미지를 생성합니다. 이 프로세스는 몇 초 정도 걸리지만 용량에 따라 비교적 느릴 수 있습니다.