Android 圖片產生指南

MediaPipe Image Generator 工作可根據文字提示生成圖片。這項工作會使用文字轉圖像模型,透過擴散技術生成圖像。

這項工作會接受文字提示做為輸入內容,以及模型可擴增並做為生成參考的選用條件圖片。圖片生成器也可以根據模型在訓練或重新訓練期間學到的特定概念生成圖片。詳情請參閱「使用 LoRA 自訂」。

您可以在 GitHub 取得這些操作說明中使用的程式碼範例。如要進一步瞭解這項工作的能力、模型和設定選項,請參閱「總覽」。

程式碼範例

MediaPipe Tasks 範例程式碼是 Android 圖片生成器應用程式的基本實作。您可以將這個應用程式做為自己 Android 應用程式的範本,也可以在修改現有應用程式時參考這個範例。圖片產生器範例程式碼位於 GitHub

下載程式碼

以下操作說明會示範如何使用 git 指令列工具,建立範例程式碼的本機副本。

如要下載範例程式碼,請按照下列步驟操作:

  1. 使用下列指令複製 git 存放區:
    git clone https://github.com/google-ai-edge/mediapipe-samples
    
  2. 您也可以設定 Git 執行個體使用稀疏簽出,這樣就只會有 Image Generator 範例應用程式的檔案:
    cd mediapipe-samples
    git sparse-checkout init --cone
    git sparse-checkout set examples/image_generation/android
    

建立範例程式碼的本機版本後,您可以將專案匯入 Android Studio 並執行應用程式。如需操作說明,請參閱「Android 設定指南」。

重要元件

下列檔案包含這個圖片生成範例應用程式的重要程式碼:

設定

本節說明設定開發環境和程式碼專案的主要步驟,以便使用 Image Generator。如需設定開發環境以使用 MediaPipe 工作的一般資訊,包括平台版本需求,請參閱 Android 設定指南

依附元件

Image Generator 工作會使用 com.google.mediapipe:tasks-vision-image-generator 程式庫。將這項依附元件新增至 Android 應用程式的 build.gradle 檔案:

dependencies {
    implementation 'com.google.mediapipe:tasks-vision-image-generator:latest.release'
}

如果是搭載 Android 12 (API 31) 以上版本的裝置,請新增原生 OpenCL 程式庫依附元件。詳情請參閱 uses-native-library 標記的說明文件。

將下列 uses-native-library 標記新增至 AndroidManifest.xml 檔案:

<uses-native-library android:name="libOpenCL.so" android:required="false" />
<uses-native-library android:name="libOpenCL-car.so" android:required="false"/>
<uses-native-library android:name="libOpenCL-pixel.so" android:required="false" />

型號

MediaPipe Image Generator 工作需要與這項工作相容的訓練基礎模型。下載模型後,請安裝必要依附元件,並將模型轉換為合適的格式。然後將轉換後的模型推送到 Android 裝置。

如要進一步瞭解 Image Generator 適用的預先訓練模型,請參閱工作總覽的「模型」一節。

下載基礎模型

圖片生成器需要基礎模型符合 stable-diffusion-v1-5/stable-diffusion-v1-5 EMA-only 模型格式,根據下列模型:stable-diffusion-v1-5/stable-diffusion-v1-5 EMA-only

安裝依附元件並轉換模型

$ pip install torch typing_extensions numpy Pillow requests pytorch_lightning absl-py

執行 convert.py 指令碼:

$ python3 convert.py --ckpt_path <ckpt_path> --output_path <output_path>

將轉換後的模型推送至裝置

<output_path> 資料夾的內容推送到 Android 裝置。

$ adb shell rm -r /data/local/tmp/image_generator/ # Remove any previously loaded weights
$ adb shell mkdir -p /data/local/tmp/image_generator/
$ adb push <output_path>/. /data/local/tmp/image_generator/bins

下載外掛程式模型並新增 LoRA 權重 (選用)

如要使用外掛程式模型,請檢查是否必須下載模型。如果外掛程式需要額外模型,外掛程式模型必須與 APK 組合在一起,或是隨選下載。外掛程式模型輕巧 (~23MB),可直接封裝在 APK 中。不過,我們建議隨選下載外掛程式模型。

如果您使用 LoRA 自訂模型,可以視需要下載。詳情請參閱 LoRA 權重外掛程式模型

建立工作

MediaPipe Image Generator 工作會使用 createFromOptions() 函式設定工作。createFromOptions() 函式會接受設定選項的值。如要進一步瞭解設定選項,請參閱「設定選項」。

設定選項

這項工作提供下列 Android 應用程式設定選項:

選項名稱 說明 值範圍
imageGeneratorModelDirectory 儲存模型權重的圖片生成器模型目錄。 PATH
loraWeightsFilePath 設定 LoRA 權重檔案的路徑。此為選用屬性,僅適用於使用 LoRA 自訂模型的情況。 PATH
errorListener 設定選用的錯誤監聽器。 N/A

