AIペイント技術実践課題2|Tencent Cloud Intelligent Picture Fusionを使用してAIペイントの効果を最適化する

前回の記事「AI ペイント技術の実践問題 1」では、Tencent Cloud のインテリジェント機能を使用して AI ペイントの簡易版を実装する方法について説明しましたが、リリース後、ネチズンの注目を集め、実現できるかどうかを検討しています。より良い結果が得られます。最近、ショートビデオ プラットフォームでも AI ペイント ゲームプレイがブームになっていることがわかりました。インターネット上でいくつかの優れた AI ペイント モデルを確認することも合わせて、前回の記事に基づいて、より良いエクスペリエンスを作成できるように努めたいと思います。

次に、私の実際のプロセスを完全に共有します。興味のある友人も試してみてください。

1. アイデアを実現する

AIによってポートレート画像が生成され、その後Tencent Cloudのインテリジェント機能を使用して顔の融合が実行され、最終的により効果の高いポートレート画像が生成されます。

1.1 詳細なプロセス:

 

2. 準備

2.1 安定拡散展開

Stable Diffusion は、テキストを入力することで意味的に正しい画像を生成できる、オープンソースのテキストから画像へのモデルです。詳細については、github の紹介を参照してください:  GitHub - CompVis/stable-diffusion: A latent text-to-image diffusion model

ドキュメントに従ってインストールします。インストール プロセスは似ているため、繰り返しません。

スクリプトを通じて画像を生成します。 

from torch import autocast
from diffusers import StableDiffusionPipeline
import sys

# 指定模型
pipe = StableDiffusionPipeline.from_pretrained(
        # "CompVis/stable-diffusion-v1-4", 
        "runwayml/stable-diffusion-v1-5",
        # "hakurei/waifu-diffusion",
        use_auth_token=True
).to("cuda")

prompt = "a photo of an astronaut riding a horse on mars"
prompt = sys.argv[1]
with autocast("cuda"):
    image = pipe(prompt, num_inference_steps=100).images[0]  
    image.save(sys.argv[2] + ".png")

キーワードを指定して出力を呼び出し、生成された効果を確認します。 

python3 interface.py "*******" out

 

3. ミニプログラムのデモ実習

以下は、ミニプログラムを通じて AI ペイントを実装するプロセスです。

3.1 AI ペイント サーバー:

モデルをデプロイした後は、ローカルでのみ実行できるため、次の関数を実装するだけです。

1. ユーザーがcosにタスクを送信し、サービスがcosの内容をプルしてAI描画タスクを実行します。

2. シェルコマンドを実行し、生成されたイメージを cos にアップロードします。

COS ドキュメント: オブジェクト ストレージの概要_オブジェクト ストレージ購入ガイド_オブジェクト ストレージ操作ガイド-Tencent Cloud

AI ペイント モデルの実行コード:

type Request struct {
	SessionId string `json:"session_id"`
	JobId     string `json:"job_id"`
	Prompt    string `json:"prompt"`
	ModelUrl  string `json:"model_url"`
	ImageUrl  string `json:"image_url"`
}

type JobInfo struct {
	JobId string `json:"job_id"`
	Request
}
func run(req *JobInfo) {
	begin := time.Now()

	Log("got a job, %+v", req)
	jobId := req.JobId
	cmd := exec.Command("sh", "start.sh", req.Prompt, jobId)

	err := cmd.Run()
	if err != nil {
		fmt.Println("Execute Command failed:" + err.Error())
		return
	}

	result, err := os.ReadFile(fmt.Sprintf("output/%s.png", jobId))
	if err != nil {
		panic(err)
	}
	url, err := cos.PutObject(context.Background(), fmt.Sprintf("aidraw/%s.png", jobId), result)
	if err != nil {
		panic(err)
	}
	resp := &Response{
		SessionId: req.SessionId,
		JobId:     jobId,
		JobStatus: "FINISNED",
		CostTime:  time.Since(begin).Milliseconds(),
		ResultUrl: url,
	}
	Log("job finished, %+v", resp)
	data, _ := json.Marshal(resp)
	pushResult(jobId, string(data))
}

