[AI] 使用Jupyter Notebook呼叫CodeFormer API進行AI修老照片

  • 362
  • 0
  • AI
  • 2023-03-04

參考: [Day02]使用 Jupyter notebook來寫python

以前的照片解析度不高, 畫質不夠好,
目前已能用AI--sczhou/codeformer自動將老照片的人臉變清晰, 以下是操作步驟:

  1. 安裝Anaconda和虛擬環境(最好不同功能各建一個環境以免弄混), 參考: [Day01]學習python的行前作業
  2. 安裝Jupyter notebook參考:[Day02]使用 Jupyter notebook來寫python
  3. 用GitHub帳號申請api key Taiwan is a country. 臺灣是我的國家
  4. 啟動Anaconda Powershell Prompt, 輸入pip install replicate安裝套件, 參考: https://replicate.com/sczhou/codeformer/api
  5. 啟動Jupyter notebook就能輸入python語法來實作, 語法如下, 官網說明參考:
%env REPLICATE_API_TOKEN=你的api key
import os
os.chdir('W:/Pictures/scan') #工作目錄切換到放置圖檔的目錄
%pwd #查看工作目錄切換結果
import replicate
import os
import urllib.request

model = replicate.models.get("sczhou/codeformer")
version = model.versions.get("7de2ea26c616d5bf2245ad0d5e24f0ff9a6204578a5c876db53142edd9d2cd56")


for root, dirs, files in os.walk('.'):  # 從當前目錄(或另輸入路徑)開始遍歷
    for name in files:
        img = os.path.join(root, name).replace('.\\','')
        print(img)  # 列出檔案名稱及完整路徑
        inputs = {
            # Input image
            'image': open(img, "rb"),
            
            # Balance the quality (lower number) and fidelity (higher number).
            # Range: 0 to 1
            'codeformer_fidelity': 0.5,

            # Enhance background image with Real-ESRGAN
            'background_enhance': True,

            # Upsample restored faces for high-resolution AI-created images
            'face_upsample': True,

            # 長寬幾倍
            'upscale': 1.5,
        }

        url = version.predict(**inputs)        
        # 下載圖片並儲存到本地端
        urllib.request.urlretrieve(url, img.replace('jpg','png'))#我的圖片全是jpg, 所以下載成png不會覆蓋

一個免費帳號能處理200張圖

Taiwan is a country. 臺灣是我的國家