這項工作也支援外掛程式模型,讓使用者在工作輸入內容中加入條件圖片,基礎模型可以擴增這些圖片,並做為生成內容的參考。這些條件圖片可以是臉部地標、邊緣輪廓和深度估計值,模型會將這些圖片做為額外的背景資訊,用來生成圖片。

將外掛程式模型新增至基礎模型時,請一併設定外掛程式選項。臉部地標外掛程式使用 faceConditionOptions,Canny 邊緣外掛程式使用 edgeConditionOptions,深度外掛程式則使用 depthConditionOptions

Canny 邊緣選項

edgeConditionOptions 中設定下列選項。

選項名稱 說明 值範圍 預設值
threshold1 滯後程序的第一個門檻。 Float 100
threshold2 磁滯程序的第二個門檻。 Float 200
apertureSize Sobel 運算子的光圈大小。一般範圍介於 3 到 7 之間。 Integer 3
l2Gradient 是否使用 L2 範數計算圖片梯度大小,而非預設的 L1 範數。 BOOLEAN False
EdgePluginModelBaseOptions 設定外掛程式模型路徑的 BaseOptions 物件。 BaseOptions 個物件 N/A

如要進一步瞭解這些設定選項的運作方式,請參閱「Canny 邊緣偵測器」。

臉部特徵選項

faceConditionOptions 中設定下列選項。

選項名稱 說明 值範圍 預設值
minFaceDetectionConfidence 臉部偵測成功所需的最低信賴分數。 Float [0.0,1.0] 0.5
minFacePresenceConfidence 臉部特徵偵測中,臉部出現分數的最低信賴分數。 Float [0.0,1.0] 0.5
faceModelBaseOptions BaseOptions 物件,用於設定建立條件圖片的模型路徑。 BaseOptions 個物件 N/A
FacePluginModelBaseOptions 設定外掛程式模型路徑的 BaseOptions 物件。 BaseOptions 個物件 N/A

如要進一步瞭解這些設定選項的運作方式,請參閱臉部地標工作

深度選項

depthConditionOptions 中設定下列選項。

選項名稱 說明 值範圍 預設值
depthModelBaseOptions BaseOptions 物件,用於設定建立條件圖片的模型路徑。 BaseOptions 個物件 N/A
depthPluginModelBaseOptions 設定外掛程式模型路徑的 BaseOptions 物件。 BaseOptions 個物件 N/A

只使用基礎模型建立

val options = ImageGeneratorOptions.builder()
    .setImageGeneratorModelDirectory(modelPath)
    .build()

imageGenerator = ImageGenerator.createFromOptions(context, options)

使用外掛程式建立

如要套用選用外掛程式模型,請使用 setPluginModelBaseOptions 設定外掛程式模型的基本選項。如果外掛程式模型需要額外下載的模型才能建立條件圖片,請在 BaseOptions 中指定路徑。

臉部特徵

val options = ImageGeneratorOptions.builder()
    .setImageGeneratorModelDirectory(modelPath)
    .build()

val faceModelBaseOptions = BaseOptions.builder()
    .setModelAssetPath("face_landmarker.task")
    .build()

val facePluginModelBaseOptions = BaseOptions.builder()
    .setModelAssetPath("face_landmark_plugin.tflite")
    .build()

val faceConditionOptions = FaceConditionOptions.builder()
    .setFaceModelBaseOptions(faceModelBaseOptions)
    .setPluginModelBaseOptions(facePluginModelBaseOptions)
    .setMinFaceDetectionConfidence(0.3f)
    .setMinFacePresenceConfidence(0.3f)
    .build()

val conditionOptions = ConditionOptions.builder()
    .setFaceConditionOptions(faceConditionOptions)
    .build()

imageGenerator =
    ImageGenerator.createFromOptions(context, options, conditionOptions)
    

Canny Edge

val options = ImageGeneratorOptions.builder()
    .setImageGeneratorModelDirectory(modelPath)
    .build()

val edgePluginModelBaseOptions = BaseOptions.builder()
    .setModelAssetPath("canny_edge_plugin.tflite")
    .build()

val edgeConditionOptions = EdgeConditionOptions.builder()
    .setThreshold1(100.0f)
    .setThreshold2(100.0f)
    .setApertureSize(3)
    .setL2Gradient(false)
    .setPluginModelBaseOptions(edgePluginModelBaseOptions)
    .build()

val conditionOptions = ConditionOptions.builder()
    .setEdgeConditionOptions(edgeConditionOptions)
    .build()

imageGenerator =
    ImageGenerator.createFromOptions(context, options, conditionOptions)
    

深度

val options = ImageGeneratorOptions.builder()
    .setImageGeneratorModelDirectory(modelPath)
    .build()

val depthModelBaseOptions = BaseOptions.builder()
    .setModelAssetPath("depth_model.tflite")
    .build()

val depthPluginModelBaseOptions = BaseOptions.builder()
    .setModelAssetPath("depth_plugin.tflite")
    .build()