タスク管理は、タスクの取得と結果のアップロードを含む cos を通じて実装されます。実装コードは次のとおりです。

func pullJob() *JobInfo {
	res, _, err := cos.GetInstance().Bucket.Get(context.Background(), &cossdk.BucketGetOptions{
		Prefix:       JOB_QUEUE_PUSH,
		Delimiter:    "",
		EncodingType: "",
		Marker:       "",
		MaxKeys:      10000,
	})
	if err != nil {
		return nil
	}
	var jobId string
	for _, v := range res.Contents {
		if !objectExist(fmt.Sprintf("%s/%s", JOB_QUEUE_RESULT, getNameByPath(v.Key))) {
			jobId = v.Key
			break
		}
	}
	if len(jobId) == 0 {
		return nil
	}
	jobId = getNameByPath(jobId)
	Log("new job %s", jobId)
	resp, err := cos.GetInstance().Object.Get(context.Background(), fmt.Sprintf("%s/%s", JOB_QUEUE_PUSH, jobId), &cossdk.ObjectGetOptions{})
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		return nil
	}
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil
	}
	job := &JobInfo{
		JobId: jobId,
	}
	err = json.Unmarshal(body, &job)
	if err != nil {
		return nil
	}

	return job
}

func pullResult(jobId string) *Response {
	resp, err := cos.GetInstance().Object.Get(context.Background(), fmt.Sprintf("%s/%s", JOB_QUEUE_RESULT, jobId), &cossdk.ObjectGetOptions{})
	if err != nil {
		return nil
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		return nil
	}
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil
	}
	rsp := &Response{}
	json.Unmarshal(body, &rsp)
	return rsp
}

func pushResult(jobId, result string) {
	_, err := cos.PutObject(context.Background(), fmt.Sprintf("%s/%s", JOB_QUEUE_RESULT, jobId), []byte(result))
	if err != nil {
		panic(err)
	}
}

3.2 ミニプログラムサーバー:

アプレットはリレー サービスを通じてメッセージを非同期に処理する必要があります。サーバーの機能を整理してみましょう。

1. リクエストを AI Painting に転送します。

2. AI ペイントの結果をクエリします。(cos経由で転送)

以下はコードの一部です。

契約関連:

type Request struct {
	SessionId string `json:"session_id"`
	JobId     string `json:"job_id"`
	Prompt    string `json:"prompt"`
	ModelUrl  string `json:"model_url"`
	ImageUrl  string `json:"image_url"`
}

type Response struct {
	SessionId string `json:"session_id"`
	JobId     string `json:"job_id"`
	JobStatus string `json:"job_status"`
	CostTime  int64  `json:"cost_time"`
	ResultUrl string `json:"result_url"`
	TotalCnt  int64  `json:"total_cnt"`
}

タスクを送信します:

// submitJobHandler 提交任务
func submitJobHandler(writer http.ResponseWriter, request *http.Request) {
	body, err := io.ReadAll(request.Body)
	req := &Request{}
	err = json.Unmarshal(body, &req)
	if err != nil {
		panic(err)
	}
	Log("got a submit request, %+v", req)
	jobId := GenJobId()
	pushJob(jobId, string(body))
	resp := &Response{
		SessionId: req.SessionId,
		JobId:     jobId,
		TotalCnt:  sumJob(),
	}
	data, _ := json.Marshal(resp)
	writer.Write(data)
}

// describeJobHandler 查询任务
func describeJobHandler(writer http.ResponseWriter, request *http.Request) {
	body, err := io.ReadAll(request.Body)
	req := &Request{}
	err = json.Unmarshal(body, &req)
	if err != nil {
		panic(err)
	}
	Log("got a query request, %+v", req.JobId)
	var ret *Response
	ret = pullResult(req.JobId)
	if ret == nil {
		ret = &Response{
			SessionId: req.SessionId,
			JobId:     req.JobId,
			JobStatus: "RUNNING",
		}
	}
	data, _ := json.Marshal(ret)
	writer.Write(data)
}

