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

AIプロンプトー試作日記9(Pythonによる画像生成)

    恥ずかしいことに今回は偶然にみつけた事実。

    まだまだAIを取り囲む技術的な部分を
    把握できていない....

    テーマはプログラミング言語Pythonによる画像生成です。

    ChatGPT上でスクリプト作成を指示すれば
    スクリプトの生成、実行も可能なPythonで画像生成ができる。
    正確に言うなら画像加工ができるということ。

    Python使用のポイントは
    プログラムなので生成時のパラメータを
    変更しなければ
    何度実行しても同じ画像になる、
    あるいは複数枚に同様の加工が施せる
    というところです。

    逆に画像上に「無いものを創出する」ということは
    できないのでAI自体とは役割を分担させるということ。

    ちなみにChatGPTにおいては、
    プロンプトでPython実行と加工後の処理の連結は
    APIがないとできないとのこと、
    別途有料プランになるようです。

    以下で、印象派風の画像生成スクリプトを
    作成、実行結果を載せておきます。

    尚、「写真を印象派様式の表現にするスクリプトを作って」で
    ここまでつくってくれます。
    (甘やかしすぎだ...)

    <以下、AIが作成、説明>

    Pythonスクリプトは単なる「油絵フィルター」ではなく、写真をいったん色面として整理し、その上へ方向・長さ・色が少しずつ異なる短い筆触を大量に重ねる構成です。モネやルノワールなど特定作家のコピーではなく、一般的な印象派絵画の視覚的特徴を狙っています。

    # impressionist.py
    #
    # Usage:
    #   python impressionist.py input.jpg output.png
    #   python impressionist.py input.jpg output.png --strength 1.5
    #   python impressionist.py input.jpg output.png --strength 2.0 --brushes 70000
    #
    # Requirements:
    #   pip install pillow numpy opencv-python
    
    import argparse
    import random
    import math
    
    import cv2
    import numpy as np
    from PIL import Image, ImageDraw, ImageFilter, ImageEnhance
    
    
    def clamp(v, lo=0, hi=255):
        return max(lo, min(hi, int(v)))
    
    
    def impressionist(
        image,
        strength=1.0,
        brushes=45000,
        min_brush=2,
        max_brush=12,
        color_variation=12,
        detail=0.65,
        seed=1234
    ):
        random.seed(seed)
        np.random.seed(seed)
    
        # ---------------------------------------------------------
        # 1. Load original image
        # ---------------------------------------------------------
        img = image.convert("RGB")
        w, h = img.size
    
        arr = np.array(img)
    
        # ---------------------------------------------------------
        # 2. Slightly simplify photographic detail
        #    Preserve objects and composition.
        # ---------------------------------------------------------
        sigma = 0.7 + strength * 0.8
    
        simplified = cv2.GaussianBlur(
            arr,
            (0, 0),
            sigmaX=sigma,
            sigmaY=sigma
        )
    
        # Preserve some original detail
        simplified = cv2.addWeighted(
            simplified,
            1.0 - detail * 0.20,
            arr,
            detail * 0.20,
            0
        )
    
        # ---------------------------------------------------------
        # 3. Calculate local edge direction
        #    Brush strokes loosely follow the image structure.
        # ---------------------------------------------------------
        gray = cv2.cvtColor(arr, cv2.COLOR_RGB2GRAY)
    
        gx = cv2.Sobel(
            gray,
            cv2.CV_32F,
            1, 0,
            ksize=3
        )
    
        gy = cv2.Sobel(
            gray,
            cv2.CV_32F,
            0, 1,
            ksize=3
        )
    
        magnitude = cv2.magnitude(gx, gy)
    
        # ---------------------------------------------------------
        # 4. Base painted color field
        # ---------------------------------------------------------
        base = Image.fromarray(simplified)
    
        # Impressionistic color enhancement
        base = ImageEnhance.Color(base).enhance(
            1.05 + strength * 0.12
        )
    
        base = ImageEnhance.Contrast(base).enhance(
            0.96
        )
    
        canvas = base.copy()
    
        # Separate transparent layer for brush strokes
        strokes = Image.new(
            "RGBA",
            (w, h),
            (0, 0, 0, 0)
        )
    
        draw = ImageDraw.Draw(strokes, "RGBA")
    
        src = np.array(base)
    
        # Scale brush size according to image resolution
        scale = max(w, h) / 2048.0
    
        bmin = max(1, int(min_brush * scale))
        bmax = max(bmin + 1, int(max_brush * scale))
    
        actual_brushes = int(
            brushes * (w * h) / (2048 * 2048)
        )
    
        actual_brushes = int(
            actual_brushes * strength
        )
    
        # ---------------------------------------------------------
        # 5. Paint short irregular strokes
        # ---------------------------------------------------------
        for _ in range(actual_brushes):
    
            x = random.randrange(w)
            y = random.randrange(h)
    
            r, g, b = src[y, x]
    
            edge = magnitude[y, x]
    
            # Follow tangent of local contour
            if edge > 12:
                angle = math.atan2(
                    gy[y, x],
                    gx[y, x]
                ) + math.pi / 2
    
                # Imperfect hand movement
                angle += random.uniform(
                    -0.45,
                    0.45
                )
    
            else:
                # Looser brushwork in flat regions
                angle = random.uniform(
                    0,
                    math.pi
                )
    
            # Brush size
            length = random.randint(
                bmin * 2,
                bmax * 2
            )
    
            width = random.randint(
                max(1, bmin),
                max(2, bmax // 2)
            )
    
            # Smaller strokes around detailed edges
            if edge > 35:
                length = max(
                    2,
                    int(length * 0.55)
                )
    
                width = max(
                    1,
                    int(width * 0.65)
                )
    
            # Slight pigment variation
            variation = color_variation * strength
    
            rr = clamp(
                r + random.gauss(0, variation)
            )
    
            gg = clamp(
                g + random.gauss(0, variation)
            )
    
            bb = clamp(
                b + random.gauss(0, variation)
            )
    
            alpha = random.randint(
                45,
                115
            )
    
            dx = math.cos(angle) * length / 2
            dy = math.sin(angle) * length / 2
    
            x1 = x - dx
            y1 = y - dy
            x2 = x + dx
            y2 = y + dy
    
            # Main stroke
            draw.line(
                (x1, y1, x2, y2),
                fill=(rr, gg, bb, alpha),
                width=width
            )
    
            # Small highlight / pigment irregularity
            if random.random() < 0.18:
    
                highlight = random.randint(
                    5, 20
                )
    
                hr = clamp(rr + highlight)
                hg = clamp(gg + highlight)
                hb = clamp(bb + highlight)
    
                draw.line(
                    (
                        x1,
                        y1,
                        x2 - dx * 0.25,
                        y2 - dy * 0.25
                    ),
                    fill=(hr, hg, hb, alpha // 2),
                    width=max(1, width // 3)
                )
    
        # ---------------------------------------------------------
        # 6. Composite brush layer
        # ---------------------------------------------------------
        canvas = Image.alpha_composite(
            canvas.convert("RGBA"),
            strokes
        ).convert("RGB")
    
        # ---------------------------------------------------------
        # 7. Subtle pigment / canvas texture
        # ---------------------------------------------------------
        result = np.array(canvas).astype(
            np.int16
        )
    
        noise_amount = max(
            1,
            int(2.0 * strength)
        )
    
        noise = np.random.normal(
            0,
            noise_amount,
            result.shape[:2]
        )
    
        # Same noise across RGB channels = physical texture,
        # not colored digital noise.
        result += noise[:, :, None].astype(
            np.int16
        )
    
        result = np.clip(
            result,
            0,
            255
        ).astype(np.uint8)
    
        result = Image.fromarray(result)
    
        # Avoid digitally sharp output
        result = result.filter(
            ImageFilter.GaussianBlur(
                radius=0.12 * strength
            )
        )
    
        return result
    
    
    def main():
    
        parser = argparse.ArgumentParser(
            description=
            "Transform a photograph into an Impressionist-style painting."
        )
    
        parser.add_argument(
            "input",
            help="Input photograph"
        )
    
        parser.add_argument(
            "output",
            help="Output image"
        )
    
        parser.add_argument(
            "--strength",
            type=float,
            default=1.0,
            help="Painting strength (default: 1.0)"
        )
    
        parser.add_argument(
            "--brushes",
            type=int,
            default=45000,
            help="Number of brush strokes for a 2048x2048 image"
        )
    
        parser.add_argument(
            "--min-brush",
            type=int,
            default=2
        )
    
        parser.add_argument(
            "--max-brush",
            type=int,
            default=12
        )
    
        parser.add_argument(
            "--color-variation",
            type=float,
            default=12
        )
    
        parser.add_argument(
            "--seed",
            type=int,
            default=1234
        )
    
        args = parser.parse_args()
    
        image = Image.open(args.input)
    
        result = impressionist(
            image,
            strength=args.strength,
            brushes=args.brushes,
            min_brush=args.min_brush,
            max_brush=args.max_brush,
            color_variation=args.color_variation,
            seed=args.seed
        )
    
        result.save(
            args.output,
            quality=95
        )
    
        print(
            f"Saved: {args.output}"
        )
    
    
    if __name__ == "__main__":
        main()

    まず基準値として、

    python impressionist.py input.jpg output.png --strength 1.0

    を試すのがよいです。もう少し筆触を強くしたければ、

    python impressionist.py input.jpg output.png --strength 2.0 --brushes 60000

    とします。

    この方式のポイントは、輪郭線を油絵フィルターでベタッと潰さないことです。元写真の色を筆ごとに拾い、隣り合う筆触の色をわずかに変化させます。また、輪郭付近では筆を細かくし、平坦な場所では方向を散らすので、「写真にフィルターをかけた感じ」よりも「写真を見ながら描き直した感じ」に寄せられます。

    <生成結果>

    画像
    生成前と生成後


    こういう発見があるから楽しいのですが、
    日々精進ですね...



     
     
    元システムエンジニア。男性、還暦過ぎ。 現役を退いて、写真撮影に現を抜かす生活。 いや抜かせていない.. 新しいもの好き

    あなたへのおすすめ