Imagen은 Google에서 개발한 고급 이미지 생성 AI 모델 시리즈로, 텍스트 프롬프트를 바탕으로 고품질의 사실적인 이미지를 생성할 수 있습니다. 이 가이드는 Imagen API를 사용하여 이미지를 생성하는 방법, 매개변수 설정, 모델 선택, 코드 예시를 이해하는 데 도움이 됩니다.
사용 가능한 모델:
imagen-4.0-generate-preview-05-20
imagen-4.0-ultra-generate-exp-05-20
imagen-3.0-generate-002
현재 Imagen은 영어 프롬프트만 지원합니다. 통합 시 자동 번역을 추가하여 사용자가 언어 장벽 없이 사용할 수 있도록 하는 것을 권장합니다.
import osimport timefrom google import genaifrom google.genai import typesfrom PIL import Imagefrom io import BytesIOclient = genai.Client( api_key="sk-***", # 🔑 AiHubMix에서 생성한 키로 교체하세요 http_options={"base_url": "https://aihubmix.com/gemini"},)# 현재 영어 프롬프트만 지원하며, 대량의 텍스트에서 성능이 떨어집니다response = client.models.generate_images( model='imagen-3.0-generate-002', prompt='A minimalist logo for a LLM router market company on a solid white background. trident in a circle as the main symbol, with ONLY text \'InferEra\' below.', config=types.GenerateImagesConfig( number_of_images=1, aspect_ratio="1:1", # "1:1", "9:16", "16:9", "3:4", "4:3" 지원 ))script_dir = os.path.dirname(os.path.abspath(__file__))output_dir = os.path.join(script_dir, "output")os.makedirs(output_dir, exist_ok=True)# 파일명 충돌을 피하기 위해 타임스탬프를 파일명 접두사로 생성timestamp = int(time.time())# 생성된 이미지 저장 및 표시for i, generated_image in enumerate(response.generated_images): image = Image.open(BytesIO(generated_image.image.image_bytes)) image.show() file_name = f"imagen3_{timestamp}_{i+1}.png" file_path = os.path.join(output_dir, file_name) image.save(file_path) print(f"이미지가 저장되었습니다: {file_path}")
"modalities": ["text","image"]{ "model": "gemini-2.0-flash-preview-image-generation", "messages": [ { "role": "user", "content": "Generate a landscape painting and provide a poem to describe it" } ], "modalities":["text","image"], //이미지 추가 필요 "temperature": 0.7 }'
출력 참조 구조:
Copy
"choices": [ { "index": 0, "message": { "role": "assistant", "content": "Hello! How can I assist you today?", "refusal": null, "multi_mod_content": //📍 새로 추가 [ { "text": "", "inlineData": { "data":"base64 str", "mimeType":"png" } }, { "text": "hello", "inlineData": { } } ], "annotations": [] }, "logprobs": null, "finish_reason": "stop" } ],
import osfrom openai import OpenAIfrom PIL import Imagefrom io import BytesIOimport base64client = OpenAI( api_key="sk-***", # 🔑 AiHubMix에서 생성한 키로 교체하세요 base_url="https://aihubmix.com/v1",)project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))image_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources", "filled.jpg")if not os.path.exists(image_path): raise FileNotFoundError(f"이미지 {image_path}가 존재하지 않습니다")def encode_image(image_path): with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode("utf-8")base64_image = encode_image(image_path)response = client.chat.completions.create( model="gemini-2.0-flash-preview-image-generation", messages=[ { "role": "user", "content": [ { "type": "text", "text": "describe the image with a concise and engaging paragraph, then fill color as children's crayon style", }, { "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}, }, ], }, ], modalities=["text", "image"], temperature=0.7,)try: # base64 데이터 없이 기본 응답 정보 출력 print(f"생성 시간: {response.created}") print(f"토큰 사용량: {response.usage.total_tokens}") # multi_mod_content 필드가 존재하는지 확인 if ( hasattr(response.choices[0].message, "multi_mod_content") and response.choices[0].message.multi_mod_content is not None ): print("\n응답 내용:") for part in response.choices[0].message.multi_mod_content: if "text" in part and part["text"] is not None: print(part["text"]) # 이미지 내용 처리 elif "inline_data" in part and part["inline_data"] is not None: print("\n🖼️ [이미지 내용 수신됨]") image_data = base64.b64decode(part["inline_data"]["data"]) mime_type = part["inline_data"].get("mime_type", "image/png") print(f"이미지 유형: {mime_type}") image = Image.open(BytesIO(image_data)) image.show() # 이미지 저장 output_dir = os.path.join(os.path.dirname(image_path), "output") os.makedirs(output_dir, exist_ok=True) output_path = os.path.join(output_dir, "edited_image.jpg") image.save(output_path) print(f"✅ 이미지가 저장되었습니다: {output_path}") else: print("유효한 멀티모달 응답을 받지 못했습니다. 응답 구조를 확인하세요")except Exception as e: print(f"응답 처리 중 오류 발생: {str(e)}")
AIhubmix는 공식 API와 동일한 출력 품질을 제공하지만 더 낮은 요율인 요청당 $0.41의 역방향 액세스 방법을 제공합니다. 하지만 모든 역방향 방법은 안정적인 생성을 보장할 수 없다는 점을 유의하세요. 개발 환경에서 초기 실험이나 개인적인 탐구용으로만 사용하는 것을 권장합니다.
알려진 제한사항은 공식 API와 일치합니다. 위의 “Veo 3.0 비디오 생성” 섹션을 참조하세요.
{ "prompt": "A sleek, metallic mechanical butterfly with intricate, glowing blue circuitry patterns on its wings flies gracefully through a futuristic garden. The garden is filled with bioluminescent plants, floating orbs of light, and holographic flowers that change colors. The butterfly's wings reflect the ambient light, creating a mesmerizing shimmer as it moves. The background features a sleek, minimalist cityscape with towering glass structures and hovering drones. The scene is bathed in a soft, ethereal glow from a setting sun, casting long shadows and enhancing the futuristic ambiance. The camera follows the butterfly in a smooth, cinematic motion, capturing the delicate movements of its wings and the vibrant, otherworldly beauty of the garden."}
Copy
> 비디오 생성 작업 생성됨> 작업 ID: `8167db37-2b7c-4794-9232-891d02ca7fa3`> 작업 중단을 방지하기 위해 다음 링크에서 지속적으로 진행 상황을 추적할 수 있습니다:> [데이터 미리보기](https://asyncdata.net/web/8167db37-2b7c-4794-9232-891d02ca7fa3) | [소스 데이터](https://asyncdata.net/source/8167db37-2b7c-4794-9232-891d02ca7fa3)> 처리 대기 중> 유형: 텍스트-비디오 생성> 🎬 비디오 생성 시작...................> ⚠️ 재시도 중 (0/3)> 유형: 텍스트-비디오 생성> 🎬 비디오 생성 시작.....................> 🔄 비디오 품질 최적화 중.................> 🎉 고품질 비디오 생성됨[▶️ 온라인 시청](https://filesystem.site/cdn/20250615/T7yfqW229fox4gJA1ys0eMAGLkcSfd.mp4) | [⏬ 비디오 다운로드](https://filesystem.site/cdn/download/20250615/T7yfqW229fox4gJA1ys0eMAGLkcSfd.mp4)
VEO 2.0은 Google에서 출시한 고급 비디오 생성 AI 모델로, 텍스트 프롬프트를 바탕으로 고품질의 사실적인 단편 비디오를 생성할 수 있습니다. 이 부분은 VEO 2.0 API를 사용하여 비디오를 생성하는 방법, 매개변수 설정, 모델 선택, 코드 예시를 이해하는 데 도움이 됩니다.