3.3. AI 描画を実装するためのミニ プログラム: 

インデックス.js

// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    totalTask: 0,
    leftTime: 40,
    beginTime: 0,
    processTime: 0,
    taskStatus: "STOP",
    inputValue: "",
    tags: [],
    option: [],
    buttonStatus: false,
    index: 0,
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    this.onTimeout();
  },
 
  getUserProfile(e) { 
    // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
    console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  enentloop() {
    var that = this
    if (!that.data.Resp || !that.data.Resp.job_id) {
      console.log("not found jobid")
      return
    }
    return new Promise(function(yes, no) {
      wx.request({
      url: 'http://127.0.0.1:8000/frontend/query',
      data: {
        "session_id": "123",
        "job_id": that.data.Resp.job_id
      },
      method: "POST",
      header: {
        'Content-Type': "application/json"
      },
      success (res) {
        yes("hello");
        if (res.data == null) {
          wx.showToast({
            icon: "error",
            title: '请求查询失败',
          })
          return
        }
        console.log(Date.parse(new Date()), res.data)
        that.setData({
          Job: res.data,
        })
        console.log("job_status: ", res.data.job_status)
        if (res.data.job_status === "FINISNED") {
          console.log("draw image: ", res.data.result_url)
          that.drawInputImage(res.data.result_url);
          that.setData({
            Resp: {},
            taskStatus: "STOP"
          })
        } else {
          that.setData({
            taskStatus: "PROCESSING",
            processTime: (Date.parse(new Date()) - that.data.beginTime)/ 1000
          })
        }
      },
      fail(res) {
        wx.showToast({
          icon: "error",
          title: '请求查询失败',
        })
        console.log(res)
      }
    })
  })
  },

  onTimeout:  function() {
    // 开启定时器
    var that = this;
    let ticker = setTimeout(async function() {
      console.log("begin")
      await that.enentloop();
      console.log("end")
      that.onTimeout();
    }, 3 * 1000); // 毫秒数
    // clearTimeout(ticker);
    that.setData({
      ticker: ticker
    });
  },

  imageDraw() {
    var that = this
    var opt = {}
    if (that.data.option && that.data.option.length > 0) {
      opt = {
        "tags": that.data.option
      }
    }
    console.log("option:", opt)
    wx.request({
      url: 'http://127.0.0.1:8000/frontend/create',
      data: {
        "prompt": that.data.inputValue
      },
      method: "POST",
      header: {
        'Content-Type': "application/json"
      },
      success (res) {
        if (res.data == null) {
          wx.showToast({
            icon: "error",
            title: '请求失败',
          })
          return
        }
        console.log(res.data)
        // let raw = JSON.parse(res.data)
        that.setData({
          Resp: res.data,
        })
        that.setData({
          totalTask: res.data.total_cnt,
          beginTime: Date.parse(new Date())
        })
      },
      fail(res) {
        wx.showToast({
          icon: "error",
          title: '请求失败',
        })
      }
    })
  },

  drawInputImage: function(url) {
    var that = this;
    console.log("result_url: ", url)

    let resUrl = url; // that.data.Job.result_url;
    
    wx.downloadFile({
      url: resUrl,
      success: function(res) {
        var imagePath = res.tempFilePath
        wx.getImageInfo({
          src: imagePath,
          success: function(res) {
            wx.createSelectorQuery()
            .select('#input_canvas') // 在 WXML 中填入的 id
            .fields({ node: true, size: true })
            .exec((r) => {
              // Canvas 对象
              const canvas = r[0].node
              // 渲染上下文
              const ctx = canvas.getContext('2d')
              // Canvas 画布的实际绘制宽高 
              const width = r[0].width
              const height = r[0].height
              // 初始化画布大小
              const dpr = wx.getWindowInfo().pixelRatio
              canvas.width = width * dpr
              canvas.height = height * dpr
              ctx.scale(dpr, dpr)
              ctx.clearRect(0, 0, width, height)

              let radio = height / res.height
              console.log("radio:", radio)
              const img = canvas.createImage()
              var x = width / 2 - (res.width * radio / 2)

              img.src = imagePath
              img.onload = function() {
                ctx.drawImage(img, x, 0, res.width * radio, res.height * radio)
              }
            })
          }
        })
      }
    })
  },

  handlerInput(e) {
    this.setData({
      inputValue: e.detail.value
    })
  },

  handlerSearch(e) {
    console.log("input: ", this.data.inputValue)

    if (this.data.inputValue.length == 0) {
      wx.showToast({
        icon: "error",
        title: '请输入你的创意 ',
      })
      return
    }
    this.imageDraw()
  },
  handlerInputPos(e) {
    console.log(e)
    this.setData({
      inputValue: e.detail.value
    })
  },
  handlerInputFusion(e) {
    console.log(e)
    this.setData({
      inputUrl: e.detail.value
    })
  },
  handlerInputImage(e) {
    console.log(e)
  },
  clickItem(e) {
    let $bean = e.currentTarget.dataset
    console.log(e)
    console.log("value: ", $bean.bean)
    this.setData({
      option: $bean.bean
    })
    this.imageDraw()
  }
})

