Gerar uma imagem baseada em texto

Este exemplo demonstra como usar o modelo do Imagen para gerar uma imagem baseada em texto.

Exemplo de código

C#

Antes de testar esse exemplo, siga as instruções de configuração para C# no Guia de início rápido da Vertex AI sobre como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vertex AI para C#.

Para autenticar na Vertex AI, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


using Google.Cloud.AIPlatform.V1;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Value = Google.Protobuf.WellKnownTypes.Value;

public class GenerateImage
{
    public async Task<FileInfo> Generate(
        string projectId = "your-project-id")
    {
        var predictionServiceClient = new PredictionServiceClientBuilder
        {
            Endpoint = "us-central1-aiplatform.googleapis.com"
        }.Build();


        string prompt = "a dog reading a newspaper";
        string outputFileName = "dog_newspaper.png";
        string model = "imagegeneration@006";

        var predictRequest = new PredictRequest
        {
            EndpointAsEndpointName = EndpointName.FromProjectLocationPublisherModel(projectId, "us-central1", "google", model),
            Instances =
            {
                Value.ForStruct(new()
                {
                    Fields =
                    {
                        ["prompt"] = Value.ForString(prompt)
                    }
                })
            },
            Parameters = Value.ForStruct(new()
            {
                Fields =
                {
                    ["sampleCount"] = Value.ForNumber(1)
                }
            })
        };

        PredictResponse response = await predictionServiceClient.PredictAsync(predictRequest);
        byte[] imageBytes = Convert.FromBase64String(response.Predictions.First().StructValue.Fields["bytesBase64Encoded"].StringValue);

        File.WriteAllBytes(outputFileName, imageBytes);
        FileInfo fileInfo = new FileInfo(Path.GetFullPath(outputFileName));

        Console.WriteLine($"Created output image {fileInfo.FullName} with {fileInfo.Length} bytes");
        return fileInfo;
    }
}

Python

Antes de testar essa amostra, siga as instruções de configuração para Python Guia de início rápido da Vertex AI: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vertex AI para Python.

Para autenticar na Vertex AI, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


import vertexai
from vertexai.preview.vision_models import ImageGenerationModel

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# output_file = "my-output.png"
# prompt = "" # The text prompt describing what you want to see.

vertexai.init(project=project_id, location="us-central1")

model = ImageGenerationModel.from_pretrained("imagegeneration@006")

images = model.generate_images(
    prompt=prompt,
    # Optional parameters
    number_of_images=1,
    language="en",
    # You can't use a seed value and watermark at the same time.
    # add_watermark=False,
    # seed=100,
    aspect_ratio="1:1",
    safety_filter_level="block_some",
    person_generation="allow_adult",
)

images[0].save(location=output_file, include_generation_parameters=False)

# Optional. View the generated image in a notebook.
# images[0].show()

print(f"Created output image using {len(images[0]._image_bytes)} bytes")

A seguir

Para pesquisar e filtrar exemplos de código de outros produtos do Google Cloud, consulte a pesquisa de exemplos de código do Google Cloud.