val depthConditionOptions =
    ConditionOptions.DepthConditionOptions.builder()
        .setDepthModelBaseOptions(depthModelBaseOptions)
        .setPluginModelBaseOptions(depthPluginModelBaseOptions)
        .build()

val conditionOptions = ConditionOptions.builder()
    .setDepthConditionOptions(depthConditionOptions)
    .build()

imageGenerator =
    ImageGenerator.createFromOptions(context, options, conditionOptions)
    

使用 LoRA 權重創作

如要加入 LoRA 權重,請使用 loraWeightsFilePath 參數指向路徑位置。

val options = ImageGeneratorOptions.builder()
    .setLoraWeightsFilePath(weightsPath)
    .setImageGeneratorModelDirectory(modelPath)
    .build()

imageGenerator = ImageGenerator.createFromOptions(context, options)

準備資料

圖像生成器接受下列輸入內容:

  • 提示 (必要):描述要生成圖片的文字提示。
  • 疊代 (必要):生成圖像的疊代總數。建議從 20 開始。
  • seed (必要):圖片生成期間使用的隨機種子。
  • 狀況圖片 (選用):模型用來做為生成參考的圖片。僅適用於外掛程式模型。
  • 條件類型 (選填):與工作搭配使用的外掛程式模型類型。 僅適用於外掛程式模型。

僅使用基礎模型的輸入內容

fun setInput(prompt: String, iteration: Int, seed: Int) {
    imageGenerator.setInputs(prompt, iteration, seed)
}

使用外掛程式輸入

如要套用選用外掛程式模型,請使用 conditionType 參數選擇外掛程式模型,並使用 sourceConditionImage 參數生成條件圖片。

選項名稱 說明
conditionType 套用至基礎模型的外掛程式模型。 {"FACE", "EDGE", "DEPTH"}
sourceConditionImage 用於建立條件圖片的來源圖片。 MPImage 個物件

如果您使用外掛程式模型,請使用 createConditionImage 建立條件圖片:

fun createConditionImage(
    inputImage: MPImage,
    conditionType: ConditionType
): Bitmap {
    val result =
        imageGenerator.createConditionImage(inputImage, conditionType)
    return BitmapExtractor.extract(result)
}

建立條件圖片後,請連同提示、種子值和疊代次數,一併做為輸入內容。

imageGenerator.setInputs(
    prompt,
    conditionalImage,
    conditionType,
    iteration,
    seed
)

使用 LoRA 權重的輸入內容

如果您使用 LoRA 權重,請務必在文字提示中加入權重代表的特定概念,才能生成相關圖片。

fun setInput(prompt: String, iteration: Int, seed: Int) {
    imageGenerator.setInputs(prompt, iteration, seed)
}

執行工作

使用 generate() 方法,根據上一節提供的輸入內容生成圖片。這會生成單一圖片。

僅使用基礎模型生成

fun generate(prompt: String, iteration: Int, seed: Int): Bitmap {
    val result = imageGenerator.generate(prompt, iteration, seed)
    val bitmap = BitmapExtractor.extract(result?.generatedImage())
    return bitmap
}

使用外掛程式生成內容

fun generate(
    prompt: String,
    inputImage: MPImage,
    conditionType: ConditionType,
    iteration: Int,
    seed: Int
): Bitmap {
    val result = imageGenerator.generate(
        prompt,
        inputImage,
        conditionType,
        iteration,
        seed
    )
    val bitmap = BitmapExtractor.extract(result?.generatedImage())
    return bitmap
}

使用 LoRA 權重生成

使用以 LoRA 權重自訂的模型生成圖像的程序,與使用標準基礎模型的程序類似。確認提示中包含權杖,然後執行相同的程式碼。

fun generate(prompt: String, iteration: Int, seed: Int): Bitmap {
    val result = imageGenerator.generate(prompt, iteration, seed)
    val bitmap = BitmapExtractor.extract(result?.generatedImage())
    return bitmap
}

反覆生成

圖片產生器也可以在每次疊代期間輸出產生的中繼圖片,如 iterations 輸入參數中所定義。如要查看這些中間結果,請呼叫 setInputs 方法,然後呼叫 execute() 執行每個步驟。將 showResult 參數設為 true,即可顯示中繼結果。

fun execute(showResult: Boolean): Bitmap {
    val result = imageGenerator.execute(showResult)

    val bitmap =
        BitmapExtractor.extract(result.generatedImage())

    return bitmap
}

處理及顯示結果

Image Generator 會傳回 ImageGeneratorResult,其中包含生成的圖片、完成時間的時間戳記,以及條件式圖片 (如有提供)。

val bitmap = BitmapExtractor.extract(result.generatedImage())

下圖是使用基礎模型,根據下列輸入內容生成。

輸入:

  • 提示:「一隻戴著軟邊寬帽的彩色卡通浣熊,拿著棍子走在森林中,動畫,四分之三視角,繪畫」
  • 種子:312687592
  • 疊代:20

生成的圖片:

根據提示生成的浣熊圖像