インデックス.wxml:

<view class="container" style="width: 750rpx; height: 1229rpx; display: flex; box-sizing: border-box">
  <div class="form-item" style="width: 673rpx; height: 70rpx; display: block; box-sizing: border-box">
    <input placeholder="写下你的创意" class="input" bindinput="handlerInput" />
    <input placeholder="待融合URL" class="input" bindinput="handlerInputFusion" />
    <button class="button" loading="{
   
   {buttonStatus}}" bindtap="handlerSearch" size="mini" style="width: 158rpx; height: 123rpx; display: block; box-sizing: border-box; left: 0rpx; top: -60rpx; position: relative"> 立即生成 </button>
  </div>
  <view class="text_box">
    <text class="text_line" style="position: relative; left: 18rpx; top: 0rpx">完成任务数:</text>
    <text class="text_line" style="position: relative; left: 8rpx; top: 0rpx">{
   
   {totalTask}},</text>
    <text class="text_line" style="position: relative; left: 38rpx; top: 0rpx">{
   
   {taskStatus}}</text>
    <text class="text_line" style="position: relative; left: 43rpx; top: 0rpx">{
   
   {processTime}}/{
   
   {leftTime}}s</text>
  </view>

  <view class="output_line" style="position: relative; left: 2rpx; top: 51rpx; width: 714rpx; height: 40rpx; display: flex; box-sizing: border-box">
    <text class="text_line" style="width: 199rpx; height: 0rpx; display: block; box-sizing: border-box; position: relative; left: 1rpx; top: -92rpx">作品图片</text>
    <view style="position: relative; left: -15rpx; top: 2rpx; width: 571rpx; height: 0rpx; display: block; box-sizing: border-box"></view>
  </view>
  <canvas type="2d" id="input_canvas" style="background: rgb(228, 228, 225); width: 673rpx; height: 715rpx; position: relative; left: 2rpx; top: -64rpx; display: block; box-sizing: border-box">
  </canvas>
  <view class="output_line" style="position: relative; left: 0rpx; top: 50rpx; width: 714rpx; height: 58rpx; display: flex; box-sizing: border-box">
  </view>
</view>

この時点で、AI 描画アプレットが実装されました。次に効果を見てみましょう キーワードを入力すると作品のイメージが掴めます。 

 

新たな問題が発生し、テストの結果、次の図に示すように、AI モデルによって直接生成された画像の顔の部分が理想的ではないことがわかりました。

 

ポートレートをより自然にするにはどうすればよいですか? 市場にある既存の AI 機能を調査したところ、Tencent Cloud AI のフェイス フュージョンで顔変更機能を実現できることがわかりましたので、以下で詳しく紹介します。

3.4. 顔の融合

3.4.1 フェイス フュージョンの概要

 

3.5.2 融合機能のデモンストレーション:

​​​​​​​

 

3.4.3 Fusion コンソール:

アクティビティやマテリアルの作成に使用されます。 

 

