メインコンテンツへスキップ

yolov5でRuntimeError: Sizes of tensors must match except in dimension 1.

·98 文字·1 分
Captain Emo
著者
Captain Emo
ドメイン知識の抽出、テスト作成、React/Nodeを得意としています。

yolov5 を動かして手元の画像を判定させたら下記エラーになった。

RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 46 but got size 45 for tensor number 1 in the list.

画像のサイズは 64 の倍数である必要があるらしい。

参考: https://github.com/CompVis/stable-diffusion/issues/301#issuecomment-1251629833

画像を読み込んだ後、余白を足してやることで無事動いた

# 画像を処理する関数
def process_image(image_path):
    image = Image.open(image_path)

    # 画像サイズが64の倍数でないとテンソルエラーになるので余白を足す
    width, height = image.size
    new_width = width
    new_height = height

    if width % 64 != 0:
        multiplier = math.ceil(width / 64)
        new_width = multiplier * 64

    if height % 64 != 0:
        multiplier = math.ceil(height / 64)
        new_height = multiplier * 64

    # 新しい画像の背景(白)を作成
    new_img = Image.new("RGB", (new_width, new_height), "white")

    # 元の画像を左上に配置
    new_img.paste(image, (0, 0))

    return new_img