背景処理をcolabのセル内の処理で実行しようと思っていてrembgを使用していたところ、エラーになりました。状況としては、この記事と同じです。
リンクが貼られているこれを経由して辿っていくと依存関係にあるu2netを再ダウンロードする?のが必要なようですが、readmeを参考に試したところうまくいきません。
該当のコード( google colab, python 3.7)
!pip install rembg
ランタイムを再起動
!sed -i -e "67c @functools.lru_cache(maxsize=None)" /usr/local/lib/python3.7/dist-packages/rembg/bg.py
from rembg.bg import remove
import numpy as np
import io
from PIL import Image
input_path = '/apple.png'# アップロード済のpathを指定
output_path = 'out.png'
f = np.fromfile(input_path)
result = remove(f)
img = Image.open(io.BytesIO(result)).convert("RGBA")
img.save(output_path)
エラーコード
u2net.pth: 2.15kiB [00:00, 790kiB/s]
---------------------------------------------------------------------------
UnpicklingError Traceback (most recent call last)
<ipython-input-1-a54fab58f517> in <module>()
12
13 f = np.fromfile(input_path)
---> 14 result = remove(f)
15 img = Image.open(io.BytesIO(result)).convert("RGBA")
16 img.save(output_path)
4 frames
/usr/local/lib/python3.7/dist-packages/rembg/bg.py in remove(data, model_name, alpha_matting, alpha_matting_foreground_threshold, alpha_matting_background_threshold, alpha_matting_erode_structure_size)
81 alpha_matting_erode_structure_size=10,
82 ):
---> 83 model = get_model(model_name)
84 img = Image.open(io.BytesIO(data)).convert("RGB")
85 mask = detect.predict(model, np.array(img)).convert("L")
/usr/local/lib/python3.7/dist-packages/rembg/bg.py in get_model(model_name)
70 return detect.load_model(model_name="u2netp")
71 else:
---> 72 return detect.load_model(model_name="u2net")
73
74
/usr/local/lib/python3.7/dist-packages/rembg/u2net/detect.py in load_model(model_name)
70 net.to(torch.device("cuda"))
71 else:
---> 72 net.load_state_dict(torch.load(path, map_location="cpu",))
73 except FileNotFoundError:
74 raise FileNotFoundError(
/usr/local/lib/python3.7/dist-packages/torch/serialization.py in load(f, map_location, pickle_module, **pickle_load_args)
583 return torch.jit.load(opened_file)
584 return _load(opened_zipfile, map_location, pickle_module, **pickle_load_args)
--> 585 return _legacy_load(opened_file, map_location, pickle_module, **pickle_load_args)
586
587
/usr/local/lib/python3.7/dist-packages/torch/serialization.py in _legacy_load(f, map_location, pickle_module, **pickle_load_args)
753 "functionality.".format(type(f)))
754
--> 755 magic_number = pickle_module.load(f, **pickle_load_args)
756 if magic_number != MAGIC_NUMBER:
757 raise RuntimeError("Invalid magic number; corrupt file?")
UnpicklingError: invalid load key, '<'.
実行したこと
u2netのreadmeより
(1) colab上で
!git clone https://github.com/NathanUA/U-2-Net.git
を実行、u2netを入手
(2) u2netのリンクにあるGoogleDriveから、u2net_portrait.pth
をダウンロード、./saved_models/
内に/u2net_portrait/
を新しく作成し(初期状態ではなかった)./saved_models/u2net_portrait/
にu2net_portrait.pth
を移動
(3)該当のコードをもう一度実行(結果同じ)