3.4.4 資材管理:

 

マテリアルを追加するだけです:

ここでの素材はAIによって生成された画像を指しますが、その効果を見てみましょう。

3.4.5 AIペイント+フュージョン効果の検証

上記の問題のある写真を画像フュージョンのデモ ページにアップロードし、写真と顔のフュージョンを実行したところ、その効果が非常に素晴らしいことがわかりました。

 

通常の顔変更効果は次のとおりです。

 

上記の結果に基づいて、使用シナリオと組み合わせることで、Tencent Cloud の画像融合機能を既存の AI ペインティングに追加できます。

3.5 ミニプログラムは融合効果を追加します:

元のプロセスに基づいて統合手順を追加します。具体的なプロセスは次のとおりです。 

3.5.1 一般的な考え方: 

 

3.5.2 詳細なプロセス: 

フェイスフュージョン操作を追加しました。

 

3.5.3 顔融合処理インターフェイスをサーバーに追加します。

ミニ プログラム サーバーに統合タスク処理を追加します。 

// facefusionHandler ...
func facefusionHandler(writer http.ResponseWriter, request *http.Request) {
	body, err := io.ReadAll(request.Body)
	req := &Request{}
	err = json.Unmarshal(body, &req)
	if err != nil {
		panic(err)
	}

	ret := &Response{
		SessionId: req.SessionId,
 		// 将AI画画的图上传至素材管理, 并和输入图做融合
		ResultUrl: rawCloud(req.ModelUrl, req.ImageUrl),
	}
	data, _ := json.Marshal(ret)
	writer.Write(data)
}

AI で描いた絵を素材管理にアップロードするには、通常、コンソール上で実行する必要があります。私は API を通じて直接呼び出します。手書きのV3 署名が必要です。コードは公開されません。興味のある方は、こちらをご覧ください。 。

3.5.4 ミニ プログラムは融合後のタスクを追加します。

AI によって描画された画像を取得した後、アプレットは必要に応じて融合操作を実行します。

facefusion(modelUrl, imageUrl) {
    var that = this;
    that.setData({
      taskStatus: "融合中...",
      processTime: (Date.parse(new Date()) - that.data.beginTime)/ 1000
    })
    wx.request({
      url: 'http://127.0.0.1:8000/frontend/fusion',
      data: {
        "session_id": "123",
        "model_url": modelUrl,
        "image_url": imageUrl
      },
      method: "POST",
      header: {
        'Content-Type': "application/json"
      },
      success (res) {
        if (res.data == null) {
          wx.showToast({
            icon: "error",
            title: '请求融合失败',
          })
          return
        }
        
        if (res.data.result_url !== "") {
          console.log("draw image: ", res.data.result_url)
          that.drawInputImage(res.data.result_url);
          that.setData({
            Resp: {}
          })
          that.setData({
            taskStatus: "STOP"
          })
          // clearTimeout(that.data.ticker);
        } else {
          that.setData({
            taskStatus: "PROCESSING",
            processTime: (Date.parse(new Date()) - that.data.beginTime)/ 1000
          })
        }
        // a portrait of an old coal miner in 19th century, beautiful painting with highly detailed face by greg rutkowski and magali villanueve
      },
      fail(res) {
        wx.showToast({
          icon: "error",
          title: '请求融合失败',
        })
        console.log(res)
      }
    })
  },

コンパイルが開始されると、タスクのステータスに「Converging」のステータスが追加されます。

 

前後の比較をご覧ください。これは AI によって生成された画像です。

融合した画像:

次のインターフェースは最適化されています。最終バージョンをご覧ください:: 

​​​​​​​

 

要約する

現時点では、AI 描画 + ポートレート フュージョンのデモが実装されており、この 2 つを組み合わせて使用​​することで、より良い顔の効果を生成することができ、より良いプロンプトを自分で編成してより良いポートレート画像を生成することもできます。ハグフェイスには検討すべきモデルやキーワードがたくさんありますので、今回はまずここで紹介します。

おすすめ

転載: blog.csdn.net/tencentAI/article/details/128316153