メインコンテンツへスキップ
見出し画像

”たまに”同じ画像が2枚生成されるStable Diffusion WebUIの仕様について

    みなさん、Stable Diffusion で楽しく画像生成(ガチャ)していますか?

    日々プロンプトをこねくり回し、理想の美少女や美麗な背景を追い求めている我が同志たちよ。ある日、出力先の `outputs` フォルダを見て、こんな奇妙な現象に遭遇したことはないでしょうか。

    「あれ? なんで同じ画像が2枚並んでるんだ……?」

    画像
    一回生成しただけなのに

    よく見ると、片方はおなじみの `png`、もう片方は `jpg`。

    画像

    心霊現象か、はたまた私の PC が疲れて幻覚を見せているのか。今回は、この「容量が大きくなると勝手に JPG が増殖する怪事件」の犯人を徹底的にプログラミングの裏側まで追い詰めた、血と汗と AI の共同捜査記録をお届けします。


    1. 契機:突如として現れる「双子のJPG」

    事件の始まりは、高解像度化(Hires. fix)や大きなサイズでの生成を試していたときでした。

    いつも通りフォルダを確認すると、そこには完全に同じ見た目の画像が2枚。
    「グラボがサービスしてくれたのかな?」なんて一瞬喜びそうになりますが、ストレージの容量は確実に2倍食われています。嘘つけ、jpgの圧縮率をなめるな。サイズは8分の1ぐらいです。まあ非可逆圧縮だからね。

    片方は高画質な PNG、もう片方は軽量な JPG。
    毎回起きるわけではなく、「なんか画像が大きくて重いとき」に限って、この双子の JPG がひっそりと生成されているのです。一体なぜ……?


    2. ネットの海へ:Google 先生、教えて!

    困ったときの Google 頼み。さっそく「Stable Diffusion 2枚保存される jpg png」などで検索を開始しました。

    しかし、出てくるのは以下のような、ちょっとふんわりした情報ばかり。

    「4MBか5MBを超える高解像度の画像が出力されたときには、PNGとJPEGで2枚出力されますよね。」
    (出典:Amebaブログ「Stable Diffusion 呪文忘備録」)

    いや、現象としてはまさにこれなんです。ドンピシャなんです。
    でも、「なぜ4MBを超えると2枚になるのか」の根本的な理由がわからない!

    「そういう仕様だから」で片付けるには、あまりにも中途半端な数字。
    4MB、5MBという境界線には、絶対に人為的に仕組まれた「開発者の意図」があるはずです。


    3. 禁断の手段:AIを相棒にソースコードのガサ入れ

    ネットの記事がダメなら、WebUI の中身(ソースコード)を直接ひっぺがして見るしかありません。

    とはいえ、筆者は Python のコードを前にすると秒で眠くなる体質。そこで、文明の利器である AI(Gemini) を相棒に迎え、WebUI の心臓部である `images.py` や `processing.py` といったプログラムファイルを片っ端から食わせて「ガサ入れ」を敢行しました。

    「おい AI、この中に『4MBを超えたらJPGを作る』っていう怪しい条件文(if文)が隠れているはずだ。探せ!」

    AI と二人三脚で、何千行もあるコードの海をひたすら泳ぎ、それっぽい関数を執拗にマークしていきます。てついに、`images.py` の中に動かぬ証拠を発見したのです。


    4. 真真:犯人は海外の巨大掲示板「4chan」だった!

    save_image関数の末尾のあたりにある    if opts.export_for_4chan and (oversize or os.stat(fullfn).st_size > opts.img_downscale_threshold * 1024 * 1024):に着目しました。opts.img_downscale_thresholdという定数は4でありまさに4Mbyteを超えたら・・・のIF文です。そしてコードの中に堂々と刻まれていた文字、それは `export_for_4chan`。

    そう、犯人はあの海外の超巨大画像掲示板「4chan」でした!

    画像
    オタクならみんな知っている

    ※念のため問題のソースコードを以下に示します。

    【.\modules\images.py】より抜粋
    
    def save_image(image, path, basename, seed=None, prompt=None, extension="png", info=None, short_filename=False, no_prompt=False, grid=False, pnginfo_section_name="parameters", p=None, existing_info=None, forced_filename=None, suffix="", save_to_dirs=None):
        """Save an image.
    
        Args:
            image (`PIL.Image`):
                The image to be saved.
            path (`str`):
                The directory to save the image. Note, the option `save_to_dirs` will make the image to be saved into a sub directory.
            basename (`str`):
                The base filename which will be applied to `filename pattern`.
            seed, prompt, short_filename,
            extension (`str`):
                Image file extension, default is `png`.
            pngsectionname (`str`):
                Specify the name of the section which `info` will be saved in.
            info (`str` or `PngImagePlugin.iTXt`):
                PNG info chunks.
            existing_info (`dict`):
                Additional PNG info. `existing_info == {pngsectionname: info, ...}`
            no_prompt:
                TODO I don't know its meaning.
            p (`StableDiffusionProcessing` or `Processing`)
            forced_filename (`str`):
                If specified, `basename` and filename pattern will be ignored.
            save_to_dirs (bool):
                If true, the image will be saved into a subdirectory of `path`.
    
        Returns: (fullfn, txt_fullfn)
            fullfn (`str`):
                The full path of the saved imaged.
            txt_fullfn (`str` or None):
                If a text file is saved for this image, this will be its full path. Otherwise None.
        """
        namegen = FilenameGenerator(p, seed, prompt, image, basename=basename)
    
        # WebP and JPG formats have maximum dimension limits of 16383 and 65535 respectively. switch to PNG which has a much higher limit
        if (image.height > 65535 or image.width > 65535) and extension.lower() in ("jpg", "jpeg") or (image.height > 16383 or image.width > 16383) and extension.lower() == "webp":
            print("Image dimensions too large; saving as PNG")
            extension = "png"
    
        if save_to_dirs is None:
            save_to_dirs = (grid and opts.grid_save_to_dirs) or (not grid and opts.save_to_dirs and not no_prompt)
    
        if save_to_dirs:
            dirname = namegen.apply(opts.directories_filename_pattern or "[prompt_words]").lstrip(" ").rstrip("\\ /")
            path = os.path.join(path, dirname)
    
        os.makedirs(path, exist_ok=True)
    
        if forced_filename is None:
            if short_filename or seed is None:
                file_decoration = ""
            elif hasattr(p, "override_settings"):
                file_decoration = p.override_settings.get("samples_filename_pattern")
            else:
                file_decoration = None
    
            if file_decoration is None:
                file_decoration = opts.samples_filename_pattern or ("[seed]" if opts.save_to_dirs else "[seed]-[prompt_spaces]")
    
            file_decoration = namegen.apply(file_decoration) + suffix
    
            add_number = opts.save_images_add_number or file_decoration == ""
    
            if file_decoration != "" and add_number:
                file_decoration = f"-{file_decoration}"
    
            if add_number:
                basecount = get_next_sequence_number(path, basename)
                fullfn = None
                for i in range(500):
                    fn = f"{basecount + i:05}" if basename == "" else f"{basename}-{basecount + i:04}"
                    fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}")
                    if not os.path.exists(fullfn):
                        break
            else:
                fullfn = os.path.join(path, f"{file_decoration}.{extension}")
        else:
            fullfn = os.path.join(path, f"{forced_filename}.{extension}")
    
        pnginfo = existing_info or {}
        if info is not None:
            pnginfo[pnginfo_section_name] = info
    
        params = script_callbacks.ImageSaveParams(image, p, fullfn, pnginfo)
        script_callbacks.before_image_saved_callback(params)
    
        image = params.image
        fullfn = params.filename
        info = params.pnginfo.get(pnginfo_section_name, None)
    
        def _atomically_save_image(image_to_save, filename_without_extension, extension):
            """
            save image with .tmp extension to avoid race condition when another process detects new image in the directory
            """
            temp_file_path = f"{filename_without_extension}.tmp"
    
            save_image_with_geninfo(image_to_save, info, temp_file_path, extension, existing_pnginfo=params.pnginfo, pnginfo_section_name=pnginfo_section_name)
    
            filename = filename_without_extension + extension
            without_extension = filename_without_extension
            if shared.opts.save_images_replace_action != "Override":
                n = 0
                while os.path.exists(filename):
                    n += 1
                    without_extension = f"{filename_without_extension}-{n}"
                    filename = without_extension + extension
            os.replace(temp_file_path, filename)
            return without_extension
    
        fullfn_without_extension, extension = os.path.splitext(params.filename)
        if hasattr(os, "statvfs"):
            max_name_len = os.statvfs(path).f_namemax
            fullfn_without_extension = fullfn_without_extension[: max_name_len - max(4, len(extension))]
            params.filename = fullfn_without_extension + extension
            fullfn = params.filename
    
        fullfn_without_extension = _atomically_save_image(image, fullfn_without_extension, extension)
        fullfn = fullfn_without_extension + extension
        image.already_saved_as = fullfn
    
        oversize = image.width > opts.target_side_length or image.height > opts.target_side_length
        if opts.export_for_4chan and (oversize or os.stat(fullfn).st_size > opts.img_downscale_threshold * 1024 * 1024):
            ratio = image.width / image.height
            resize_to = None
            if oversize and ratio > 1:
                resize_to = round(opts.target_side_length), round(image.height * opts.target_side_length / image.width)
            elif oversize:
                resize_to = round(image.width * opts.target_side_length / image.height), round(opts.target_side_length)
    
            if resize_to is not None:
                try:
                    # Resizing image with LANCZOS could throw an exception if e.g. image mode is I;16
                    image = image.resize(resize_to, LANCZOS)
                except Exception:
                    image = image.resize(resize_to)
            try:
                _ = _atomically_save_image(image, fullfn_without_extension, ".jpg")
            except Exception as e:
                errors.display(e, "saving image as downscaled JPG")
    
        if opts.save_txt and info is not None:
            txt_fullfn = f"{fullfn_without_extension}.txt"
            with open(txt_fullfn, "w", encoding="utf8") as file:
                file.write(f"{info}\n")
        else:
            txt_fullfn = None
    
        script_callbacks.image_saved_callback(params)
    
        return fullfn, txt_fullfn

    実は 4chan に画像をアップロードする際、「PNGファイルは最大4Mbyteまで」というサイズ制限(縛り)が存在します。
    WebUI の親切な開発者はこう考えたのでしょう。

    「ユーザーが高解像度な神絵(PNG)を作ったのに、4chan に貼れなくて絶望したら可哀想だな……よし! 4MB を超えたら、自動的に 4chan にそのまま貼れる軽量な JPG も横に添えて出力してあげる親切機能を実装しよう!」

    これこそが、4MBを超えたときに突如として JPG が召喚されるシステムの正体でした。謎がすべて美しく解けましたね!


    5. 対策:この機能を飼い慣らす設定方法

    原因がわかれば、あとはこっちのものです。この「4chan親切システム」の閾値は、プログラムを書き換えなくても、WebUI の設定画面から自由にいじることができます。

    WebUI の `Settings` タブから `Show all pages` を開き、`File size limit for the above option` という項目を探してください。

    画像

    ここをどういじるかで、あなたの WebUI の挙動をコントロールできます。

    • 「2枚出力されるのがぶっちゃけ煩わしい、PNGだけでいい!」という人
      👉 閾値の数字を `9999` などのめちゃくちゃ大きい数字に書き換えましょう。これで実質的に機能が眠りにつき、余計な JPG は生成されなくなります。

    • 「容量に関係なく、常にPNGとJPGを両方セットで出力したい!」という人
      👉 閾値を `0` にしましょう。これで、どんなに小さな画像であっても「0MBの壁」を突破するため、常に両方の形式が仲良く出力されるようになります。なお筆者の環境だとapply settingsおよびReload UIをすると盛大にエラーをぶちまけ始めましたが、普通にリスタートで治りましたし、想定通り、常にPNGとJPG両方セットで出力されるようになりました。

    画像
    常にpngとjpgがせってで出力されている図。

    まとめ:ソースコードの裏には開発者の愛があった

    「バグかな?」とか「不具合かな?」と疑ってしまった今回の2枚出力現象ですが、蓋を開けてみれば「4chanの住人に向けた、開発者の底なしの優しさ」が生んだ仕様でした。

    ネットの不確かな情報で妥協せず、ソースコードまで潜ってみると思わぬドラマ(と4chan)に出会えるものですね。

    同じ現象でフォルダがパンパンになって困っている方がいたら、ぜひ設定を見直してみてください!
    それでは、良き AI ガチャライフを!

    あなたへのおすすめ