0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python 3.13でReal-ESRGANを動かす ― KeyError: '__version__' の原因と解決策

0
Posted at

画像を高画質にする必要があり、記事をいろいろ調べたところ、Google Colab向けに書かれたReal-ESRGANだった。
そこでGoogle Colab向けに書かれたReal-ESRGANの高画質化スクリプトを、ローカルのPython 3.13環境で動かした際のハマりどころと解決手順をまとめます。

動作環境・フォルダ構成

作業フォルダ 画質UpPython の構成は以下のとおりです。

d:\画質UpPython\
├── input.png      # 元画像
├── output.png      # 出力画像(処理後に生成)
├── izon.py       # 依存ライブラリ・モデルのインストール
├── jiko.py       # 高画質化の実行スクリプト
├── weights/
│  └── RealESRGAN_x4plus.pth
├── BasicSR/       # GitHubからクローン・手動修正済み
└── Real-ESRGAN/    # 同上

スクリプトの解説

izon.py ― 環境構築・モデルダウンロード
元コードはColabの!pip install 構文でした。ローカル実行のため subprocess に書き換えています。

import os
import sys
import subprocess
import wget

print("依存ライブラリをインストール中...")
subprocess.check_call([sys.executable, "-m", "pip", "install",
                       "facexlib", "gfpgan", "resampy", "wget"])

model_dir = 'weights'
os.makedirs(model_dir, exist_ok=True)
model_url = ('https://github.com/xinntao/Real-ESRGAN/releases/'
             'download/v0.1.0/RealESRGAN_x4plus.pth')
model_path = os.path.join(model_dir, 'RealESRGAN_x4plus.pth')

if not os.path.exists(model_path):
    print("モデルをダウンロード中...")
    wget.download(model_url, model_path)
    print("\nダウンロード完了")

jiko.py ― 高画質化の実行

RRDBNet でネットワーク構造を定義し、RealESRGANer で4倍アップスケールを行います。GPU有無を自動判定し、GPUが使える場合はFP16(半精度)で高速化します。tile_size=800 の分割処理でメモリ消費を抑えています。

import cv2
import torch
from basicsr.archs.rrdbnet_arch import RRDBNet
from realesrgan import RealESRGANer

# ==========================================
# 設定項目
# ==========================================
input_image_path  = 'input.png'   # 元画像のパス
output_image_path = 'output.png'  # 保存先のパス
tile_size = 800                   # --tile 800 に相当(VRAM節約用、0でタイルなし)
scale = 4                         # -s 4 (4倍拡大)

# ==========================================
# 1. モデルのビルドと初期化
# ==========================================
model = RRDBNet(
    num_in_ch=3,
    num_out_ch=3,
    num_feat=64,
    num_block=23,
    num_grow_ch=32,
    scale=scale
)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type == 'cpu':
    print("【警告】GPUが認識されていません。処理に時間がかかるか、エラーになる可能性があります。")

upscaler = RealESRGANer(
    scale=scale,
    model_path='weights/RealESRGAN_x4plus.pth',
    model=model,
    tile=tile_size,            # タイルサイズを指定
    tile_pad=10,               # タイルの継ぎ目を滑らかにするバッファ
    pre_pad=0,
    half=True if device.type == 'cuda' else False,  # FP16で高速化
    device=device
)

# ==========================================
# 2. 画像の読み込みと高画質化の実行
# ==========================================
img = cv2.imread(input_image_path, cv2.IMREAD_UNCHANGED)

if img is None:
    raise FileNotFoundError(
        f"画像が見つかりません: {input_image_path}"
    )

print(f"処理開始: {img.shape[1]}x{img.shape[0]} px")

try:
    output, img_mode = upscaler.enhance(img, outscale=scale)
    cv2.imwrite(output_image_path, output)
    print(f"処理成功!保存先: {output_image_path} "
          f"({output.shape[1]}x{output.shape[0]} px)")
          
except Exception as e:
    print(f"エラーが発生しました: {e}")

💡 upscaler.enhance() の戻り値は (高画質化画像データ, カラーモード) のタプルです。保存には cv2.imwrite を使います。

Python 3.13 特有のエラー

pip install basicsrpip install git+https://github.com/xinntao/Real-ESRGAN.git を実行すると、次のエラーが発生します。

File "<string>", line 79, in get_version
KeyError: '__version__'

原因:Python 3.13での locals() の仕様変更
問題箇所は setup.pyget_version() です。

def get_version():
    with open(version_file, 'r') as f:
        exec(compile(f.read(), version_file, 'exec'))
    return locals()['__version__']  # ← ここで KeyError

Python 3.13 では、関数内で exec() を実行しても、その結果がデフォルトで locals() に反映されなくなりました。そのため __version__ が見つからず KeyError になります。

⚠️ 影響範囲:BasicSR と Real-ESRGAN の両リポジトリで同じ問題が発生します。両方の修正が必要です。

解決策:明示的な辞書を渡す
GitHubから各リポジトリをクローン
setup.pyget_version() を以下のように修正
pip install -e . でローカルインストール

def get_version():
    with open(version_file, 'r') as f:
        d = {}                                          # 明示的に辞書を用意
        exec(compile(f.read(), version_file, 'exec'), d)  # dの中で実行
    return d['__version__']

💡 exec(code, globals_dict) のように第2引数に辞書を渡すことで、実行結果を確実にキャプチャできます。Python 3.13以前でも動作します。

まとめ

ColabコードのローカルPython移植では !pipsubprocess.check_call に置き換える
Python 3.13 では exec() + locals() の組み合わせが機能しなくなった
setup.pyget_version() に明示的な辞書 d を渡す修正で解決
BasicSRReal-ESRGAN の両方を手動修正してから pip install -e . する

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?