Skip to content

Claude paints with code: a Claude Code skill for procedural illustration in 83 styles, from ink wash (水墨), watercolour and ukiyo-e to stained glass, Roman mosaic, Art Deco, shadow puppets, pastel UI, sketchbook doodles, spot illustrations, grainy picture books, dreamy hills, sunlit greenery. No image model: numpy + Pillow on a CPU, draw-on GIFs.

Add impasto oil, ukiyo-e and pixel-art styles; one example per style

cloveric9811f63d8d95
diff --git a/README.md b/README.md
index c9f2a93..d81406c 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
# Claude Drawing · Claude 绘图
-**Claude paints with code — no image model.** Ink wash · watercolour · paper collage · coloured pencil · anime · editorial.
-**不用生图模型,Claude 用代码一笔一笔作画。** 水墨 · 水彩 · 剪纸拼贴 · 韩国彩铅 · 日本动漫 · 编辑风手绘。
+**Claude paints with code — no image model.** Nine styles, from ink wash to pixel art.
+**不用生图模型,Claude 用代码一笔一笔作画。** 九种画风,从水墨到像素。
[English](#english) · [中文](#中文)
@@ -10,18 +10,23 @@
| ![ink](examples/drawing_bawansiqian.gif) | ![watercolour](examples/drawing_watercolor_autumn.gif) | ![collage](examples/drawing_papercut_balloons.gif) |
| **Coloured pencil · 韩国彩铅** | **Anime · 日本动漫** | **Editorial · 编辑风手绘** |
| ![pencil](examples/drawing_colorpencil_dessert.gif) | ![anime](examples/drawing_anime_summer.gif) | ![editorial](examples/drawing_editorial_ideas.gif) |
+| **Impasto oil · 油画厚涂** | **Ukiyo-e · 浮世绘木版画** | **Pixel art · 像素风** |
+| ![oil](examples/drawing_oil_wheatfield.gif) | ![ukiyoe](examples/drawing_ukiyoe_fuji.gif) | ![pixel](examples/drawing_pixel_rainy_cafe.gif) |
-| 八万四千法门 · *Many paths, one summit* | 月印万川 · *One moon in ten thousand rivers* |
-|---|---|
-| ![bawansiqian](examples/bawansiqian.jpg) | ![moon_river](examples/moon_river.jpg) |
-| **秋日湖畔** · *Autumn Lake* | **热气球小镇** · *Balloon Day* |
-| ![autumn](examples/watercolor_autumn.jpg) | ![balloons](examples/papercut_balloons.jpg) |
-| **午后甜点** · *Afternoon Dessert* | **夏空** · *Summer Sky* |
-| ![dessert](examples/colorpencil_dessert.jpg) | ![anime](examples/anime_summer.jpg) |
-| **灵感生长** · *Growing Ideas* | |
-| ![ideas](examples/editorial_ideas.jpg) | |
+<details>
+<summary><b>Full-size gallery · 大图</b></summary>
-Every mark above is computed: paper fibres, ink washes and mist, dry-brush strokes, pigment granulation and blooms, torn-paper edges, pencil wax on paper tooth, cel-shaded clouds, risograph grain and halftones. No diffusion model, no API, no stock art. It is just Python with **numpy + Pillow** on a CPU: 2–4 s for an ink painting and 10–30 s for the other styles, at 1920×1080.
+| 八万四千法门 · *Many Paths, One Summit* | 秋日湖畔 · *Autumn Lake* | 热气球小镇 · *Balloon Day* |
+|---|---|---|
+| ![](examples/bawansiqian.jpg) | ![](examples/watercolor_autumn.jpg) | ![](examples/papercut_balloons.jpg) |
+| **午后甜点** · *Afternoon Dessert* | **夏空** · *Summer Sky* | **灵感生长** · *Growing Ideas* |
+| ![](examples/colorpencil_dessert.jpg) | ![](examples/anime_summer.jpg) | ![](examples/editorial_ideas.jpg) |
+| **麦田星空** · *Swirling Sky over the Wheat Field* | **富士曙** · *Fuji at Dawn* | **雨夜咖啡店** · *Rainy Night Cafe* |
+| ![](examples/oil_wheatfield.jpg) | ![](examples/ukiyoe_fuji.jpg) | ![](examples/pixel_rainy_cafe.png) |
+
+</details>
+
+Every mark above is computed: paper fibres, ink washes and mist, dry-brush strokes, pigment granulation and blooms, torn-paper edges, pencil wax on paper tooth, cel-shaded clouds, risograph grain and halftones, lit impasto relief, woodblock grain and bokashi, dithered pixels. No diffusion model, no API, no stock art. It is just Python with **numpy + Pillow** on a CPU: from 0.1 s (pixel art) to about 30 s per 1920×1080 image.
---
@@ -29,28 +34,31 @@ Every mark above is computed: paper fibres, ink washes and mist, dry-brush strok
### What it is
-A [Claude Code](https://claude.com/claude-code) skill and a small painting library with six styles:
+A [Claude Code](https://claude.com/claude-code) skill and a small painting library with nine styles:
| Style | Module | What makes it read as the real medium |
|---|---|---|
-| **Ink wash (水墨)** | `lib/inkpaint.py` · `Painting` | rice paper; occluding washes with wet rims and mist; bristle brush with flying-white; texture strokes (皴); moss dots; pines, boats, reeds; a moon reserved in white; calligraphy and seal |
-| **Watercolour** | `lib/watercolor.py` · `Watercolor` | cold-press paper tooth; *transparent glazes* that mix subtractively; wet-edge darkening; granulation; blooms (back-runs); wet-in-wet feathering; lifting; splatter |
-| **Paper collage** | `lib/papercut.py` · `Collage` | torn edges with a white fibrous core; paper depth shadows; coloured, kraft, crayon, newsprint and ruled-notebook papers; waxy crayon lines; cute faces with blush |
-| **Coloured pencil (Korean style)** | `lib/colorpencil.py` · `ColorPencil` | short directional hatching; wax that only catches on the paper tooth, with pressure pushing into the valleys; soft layered blending; light brown pencil outlines; white gel-pen sparkles |
-| **Anime (Japanese)** | `lib/anime.py` · `Anime` | saturated gradient skies; towering cumulus with *crescent* cel shadows on every puff; sun bloom, god rays and lens flare; flat-shaded fields, perspective roads, sagging power lines; clean line-art characters |
-| **Editorial (risograph)** | `lib/editorial.py` · `Editorial` | 4–5 spot inks on cream stock; per-ink grain, uneven density and mis-registration; translucent overprinting (overlaps make new colours); halftone shading; wobbly hand-drawn line; big simple shapes and stylised figures |
-
-Ask Claude to *"draw it yourself"*, *"paint this with code"*, or *"claude绘图"*. It then works in three steps:
-
-1. **Plan the composition**: layers, a focal point, breathing space, one accent colour, and a subject that illustrates the idea rather than generic scenery.
-2. **Write a short scene script** using the library.
-3. **Render it, look at the result, and fix it** against a per-style checklist of real failure modes, usually over 2–4 rounds.
+| **Ink wash (水墨)** | `lib/inkpaint.py` · `Painting` | rice paper; occluding washes with wet rims and mist; bristle brush with flying-white; texture strokes (皴); moss dots; pines, boats, reeds; calligraphy and seal |
+| **Watercolour** | `lib/watercolor.py` · `Watercolor` | cold-press paper tooth; *transparent glazes* that mix subtractively; wet-edge darkening; granulation; blooms; wet-in-wet feathering; reflections; lifting |
+| **Paper collage** | `lib/papercut.py` · `Collage` | torn edges with a white fibrous core; paper depth shadows; kraft, crayon, newsprint and ruled-notebook papers; waxy crayon lines; cute faces |
+| **Coloured pencil (Korean style)** | `lib/colorpencil.py` · `ColorPencil` | short directional hatching; wax that catches on the paper tooth, with pressure reaching the valleys; soft layered blending; brown pencil outlines; gel-pen sparkles |
+| **Anime (Japanese)** | `lib/anime.py` · `Anime` | gradient skies; cumulus with *crescent* cel shadows on every puff; bloom, god rays, lens flare; flat-shaded fields, perspective roads, power lines; line-art characters |
+| **Editorial (risograph)** | `lib/editorial.py` · `Editorial` | 4–5 spot inks with grain, uneven density and mis-registration; overprinting; halftone shading; wobbly hand-drawn line; stylised figures |
+| **Impasto oil** | `lib/oilpaint.py` · `OilPainting` | thousands of strokes following a *flow field*; each pixel knows its place inside its stroke → flat-topped paint ridges, bristle grooves, heavier paint where the brush lands; lit relief |
+| **Ukiyo-e woodblock** | `lib/ukiyoe.py` · `Ukiyoe` | one block per colour on washi, with wood grain and registration drift; *bokashi* graded wipes; black key-block outlines; seigaiha waves; cloud bands; title cartouche and seal |
+| **Pixel art** | `lib/pixelart.py` · `PixelArt` | a 320×180 canvas painted pixel by pixel; limited palette; ordered (Bayer) dithering for gradients, glows and reflections; 3×5 bitmap font; crisp ×6 upscale |
+
+Ask Claude to *"draw it yourself"*, *"paint this with code"*, or *"claude绘图"*, and name a style if you like. Claude then:
+
+1. **Plans the composition**: layers, a focal point, breathing space, and a subject that illustrates the idea.
+2. **Writes a short scene script** using the library.
+3. **Renders it, looks at the result, and fixes it** against a per-style checklist of real failure modes, usually over 2–4 rounds.
### Why code instead of an image model?
- **Directed composition**: placement, empty space and accents are exact, not sampled.
-- **Reproducible**: the same seed gives the same painting.
-- **Animatable**: `stage()` snapshots let a video show the painting *being made*. The GIFs above are exactly that; a generated bitmap can't do it.
+- **Reproducible**: the same seed gives the same picture.
+- **Animatable**: `stage()` snapshots let a video show the picture *being made*. The GIFs above are exactly that; a generated bitmap can't do it.
- **Runs anywhere**: offline, on a CPU, with no GPU, key or quota.
### Install
@@ -90,21 +98,23 @@ c.piece(mask=c.circle_mask(1360, 300, 150), colour='#f6d77a', texture='crayon')
c.face(1360, 310, 128, mood='sleep'); c.save("collage.png")
```
-Full scenes: `python3 examples/<name>.py out.png --stages stages/`. `--stages` also writes the draw-on snapshots.
+Every style has a complete example: `python3 examples/<name>.py out.png --stages stages/`. `--stages` also writes the draw-on snapshots.
### Principles (the checklist Claude uses)
-- **Ink**: paint far to near, and each wash occludes what is behind it. Tie dab spacing to bristle size so strokes never look beaded. Paths should be few, smooth and emerge from mist. Texture strokes should be long, follow the slope and sit on the shadow side. Ridge lines stay light and broken.
-- **Watercolour**: keep the paper tooth subtle. Pool shadows wet-in-wet on one side (no bull's-eyes). Paint stems before leaves and keep them outside the leaf. Use at most three glazes in one place, and save lights or lift them out.
-- **Collage**: big areas use flat or kraft paper, and crayon texture is only for accents. Torn white rims are 5–8 px wide and appear on only part of an edge. Shadows use a zero-padded shift, never a wrap-around one. A moon gets a halo, not sun rays.
-- **Coloured pencil**: hatch densely enough that strokes saturate, and let pressure decide how deep the wax reaches into the tooth. White objects (cream, china) are warm off-white with lavender or blue-grey shading, never white on white.
-- **Anime**: clouds are many lumpy puffs, each with a hard crescent shadow (the puff minus itself shifted toward the sun), not smooth circles with straight terminators. Keep characters' proportions (hem near the knee).
-- **Editorial**: use 4–5 inks and overlap them on purpose so overprints make the extra colours. Every ink layer gets grain, uneven density and a few pixels of mis-registration, otherwise it looks like clip-art.
+- **Ink**: paint far to near, and each wash occludes what is behind it. Tie dab spacing to bristle size so strokes never look beaded. Paths should be few, smooth and emerge from mist. Texture strokes are long, follow the slope and sit on the shadow side.
+- **Watercolour**: keep the paper tooth subtle. Pool shadows wet-in-wet on one side, not in bull's-eyes. Keep darker glazes inside the first crown. Use at most three glazes in one place.
+- **Collage**: big areas use flat or kraft paper, and crayon texture is only for accents. Torn white rims are 5–8 px wide and appear on only part of an edge. Shadows use a zero-padded shift.
+- **Coloured pencil**: hatch densely enough to saturate, and let pressure decide how deep the wax reaches. White objects are warm off-white with lavender or blue-grey shading, never white on white.
+- **Anime**: clouds are many lumpy puffs, each with a hard crescent shadow (the puff minus itself shifted toward the sun). Keep character proportions right.
+- **Editorial**: use 4–5 inks and overlap them on purpose. Every ink layer gets grain, uneven density and a few pixels of mis-registration.
+- **Oil**: lay big strokes first, then smaller ones, then detail only where it matters. Keep the relief modest (flat-topped ridges, soft speculars), or strokes turn into plastic tubes.
+- **Ukiyo-e**: flat colour blocks plus bokashi only on skies and seas. Clouds are opaque bands. The key block outlines everything, and a cartouche and seal sit in the empty sky.
+- **Pixel art**: paint at the true low resolution and dither instead of blending. Keep glows small (a big dither glow turns into a square). Upscale with nearest-neighbour only.
### Roadmap
- Per-stroke layer export, for stroke-by-stroke animation in Motion Canvas or Remotion.
-- More styles on the same core, such as gouache, woodblock print and pencil sketch.
---
@@ -112,19 +122,22 @@ Full scenes: `python3 examples/<name>.py out.png --stages stages/`. `--stages` a
### 这是什么
-一个 [Claude Code](https://claude.com/claude-code) skill,加上一个小巧的绘图库,内置六种画风:
+一个 [Claude Code](https://claude.com/claude-code) skill,加上一个小巧的绘图库,内置九种画风:
| 画风 | 模块 | 为什么看起来像真的 |
|---|---|---|
-| **水墨** | `lib/inkpaint.py` · `Painting` | 宣纸纹理;会遮挡身后的墨染山体,带水痕边和雾;分笔毛的毛笔与飞白;皴擦、苔点;松、孤舟、芦苇;烘云托月的留白月亮;题字与印章 |
-| **水彩** | `lib/watercolor.py` · `Watercolor` | 冷压水彩纸纹理;**透明罩染**,叠色像真颜料一样变深、混色;水痕边;颜料颗粒;水渍花;湿画晕开;提白;甩点 |
-| **剪纸拼贴** | `lib/papercut.py` · `Collage` | 撕纸露出的白色纤维边;纸片层叠的阴影;彩纸、牛皮纸、蜡笔、报纸、笔记本横线纸;蜡笔线条;带腮红的可爱圆脸 |
-| **韩国彩铅** | `lib/colorpencil.py` · `ColorPencil` | 细密的短排线;蜡只挂在纸纹凸起上,用力越大越能压进凹处;柔和叠色;浅褐色铅笔勾线;白色高光笔 |
-| **日本动漫** | `lib/anime.py` · `Anime` | 高饱和的天空渐变;每个鼓包都带**月牙形**硬边暗面的积雨云;阳光泛光、光束、镜头光斑;平涂田野、透视公路、下垂的电线;干净线稿的角色 |
-| **编辑风手绘** | `lib/editorial.py` · `Editorial` | 米色纸上 4–5 种专色;每层油墨有颗粒、浓淡不匀和套色错位;透明叠印(重叠处出新颜色);半调网点;歪扭的手绘墨线;大块简洁造型和几何人物 |
-
-对 Claude 说「claude绘图」「你自己画」「用代码画」,它会:
-1. **先定构图**:层次、焦点、留白、一处点睛色,而且画面要图解内容本身,不是随便一幅风景;
+| **水墨** | `lib/inkpaint.py` · `Painting` | 宣纸纹理;会遮挡身后的墨染山体,带水痕边和雾;分笔毛的毛笔与飞白;皴擦、苔点;松、孤舟、芦苇;题字与印章 |
+| **水彩** | `lib/watercolor.py` · `Watercolor` | 冷压水彩纸纹理;**透明罩染**,叠色像真颜料一样变深、混色;水痕边;颜料颗粒;水渍花;湿画晕开;倒影;提白 |
+| **剪纸拼贴** | `lib/papercut.py` · `Collage` | 撕纸露出的白色纤维边;纸片层叠的阴影;牛皮纸、蜡笔、报纸、笔记本横线纸;蜡笔线条;可爱圆脸 |
+| **韩国彩铅** | `lib/colorpencil.py` · `ColorPencil` | 细密的短排线;蜡挂在纸纹凸起上,用力越大越能压进凹处;柔和叠色;浅褐色铅笔勾线;白色高光笔 |
+| **日本动漫** | `lib/anime.py` · `Anime` | 天空渐变;每个鼓包都带**月牙形**硬边暗面的积雨云;泛光、光束、镜头光斑;平涂田野、透视公路、电线;线稿角色 |
+| **编辑风手绘** | `lib/editorial.py` · `Editorial` | 4–5 种专色,每层带颗粒、浓淡不匀和套色错位;叠印出新颜色;半调网点;歪扭的手绘墨线;几何人物 |
+| **油画厚涂** | `lib/oilpaint.py` · `OilPainting` | 几万道笔触顺着**流向图**排列;每个像素都知道自己在笔触里的位置,算出平顶鼓边的颜料、笔毛沟、落笔处更厚的颜料,再打光出凸起 |
+| **浮世绘木版画** | `lib/ukiyoe.py` · `Ukiyoe` | 每种颜色一块版,印在和纸上,带木纹和套印偏移;天空和海面用**晕色(bokashi)**;墨色主版勾线;青海波纹;横向云带;标题签和朱印 |
+| **像素风** | `lib/pixelart.py` · `PixelArt` | 在 320×180 的小画布上逐像素作画;有限调色板;渐变、光晕、倒影都用 Bayer 抖动;3×5 像素字体;无插值放大 6 倍 |
+
+对 Claude 说「claude绘图」「你自己画」「用代码画」,也可以指定画风。它会:
+1. **先定构图**:层次、焦点、留白,而且画面要图解内容本身;
2. **写一段场景脚本**,调用绘图库;
3. **渲染并自己看图**,对照该画风的毛病清单修改,一般改 2–4 轮。
@@ -146,31 +159,35 @@ pip install -r ~/.claude/skills/claude-drawing/requirements.txt # numpy、Pill
### 快速上手
-水墨、水彩、剪纸的最小示例见上方英文部分的代码。全部范例:
+水墨、水彩、剪纸的最小示例见上方英文部分的代码。每种画风都有完整范例:
```bash
-python3 examples/bawansiqian.py out.png --stages stages/ # 水墨:八万四千法门
-python3 examples/moon_river.py out.png # 水墨:月印万川
-python3 examples/watercolor_autumn.py out.png # 水彩:秋日湖畔
-python3 examples/papercut_balloons.py out.png # 剪纸:热气球小镇
-python3 examples/colorpencil_dessert.py out.png # 韩国彩铅:午后甜点
-python3 examples/anime_summer.py out.png # 日本动漫:夏空
-python3 examples/editorial_ideas.py out.png # 编辑风:灵感生长
+python3 examples/bawansiqian.py out.png --stages stages/ # 水墨:八万四千法门
+python3 examples/watercolor_autumn.py out.png # 水彩:秋日湖畔
+python3 examples/papercut_balloons.py out.png # 剪纸:热气球小镇
+python3 examples/colorpencil_dessert.py out.png # 韩国彩铅:午后甜点
+python3 examples/anime_summer.py out.png # 日本动漫:夏空
+python3 examples/editorial_ideas.py out.png # 编辑风:灵感生长
+python3 examples/oil_wheatfield.py out.png # 油画厚涂:麦田星空
+python3 examples/ukiyoe_fuji.py out.png # 浮世绘:富士曙
+python3 examples/pixel_rainy_cafe.py out.png # 像素风:雨夜咖啡店
```
### 作画要点(Claude 交图前逐条自查)
-- **水墨**:先远后近,每层墨染遮挡身后;落笔间距跟笔毛挂钩,笔画不会一节一节;小路要少、平滑、从雾里伸出来;皴擦长而顺坡、集中在阴面;山脊线要淡而断续。
-- **水彩**:纸纹要细;阴影用湿画偏一侧积色,不要画成靶心;先画叶梗,并且只画在叶子外面;同一处罩染不超过三层,亮部留白或提白。
-- **剪纸**:大色块用平纸或牛皮纸,蜡笔只做点缀;撕口白边宽 5–8 像素,只出现在部分边缘;阴影偏移要补零,不能首尾相接;月亮用光圈,不画放射线。
-- **彩铅**:排线要够密,颜色才能叠到饱和,用力大小决定能压进多少纸纹;奶油、白瓷这类白色物体用暖奶白色配淡紫灰或淡蓝灰阴影,不要白画在白纸上。
-- **动漫**:云要用许多不规则团块,每团带月牙形的硬边暗面(团块减去朝太阳偏移的自身),不要画成光滑正圆加直线明暗交界;人物比例要对,裙摆在膝盖附近。
-- **编辑风**:专色 4–5 种,并刻意让它们重叠,靠叠印得到更多颜色;每层油墨都要有颗粒、浓淡不匀和几像素的套色错位,否则就像电脑剪贴画。
+- **水墨**:先远后近,每层墨染遮挡身后;落笔间距跟笔毛挂钩,笔画不会一节一节;小路要少、平滑、从雾里伸出来;皴擦长而顺坡、集中在阴面。
+- **水彩**:纸纹要细;阴影用湿画偏一侧积色,不要画成靶心;深色罩染只积在树冠内;同一处罩染不超过三层。
+- **剪纸**:大色块用平纸或牛皮纸,蜡笔只做点缀;撕口白边宽 5–8 像素,只出现在部分边缘;阴影偏移要补零。
+- **彩铅**:排线要够密,颜色才能叠到饱和,用力大小决定能压进多少纸纹;白色物体用暖奶白色配淡紫灰或淡蓝灰阴影。
+- **动漫**:云要用许多不规则团块,每团带月牙形的硬边暗面;人物比例要对。
+- **编辑风**:专色 4–5 种,刻意让它们重叠;每层油墨都要有颗粒、浓淡不匀和几像素的套色错位。
+- **油画**:先大笔铺底,再中笔,细节笔只用在要紧处;颜料凸起要克制(平顶、弱高光),否则笔触像塑料管。
+- **浮世绘**:平涂色块,晕色只用在天空和海面;云带不透明;墨线勾住一切;标题签和印章放在天空留白处。
+- **像素风**:在真正的低分辨率上画,用抖动代替渐变;光晕要小(大面积抖动会变成方块);放大只能用无插值。
### 计划
- 按笔画分层导出,方便在 Motion Canvas / Remotion 里做逐笔动画。
-- 在同一套底层上扩展更多画风:水粉、木刻版画、铅笔素描。
---
diff --git a/SKILL.md b/SKILL.md
index 9319218..8ca27d8 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,6 +1,6 @@
---
name: claude绘图
-description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置六种画风:中国水墨(宣纸、远山与雾、飞白、皴擦、题字印章)、水彩(透明罩染、水痕边、颗粒、水渍花、倒影)、剪纸拼贴(撕纸白边、纸片阴影、报纸/笔记本纸、蜡笔、可爱小人)、韩国彩铅(细密排线、纸纹颗粒、柔和叠色、白色高光笔)、日本动漫(赛璐璐积雨云、蓝天、光晕光斑、线稿角色)、编辑风手绘(Riso 套色叠印、颗粒与错位、半调网点、手绘墨线、几何人物)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名水墨/水彩/剪纸/彩铅/动漫/编辑插画,或 "draw it yourself", "paint with code", "procedural painting", "watercolor / paper collage / colored pencil / anime / editorial illustration without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。
+description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置九种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风,或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。
---
# Claude 绘图
@@ -14,12 +14,15 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型
| 画风 | 库 | 范例 | 耗时 |
|---|---|---|---|
-| 水墨 | `lib/inkpaint.py` · `Painting` | `examples/bawansiqian.py` 八万四千法门、`examples/moon_river.py` 月印万川 | 2–4 秒 |
+| 水墨 | `lib/inkpaint.py` · `Painting` | `examples/bawansiqian.py` 八万四千法门 | 约 4 秒 |
| 水彩 | `lib/watercolor.py` · `Watercolor` | `examples/watercolor_autumn.py` 秋日湖畔(秋树罩染、湖面倒影、红色小舟) | 约 15 秒 |
| 剪纸拼贴 | `lib/papercut.py` · `Collage` | `examples/papercut_balloons.py` 热气球小镇(条纹热气球、笑脸太阳、纸云、小房子) | 约 30 秒 |
| 韩国彩铅 | `lib/colorpencil.py` · `ColorPencil` | `examples/colorpencil_dessert.py` 午后甜点(草莓蛋糕、红茶、草莓) | 约 17 秒 |
| 日本动漫 | `lib/anime.py` · `Anime` | `examples/anime_summer.py` 夏空(积雨云、乡间公路、电线杆、草帽女孩背影) | 约 30 秒 |
| 编辑风手绘 | `lib/editorial.py` · `Editorial` | `examples/editorial_ideas.py` 灵感生长(浇水长出灯泡的概念插画) | 约 11 秒 |
+| 油画厚涂 | `lib/oilpaint.py` · `OilPainting` | `examples/oil_wheatfield.py` 麦田星空(旋转的星空、麦田、柏树、乌鸦) | 约 2 秒 |
+| 浮世绘木版画 | `lib/ukiyoe.py` · `Ukiyoe` | `examples/ukiyoe_fuji.py` 富士曙(晕色天空、富士、云带、青海波、帆船、崖松) | 约 7 秒 |
+| 像素风 | `lib/pixelart.py` · `PixelArt` | `examples/pixel_rainy_cafe.py` 雨夜咖啡店(霓虹、路灯、雨、倒影、猫) | 约 0.1 秒 |
各画风共用 `lib/core.py` 里的底层工具:噪声、模糊、样条曲线、多边形遮罩、有机轮廓 `blob_pts`、毛笔 `bristle_stroke`、中文字体查找。
@@ -29,7 +32,12 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型
- 童趣、温暖、讲故事 → 剪纸拼贴;
- 甜点、小物、日常可爱 → 韩国彩铅;
- 青春、夏日、天空、背景美术 → 日本动漫;
-- 观点、概念、商业文章配图 → 编辑风手绘。
+- 观点、概念、商业文章配图 → 编辑风手绘;
+- 浓烈、有笔触质感、名画感 → 油画厚涂;
+- 日式古典、海浪、富士、东方装饰感 → 浮世绘;
+- 复古游戏、夜景霓虹、小尺寸动画 → 像素风。
+
+每种画风只保留一幅范例,作为质量基准。
## 一、流程(每幅画都照做)
@@ -103,6 +111,27 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
- `line(pts, 墨色, width, wobble, breaks)`:歪扭的手绘墨线;`dashes()` 虚线;`stars()` 小十字星
- 专色控制在 4–5 种,并刻意让它们互相重叠,叠出第三种颜色
+**油画厚涂 `OilPainting`**:
+- 先准备两张图:参考色 `ref`(H×W×3,画面要画成什么颜色)和流向图 `ang`(H×W,每个像素上笔触的角度,比如天空打旋、麦田横扫、树木向上)
+- `layer(ref, ang, length, width, density, mask)`:铺一层笔触。先大笔铺底,再中笔,最后只在要紧处(`mask`)加细节笔
+- `stroke_at(x, y, angle, length, width, 颜色)`:在指定位置画一笔(乌鸦、签名、点睛)
+- `render()` 自动打光:颜料平顶鼓边、有笔毛沟,落笔处更厚
+
+**浮世绘 `Ukiyoe`**:
+- `block(mask, 颜色)`:印一块平涂色版,带木纹和套印偏移
+- `bokashi(mask, 颜色, y_strong, y_fade)`:晕色,从某一边浓到另一边消失,用于天空和海面
+- `key(pts, width)`:墨色主版勾线
+- 物件:`cloud_band(x0, x1, y, h, glow)` 不透明云带、`seigaiha(mask, 颜色, r)` 青海波纹
+- 标题签和朱印:`cartouche(x, y, w, h, '标题')`、`seal()`
+- 形状:`poly()`、`rect()`、`circle()`
+
+**像素风 `PixelArt`**:
+- 在低分辨率上画(默认 320×180,放大 6 倍)。坐标都是整数像素
+- 画形状:`rect()`、`poly()`、`circle()`、`line()`(Bresenham 直线)、`outline(mask)`、`put(x, y)`
+- 抖动:`gradient(x0, y0, x1, y1, c0, c1, steps)` 分带渐变,带与带之间用抖动过渡;`dither(mask, 颜色, alpha)` 按 Bayer 矩阵抖动上色;`glow(cx, cy, r, 颜色)` 抖动光晕
+- 其他:`text('CAFE', x, y, 颜色, size)` 3×5 像素字、`rain()` 雨丝
+- 交付用 PNG(无损),像素才清晰
+
**顺序**:都是先远后近、先大后小,文字最后叠加。水墨的雾要画在它该吞没的东西之后;水彩的叶梗要先画,并且只画在叶子外面。
## 三、毛病清单(都真实出现过)
@@ -164,6 +193,27 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
| 色块死板,像电脑矢量图 | 每层专色都要有颗粒、浓淡不匀和几像素的套色错位 |
| 颜色太多太杂 | 4–5 种专色,靠叠印得到其他颜色(比如青叠黄出绿) |
+**油画厚涂**
+
+| 问题 | 改法 |
+|---|---|
+| 笔触像一根根塑料管、橡皮泥 | 凸起要克制:平顶鼓边的截面,高光约 0.1,打光范围约 0.8–1.18 |
+| 笔触之间大量露底 | 铺底笔加密(density 约 2),宽笔铺满后再上细笔 |
+
+**浮世绘**
+
+| 问题 | 改法 |
+|---|---|
+| 云带半透明,透出后面的轮廓线 | 云带用不透明的色版(strength 超过 1,确保完全盖住) |
+| 标题签和云带、主体撞在一起 | 标题签放在天空的空白处,其他元素给它让位 |
+
+**像素风**
+
+| 问题 | 改法 |
+|---|---|
+| 背景底部露出一条黑带 | 天空渐变和楼群都要铺到地面线,不留缝 |
+| 光晕变成一大块方形点阵 | 光晕半径要小(约 20 像素)、强度约 0.4–0.5;霓虹光晕压扁一些 |
+
## 四、做成动画
- 各画风都有 `stage(name)` 和 `save(path, stages_dir)`,按阶段依次淡入叠化,就是「一幅画被逐步画出来」。README 里的动图就是这样做的。
@@ -179,6 +229,9 @@ lib/papercut.py 剪纸拼贴
lib/colorpencil.py 韩国彩铅
lib/anime.py 日本动漫
lib/editorial.py 编辑风手绘
+lib/oilpaint.py 油画厚涂
+lib/ukiyoe.py 浮世绘木版画
+lib/pixelart.py 像素风
examples/*.py 范例脚本;*.jpg 成品;drawing_*.gif 逐步画出的动图
中文字体:自动找 Kaiti/Songti(macOS)、Noto CJK(Linux)、KaiTi/SimSun(Windows),或设 INKPAINT_FONT
```
diff --git a/examples/drawing_moon_river.gif b/examples/drawing_moon_river.gif
deleted file mode 100644
index 473b4ac..0000000
Binary files a/examples/drawing_moon_river.gif and /dev/null differ
diff --git a/examples/drawing_oil_wheatfield.gif b/examples/drawing_oil_wheatfield.gif
new file mode 100644
index 0000000..ef51030
Binary files /dev/null and b/examples/drawing_oil_wheatfield.gif differ
diff --git a/examples/drawing_pixel_rainy_cafe.gif b/examples/drawing_pixel_rainy_cafe.gif
new file mode 100644
index 0000000..6c81f80
Binary files /dev/null and b/examples/drawing_pixel_rainy_cafe.gif differ
diff --git a/examples/drawing_ukiyoe_fuji.gif b/examples/drawing_ukiyoe_fuji.gif
new file mode 100644
index 0000000..4102388
Binary files /dev/null and b/examples/drawing_ukiyoe_fuji.gif differ
diff --git a/examples/moon_river.jpg b/examples/moon_river.jpg
deleted file mode 100644
index 659d473..0000000
Binary files a/examples/moon_river.jpg and /dev/null differ
diff --git a/examples/moon_river.py b/examples/moon_river.py
deleted file mode 100644
index f545b35..0000000
--- a/examples/moon_river.py
+++ /dev/null
@@ -1,94 +0,0 @@
-"""范例:「月印万川」— 烘云托月、孤舟、芦苇。纯代码水墨。
-python3 moon_river.py [out.png] [--stages DIR]
-"""
-import os, sys
-sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
-import numpy as np
-from inkpaint import Painting, spline, curve, blur
-
-out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'moon_river.png'
-stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
-
-p = Painting(1920, 1080, seed=2026)
-p.paper()
-p.stage('宣纸')
-YY, XX, rng = p.YY, p.XX, p.rng
-
-# ---- night sky wash that leaves the moon as bare paper (烘云托月)
-MX, MY, MR = 1360, 250, 74
-horizon = 610
-dist = np.hypot(XX - MX, YY - MY)
-sky = 0.30 * np.clip(1 - YY / horizon, 0, 1) ** 0.8 * (0.6 + 0.4 * p.noise2d(220, 4, 3))
-sky *= np.clip((horizon - YY) / 140, 0, 1) ** 0.7 # fades out toward the water line
-moon = np.clip((MR - dist) / 3, 0, 1)
-halo = np.exp(-((dist - MR) / 60) ** 2) * (dist > MR)
-sky = sky * (1 - moon) * (1 - 0.55 * np.exp(-(np.clip(dist - MR, 0, None) / 90))) # lighter glow near the moon
-sky += 0.06 * halo * (0.6 + 0.4 * p.noise2d(40, 3, 4))
-p.over(p.D, sky)
-p.stage('夜空')
-
-# ---- distant hills, very pale, sitting on the water line
-# hills are bumps rising from below the water line, so the open water under the moon stays clean
-far = p.ridge(horizon + 60, peaks=[(260, 150, 260), (640, 110, 200), (1760, 120, 230)], rough=12, rough_scale=200, seed=21)
-p.wash(far, dens=0.2, decay=45, tex=90, edge=0.35, seed=22)
-np.multiply(p.D, 1 - np.clip((YY - horizon) / 5, 0, 1), out=p.D) # everything stops at the water line
-p.stage('远山')
-
-# ---- water: moon reflection (broken pale strokes) and sparse ripples
-for i in range(14):
- y = horizon + 30 + i * 22 + rng.normal(0, 3)
- half = 70 * (1 - i / 16) + rng.uniform(-10, 10)
- x0 = MX - half + rng.normal(0, 12)
- p.stroke(spline([(x0, y), (MX + rng.normal(0, 10), y + rng.normal(0, 1.5)), (MX + half, y)], 10), 1.6, 0.16, dry=0.55, taper=(0.3, 0.3))
-for _ in range(40):
- x = rng.uniform(80, 1840); y = rng.uniform(horizon + 40, 1000)
- if abs(x - MX) < 150: continue
- ln = rng.uniform(40, 140) * (0.6 + (y - horizon) / 500)
- p.stroke(spline([(x, y), (x + ln / 2, y + rng.normal(0, 1.2)), (x + ln, y)], 8), 1.3, 0.13 + 0.1 * (y - horizon) / 470, dry=0.6, taper=(0.3, 0.3))
-p.stage('江面')
-
-# ---- lone boat with a fisherman
-BX, BY = 760, 742
-hull = spline([(BX - 120, BY - 8), (BX - 60, BY + 12), (BX + 40, BY + 14), (BX + 118, BY - 14)], 12)
-p.stroke(hull, 7, 0.85, dry=0.25, taper=(0.1, 0.2))
-p.stroke(spline([(BX - 108, BY - 4), (BX, BY + 6), (BX + 104, BY - 10)], 10), 2.2, 0.5, dry=0.4)
-cover = spline([(BX + 10, BY - 4), (BX + 38, BY - 38), (BX + 78, BY - 36), (BX + 96, BY - 8)], 10) # woven canopy
-p.stroke(cover, 4, 0.7, dry=0.35)
-for k in range(5):
- x = BX + 22 + k * 15
- p.stroke([(x, BY - 34 + abs(k - 2) * 2), (x + 2, BY - 6)], 1.2, 0.45, dry=0.4)
-FX, FY = BX - 58, BY - 10 # the fisherman
-p.stroke(spline([(FX - 10, FY), (FX - 4, FY - 22), (FX + 4, FY - 32)], 8), 6, 0.8, dry=0.2, taper=(0.1, 0.3))
-p.stroke(spline([(FX - 18, FY - 34), (FX + 3, FY - 50), (FX + 22, FY - 33)], 8), 3, 0.85, dry=0.15, taper=(0.1, 0.1)) # straw hat
-p.stroke(spline([(FX + 2, FY - 22), (FX - 80, FY - 120), (FX - 210, FY - 170)], 14), 1.4, 0.7, dry=0.2, taper=(0.05, 0.6)) # rod
-p.stroke(spline([(FX - 210, FY - 170), (FX - 214, FY - 60), (FX - 212, FY + 30)], 12), 0.8, 0.35, dry=0.3, taper=(0.05, 0.05)) # line
-for r_ in (10, 20):
- p.stroke(spline([(FX - 212 - r_ * 2, FY + 34), (FX - 212, FY + 34 + r_ * 0.25), (FX - 212 + r_ * 2, FY + 34)], 8), 1.1, 0.25, dry=0.5)
-p.stroke(spline([(BX - 150, BY + 22), (BX, BY + 30), (BX + 150, BY + 20)], 10), 1.4, 0.18, dry=0.6) # boat's shadow ripple
-p.stage('孤舟')
-
-# ---- reeds in the lower-right foreground
-for i in range(22):
- back = i < 8 # paler reeds behind for depth
- x0 = rng.uniform(1500, 1900); y0 = 1085
- h = rng.uniform(220, 420)
- lean = rng.uniform(-70, 40)
- top = (x0 + lean, y0 - h)
- stem = spline([(x0, y0), (x0 + lean * 0.35 + rng.normal(0, 6), y0 - h * 0.5), top], 12)
- p.stroke(stem, rng.uniform(1.4, 2.4), rng.uniform(0.18, 0.3) if back else rng.uniform(0.45, 0.72), dry=0.4, taper=(0.02, 0.7))
- for _ in range(int(rng.integers(1, 3))): # blade leaves
- k = int(rng.integers(8, 20)); q = stem[k]
- side = rng.choice([-1, 1]); ln = rng.uniform(60, 130)
- p.stroke(spline([tuple(q), (q[0] + side * ln * 0.5, q[1] - ln * 0.35), (q[0] + side * ln, q[1] - ln * 0.1)], 8),
- rng.uniform(3, 5), rng.uniform(0.15, 0.25) if back else rng.uniform(0.4, 0.65), dry=0.45, taper=(0.05, 0.9))
- if rng.random() < 0.55: # plume
- for _ in range(7):
- p.stroke([top, (top[0] + rng.normal(-14, 8), top[1] + rng.uniform(18, 34))], 1.1, 0.35, dry=0.5, taper=(0.1, 0.8))
-p.mist(1000, 60, 0.45)
-p.stage('芦苇')
-
-p.birds([(560, 330, 0.8), (600, 348, 0.6)])
-p.title_vertical('月印万川', 150, 150, 92)
-p.seal('禅心', 262, 176, 40)
-p.save(out, stages_dir=stages)
-print('saved', out)
diff --git a/examples/oil_wheatfield.jpg b/examples/oil_wheatfield.jpg
new file mode 100644
index 0000000..55d17a2
Binary files /dev/null and b/examples/oil_wheatfield.jpg differ
diff --git a/examples/oil_wheatfield.py b/examples/oil_wheatfield.py
new file mode 100644
index 0000000..2c85ce3
--- /dev/null
+++ b/examples/oil_wheatfield.py
@@ -0,0 +1,94 @@
+"""Example (impasto oil): Swirling Sky over the Wheat Field / 麦田星空 — thousands of directional
+strokes following a flow field (swirling sky, sweeping wheat, flame-like cypress), with lit paint relief.
+Pure code, no image model.
+python3 oil_wheatfield.py [out.png] [--stages DIR]
+"""
+import os, sys
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from oilpaint import OilPainting, hexc
+from core import smoothstep, noise2d, polygon_mask, spline
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'oil_wheatfield.png'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+
+o = OilPainting(1920, 1080, seed=1889)
+W, H = o.W, o.H
+X, Y = o.XX, o.YY
+HOR = 600
+n1 = noise2d(H, W, 120, 3, 1); n2 = noise2d(H, W, 40, 3, 2)
+
+# ---------------------------------------------------------------- reference colours + flow field
+sky = Y < HOR
+ref = np.zeros((H, W, 3), np.float32)
+ang = np.zeros((H, W), np.float32)
+
+# sky: deep blue with swirling lighter bands around two vortices, a blazing moon
+t = np.clip(Y / HOR, 0, 1)[..., None]
+ref[:] = hexc('#1c3a8a') * (1 - t) + hexc('#3f71c4') * t
+ang[:] = 0.25 * np.sin(X / 210 + Y / 95) + 0.15 * (n1 - 0.5)
+for (vx, vy, R, turns) in [(720, 270, 260, 1), (1230, 360, 190, -1)]:
+ dxv, dyv = X - vx, Y - vy
+ r = np.hypot(dxv, dyv) + 1e-3
+ wgt = np.exp(-(r / (R * 1.4)) ** 2)
+ tang = np.arctan2(dyv, dxv) + turns * np.pi / 2
+ ang = np.arctan2(np.sin(ang) * (1 - wgt) + np.sin(tang) * wgt, np.cos(ang) * (1 - wgt) + np.cos(tang) * wgt)
+ band = (0.5 + 0.5 * np.sin(r / 22 + np.arctan2(dyv, dxv) * 2 * turns)) * np.exp(-(r / R) ** 2)
+ ref = ref * (1 - 0.8 * band[..., None]) + (hexc('#9cc0ea') * (1 - n2[..., None]) + hexc('#e8eef2') * n2[..., None]) * 0.8 * band[..., None]
+MX, MY = 1560, 170
+rm = np.hypot(X - MX, Y - MY)
+halo = (0.5 + 0.5 * np.cos(rm / 14)) * np.exp(-(rm / 190) ** 2) * (rm > 62)
+ref = ref * (1 - 0.85 * halo[..., None]) + hexc('#f3e27a') * 0.85 * halo[..., None]
+moon = rm < 62
+ref[moon] = hexc('#f7d23e') * (1 - 0.25 * (rm[moon] / 62))[..., None] + hexc('#fff6c8') * 0.25 * (1 - rm[moon] / 62)[..., None]
+tang_m = np.arctan2(Y - MY, X - MX) + np.pi / 2
+wm = np.exp(-(rm / 230) ** 2)
+ang = np.where(rm < 240, np.arctan2(np.sin(ang) * (1 - wm) + np.sin(tang_m) * wm, np.cos(ang) * (1 - wm) + np.cos(tang_m) * wm), ang)
+for (sx, sy, sr) in [(300, 120, 26), (1010, 90, 22), (1760, 420, 20), (420, 430, 18), (1330, 120, 16)]: # smaller stars
+ rs = np.hypot(X - sx, Y - sy)
+ st = np.exp(-(rs / sr) ** 2)
+ ref = ref * (1 - st[..., None]) + hexc('#f6ea9a') * st[..., None]
+
+# distant blue-violet hills on the horizon
+hill_y = HOR - 30 - 35 * np.sin(X / 260 + 1.2) - 18 * np.sin(X / 90)
+hills = (Y > hill_y) & (Y < HOR + 30)
+ref[hills] = (hexc('#4a4f8c') * 0.6 + hexc('#6d5f9e') * 0.4)
+ang[hills] = 0.05 * np.sin(X[hills] / 80)
+
+# wheat field: gold with orange and green streaks, strokes sweeping in waves
+field = Y >= HOR + 10
+f_t = np.clip((Y - HOR) / (H - HOR), 0, 1)
+gold = hexc('#e4b93e') * (1 - n1[..., None]) + hexc('#cf8f2a') * n1[..., None]
+gold = gold * (1 - 0.35 * (n2[..., None] > 0.7)) + hexc('#7e8f3a') * 0.35 * (n2[..., None] > 0.7)
+ref[field] = gold[field] * (0.85 + 0.25 * f_t[field])[..., None]
+ang[field] = (-0.35 - 0.55 * np.sin(X[field] / 170 + Y[field] / 60)) * (0.5 + f_t[field])
+# a winding dirt path to the horizon
+path_x = 980 + 260 * (1 - f_t) ** 0 * np.sin(f_t * 3.2) * f_t + 30 * np.sin(Y / 70) * f_t
+path_w = 12 + 190 * f_t ** 1.4
+path = field & (np.abs(X - path_x) < path_w)
+ref[path] = hexc('#d7b98a') * (0.9 + 0.2 * n2[path])[..., None]
+ang[path] = np.arctan2(1.0, 0.25 * np.cos(f_t[path] * 3.2)) # strokes run along the path
+
+# a flame-like cypress on the left
+cyp_center = 330 + 30 * np.sin(Y / 55)
+half = np.clip((Y - 150) / 930, 0, 1) ** 0.7 * 150 * (1 + 0.25 * np.sin(Y / 23))
+cyp = (np.abs(X - cyp_center) < half) & (Y > 150)
+ref[cyp] = hexc('#1d4b33') * (1 - n2[cyp])[..., None] + hexc('#3a7a45') * n2[cyp][..., None]
+ref[cyp & (X > cyp_center + half * 0.2)] = ref[cyp & (X > cyp_center + half * 0.2)] * 0.8 + hexc('#6f9a4a') * 0.2
+ang[cyp] = -np.pi / 2 + 0.45 * np.sin(Y[cyp] / 28 + X[cyp] / 40)
+
+# ---------------------------------------------------------------- paint: big -> small strokes
+o.layer(ref, ang, length=(60, 110), width=(22, 32), density=2.2, value_jitter=0.05)
+o.stage('underpainting')
+o.layer(ref, ang, length=(34, 64), width=(11, 17), density=1.9, value_jitter=0.07)
+o.stage('strokes')
+detail = ((rm < 260) | (np.hypot(X - 720, Y - 270) < 300) | (np.hypot(X - 1230, Y - 360) < 220) | cyp).astype(np.float32)
+o.layer(ref, ang, length=(18, 36), width=(6, 10), density=1.6, value_jitter=0.08, mask=detail)
+o.stage('detail')
+# crows over the field: two short dark strokes each
+for (bx, by, sc) in [(1150, 690, 1.0), (1290, 655, 0.8), (1060, 745, 0.75), (1410, 720, 0.9), (1225, 790, 0.65)]:
+ o.stroke_at(bx - 17 * sc, by, -0.45, 38 * sc, 9 * sc, '#1b1b24', 1.3)
+ o.stroke_at(bx + 17 * sc, by, 0.45, 38 * sc, 9 * sc, '#1b1b24', 1.3)
+
+o.save(out, stages_dir=stages)
+print('saved', out)
diff --git a/examples/pixel_rainy_cafe.png b/examples/pixel_rainy_cafe.png
new file mode 100644
index 0000000..74b59d2
Binary files /dev/null and b/examples/pixel_rainy_cafe.png differ
diff --git a/examples/pixel_rainy_cafe.py b/examples/pixel_rainy_cafe.py
new file mode 100644
index 0000000..f7d7858
--- /dev/null
+++ b/examples/pixel_rainy_cafe.py
@@ -0,0 +1,99 @@
+"""Example (pixel art): Rainy Night Cafe / 雨夜咖啡店 — a 320x180 scene painted pixel by pixel with a
+limited palette, dithered sky and glows, neon sign in a 3x5 bitmap font, wet-street reflections,
+rain, a passer-by with an umbrella and a cat; upscaled x6 with nearest-neighbour. No image model.
+python3 pixel_rainy_cafe.py [out.png] [--stages DIR]
+"""
+import os, sys
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from pixelart import PixelArt
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'pixel_rainy_cafe.png'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+
+p = PixelArt(320, 180, scale=6, seed=2084)
+rng = p.rng
+W, H = p.w, p.h
+
+# ---- sky and skyline
+p.gradient(0, 0, W, 138, '#0d1030', '#2c2a5c', steps=6)
+x = 0
+while x < W: # far skyline with lit windows
+ bw = int(rng.integers(14, 30)); bh = int(rng.integers(30, 75))
+ p.rect(x, 118 - bh, x + bw, 138, '#1a1d40')
+ for wy in range(118 - bh + 4, 134, 5):
+ for wx in range(x + 3, x + bw - 3, 4):
+ if rng.random() < 0.28:
+ p.rect(wx, wy, wx + 2, wy + 2, '#f2c14e' if rng.random() < 0.8 else '#6fd3e8')
+ x += bw + int(rng.integers(0, 3))
+p.rect(170, 40, 230, 138, '#23264c') # a closer building behind the lamp
+for wy in range(48, 130, 9):
+ for wx in (178, 192, 206, 218):
+ p.rect(wx, wy, wx + 6, wy + 5, '#f2b24a' if rng.random() < 0.35 else '#171a38')
+p.stage('skyline')
+
+# ---- the cafe: brick facade, upper windows, striped awning, glowing shop window, door, neon sign
+p.rect(30, 58, 162, 138, '#6e3a3a')
+for yy in range(60, 138, 4): # brick courses
+ p.rect(30, yy, 162, yy + 1, '#552c2c')
+ off = 0 if (yy // 4) % 2 == 0 else 4
+ for xx in range(30 + off, 162, 8):
+ p.rect(xx, yy, xx + 1, yy + 4, '#552c2c')
+p.rect(28, 56, 164, 60, '#3a1f25') # cornice
+for (wx, lit) in [(44, False), (78, True), (112, False), (140, False)]:
+ p.rect(wx - 1, 63, wx + 15, 79, '#2a1a1e')
+ p.rect(wx, 64, wx + 14, 78, '#ffd27a' if lit else '#1b2244')
+ p.rect(wx + 6, 64, wx + 8, 78, '#2a1a1e'); p.rect(wx, 70, wx + 14, 72, '#2a1a1e')
+for k, xx in enumerate(range(34, 158, 6)): # awning stripes with a scalloped edge
+ p.rect(xx, 90, xx + 6, 99, '#d64b4b' if k % 2 == 0 else '#f1e3c6')
+ p.rect(xx + 1, 99, xx + 5, 101, '#d64b4b' if k % 2 == 0 else '#f1e3c6')
+p.rect(34, 89, 158, 90, '#8a2a2a')
+p.rect(42, 103, 112, 136, '#2a1a1e') # shop window frame
+p.gradient(44, 105, 110, 134, '#ffdc8a', '#e79a45', steps=4)
+p.rect(44, 118, 110, 119, '#9a5a2a'); p.rect(44, 127, 110, 128, '#9a5a2a') # shelves
+for sx in range(48, 106, 7):
+ p.rect(sx, 113 + (sx % 3), sx + 3, 118, '#b0662e') # jars and cups
+ p.rect(sx + 1, 123, sx + 4, 127, '#8e4f28')
+p.rect(58, 105, 59, 110, '#5a3a22'); p.rect(55, 110, 62, 112, '#fff1b8') # hanging lamp
+p.rect(116, 103, 142, 138, '#2a1a1e'); p.rect(118, 105, 140, 138, '#6b4326') # door
+p.rect(122, 108, 136, 118, '#ffd27a'); p.put(137, 122, '#e8c35a')
+p.glow(96, 83, 22, '#ff5fa2', 0.42, squash=0.45) # neon glow, then the tube letters
+p.text('CAFE', 81, 78, '#ffd1e6', size=2)
+p.stage('cafe')
+
+# ---- street lamp with a pool of light
+p.rect(248, 62, 251, 146, '#2b2d3f'); p.rect(244, 58, 256, 62, '#2b2d3f'); p.rect(246, 62, 254, 65, '#ffe7a1')
+p.glow(250, 64, 20, '#ffe7a1', 0.5)
+p.glow(250, 146, 30, '#d9c27a', 0.45, squash=0.2)
+
+# ---- sidewalk and wet street with broken reflections
+p.rect(0, 138, W, 146, '#2a2c46'); p.rect(0, 146, W, 148, '#3c3f63')
+p.gradient(0, 148, W, H, '#161831', '#0c0d1f', steps=3)
+for (x0, x1, col, a0) in [(44, 110, '#e8a44f', 0.75), (78, 92, '#ffd27a', 0.45), (80, 112, '#ff5fa2', 0.35), (242, 258, '#ffe7a1', 0.8), (178, 226, '#f2b24a', 0.25)]:
+ m = np.zeros((H, W), bool); m[150:H, x0:x1] = True
+ ripple = ((p.YY % 3) != 0) # horizontal ripple gaps
+ fade = np.clip(1 - (p.YY - 150) / 34, 0, 1) * a0
+ p.dither(m & ripple, col, fade)
+p.stage('street')
+
+# ---- a passer-by with an umbrella, and a cat on the step
+UX, UY = 206, 118
+dome = ((p.XX - UX) ** 2 + (p.YY - (UY + 8)) ** 2 <= 121) & (p.YY <= UY + 8) # half-disc umbrella
+p.buf[dome] = np.array([62, 193, 201], np.float32) / 255
+p.outline(dome, '#2a8a91')
+for k in range(-10, 11, 5):
+ p.put(UX + k, UY + 8, '#2a8a91')
+p.rect(UX, UY + 8, UX + 1, UY + 16, '#1b1c2e') # handle
+p.rect(UX - 3, UY + 14, UX + 4, UY + 25, '#23243a'); p.rect(UX - 3, UY + 14, UX + 4, UY + 16, '#c9a07a')
+p.rect(UX - 2, UY + 25, UX, UY + 31, '#1b1c2e'); p.rect(UX + 2, UY + 25, UX + 4, UY + 30, '#1b1c2e')
+p.rect(126, 133, 134, 138, '#e08a3c'); p.rect(127, 130, 131, 134, '#e08a3c') # cat
+p.put(127, 129, '#e08a3c'); p.put(130, 129, '#e08a3c'); p.put(128, 131, '#1b1c2e'); p.put(130, 131, '#1b1c2e')
+p.rect(134, 132, 136, 134, '#e08a3c'); p.rect(135, 130, 136, 132, '#e08a3c')
+
+# ---- rain and ripples
+p.rain(260, '#8fa4c8', (4, 8), slant=1)
+for _ in range(14):
+ rx, ry = int(rng.integers(5, W - 5)), int(rng.integers(152, H - 3))
+ p.put(rx - 1, ry, '#5c6a93'); p.put(rx + 1, ry, '#5c6a93'); p.put(rx, ry - 1, '#5c6a93')
+p.save(out, stages_dir=stages)
+print('saved', out)
diff --git a/examples/ukiyoe_fuji.jpg b/examples/ukiyoe_fuji.jpg
new file mode 100644
index 0000000..5f2d63a
Binary files /dev/null and b/examples/ukiyoe_fuji.jpg differ
diff --git a/examples/ukiyoe_fuji.py b/examples/ukiyoe_fuji.py
new file mode 100644
index 0000000..093f106
--- /dev/null
+++ b/examples/ukiyoe_fuji.py
@@ -0,0 +1,90 @@
+"""Example (ukiyo-e woodblock print): Fuji at Dawn / 富士曙 — bokashi sky, snow-capped Fuji, stylised
+cloud bands, a seigaiha-patterned sea with sailboats, a pine on a cliff, title cartouche and seal.
+Pure code, no image model.
+python3 ukiyoe_fuji.py [out.png] [--stages DIR]
+"""
+import os, sys
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
+import numpy as np
+from ukiyoe import Ukiyoe
+from core import spline, curve
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'ukiyoe_fuji.png'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+
+u = Ukiyoe(1920, 1080, seed=1831)
+W, H = u.W, u.H
+HOR = 640
+
+# ---- sky: Prussian blue wiped down from the top, dawn red rising from the horizon
+sky = u.rect(0, 0, W, HOR + 2)
+u.bokashi(sky, '#27487f', 0, 340)
+u.bokashi(sky, '#e0723b', HOR, 420, strength=0.85)
+u.stage('sky')
+
+# ---- Mount Fuji: concave slopes, snow cap with long fingers, darker bokashi at the summit
+AX, AY = 1180, 190
+ts = np.linspace(0, 1, 40)
+left = [(AX - 20 - 450 * t ** 1.6, AY + (HOR - AY) * t) for t in ts]
+right = [(AX + 20 + 470 * t ** 1.6, AY + (HOR - AY) * t) for t in ts]
+fuji = left[::-1] + [(AX - 20, AY), (AX + 20, AY)] + right
+u.block(u.poly(fuji), '#4d6f8f')
+u.bokashi(u.poly(fuji), '#2d4a68', AY, 470)
+snow_y = lambda x: AY + 150 + 30 * np.sin(x / 13) * np.clip(1 - np.abs(x - AX) / 260, 0, 1) + 18 * np.sin(x / 5.3)
+snow = u.poly(fuji) * (u.YY < snow_y(u.XX))
+u.block(snow, '#f6f1e3')
+u.key(fuji[:40][::-1], 3.5); u.key(fuji[40:], 3.5)
+xs = np.linspace(AX - 230, AX + 240, 60)
+u.key([(x, snow_y(x)) for x in xs if abs(x - AX) < 20 + 450 * (((snow_y(x) - AY) / (HOR - AY)) ** 1.6) + 5], 2.2)
+# distant low islands on the horizon
+for (x0, x1, h) in [(0, 420, 26), (1560, 1920, 20)]:
+ isl = [(x0, HOR + 4)] + [(x, HOR - h * np.sin(np.pi * (x - x0) / (x1 - x0)) ** 0.6) for x in np.linspace(x0, x1, 30)] + [(x1, HOR + 4)]
+ u.block(u.poly(isl), '#56786a'); u.key(isl[1:-1], 2.2)
+# stylised mist bands crossing the mountain
+for (x0, x1, y, h) in [(560, 1480, 470, 44), (950, 1880, 548, 38), (60, 760, 170, 38), (1260, 1690, 300, 30)]:
+ u.cloud_band(x0, x1, y, h, glow='#f0a27a' if y > 400 else None)
+u.stage('fuji')
+
+# ---- the sea: deep blue bokashi from the foreground, seigaiha waves, sailboats
+sea = u.rect(0, HOR, W, H)
+u.block(sea, '#2c5d9c')
+u.bokashi(sea, '#15356a', H, 720)
+u.seigaiha(sea * (u.YY > 690), '#8db3de', r=30, width=2.2)
+for (bx, by, s) in [(820, 735, 1.0), (1040, 700, 0.7), (1480, 760, 1.2), (620, 690, 0.55)]:
+ hull = [(bx - 46 * s, by), (bx + 46 * s, by), (bx + 32 * s, by + 14 * s), (bx - 32 * s, by + 14 * s)]
+ sail = [(bx - 22 * s, by - 6 * s), (bx + 18 * s, by - 6 * s), (bx + 14 * s, by - 74 * s), (bx - 20 * s, by - 70 * s)]
+ u.block(u.poly(sail), '#f4ead2'); u.key(sail, 2.2, closed=True)
+ for k in range(1, 4):
+ u.key([(bx - 21 * s + k, by - 6 * s - 17 * k * s), (bx + 17 * s - k, by - 6 * s - 17 * k * s)], 1.4)
+ u.block(u.poly(hull), '#3a2a22'); u.key(hull, 2.2, closed=True)
+u.stage('sea')
+
+# ---- a pine leaning out from a cliff in the left foreground
+cliff = [(0, H), (0, 720), (120, 690), (250, 725), (360, 820), (430, 960), (410, H)]
+u.block(u.poly(cliff), '#80603e')
+u.bokashi(u.poly(cliff), '#4f3a26', H, 780)
+u.key(cliff[1:-1], 4)
+for (a, b) in [((60, 760), (140, 850)), ((200, 780), (260, 900)), ((110, 900), (230, 1000))]:
+ u.key(spline([a, ((a[0] + b[0]) / 2 + 12, (a[1] + b[1]) / 2), b], 8), 2.2) # rock cracks
+trunk = spline([(170, 715), (210, 620), (190, 540), (260, 470), (380, 430), (470, 380)], 14)
+u.key(trunk, 22, colour='#4a3121'); u.key(trunk, 3)
+for (a, b) in [((215, 600), (330, 560)), ((200, 545), (95, 470)), ((300, 455), (330, 360))]:
+ u.key(spline([a, ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2 - 10), b], 8), 9, colour='#4a3121')
+for (cx, cy, w) in [(480, 372, 170), (345, 552, 150), (95, 462, 130), (330, 352, 120), (590, 405, 110)]:
+ top = [(cx + w * np.cos(t) / 2, cy + (w * 0.32) * np.sin(t)) for t in np.linspace(np.pi, 2 * np.pi, 24)]
+ umb = top + [(cx + w / 2, cy + 8), (cx - w / 2, cy + 8)]
+ u.block(u.poly(umb), '#2d5b3d')
+ u.block(u.poly(umb) * (u.YY < cy - w * 0.12), '#5d8f4f')
+ u.key(umb, 2.6, closed=True)
+ for k in range(-3, 4):
+ u.key([(cx + k * w / 8, cy - 2), (cx + k * w / 7.2, cy - w * 0.22)], 1.4)
+u.stage('pine')
+
+# ---- birds, title cartouche and seal
+for (bx, by, s) in [(1480, 250, 1.0), (1530, 272, 0.8), (1440, 285, 0.7), (1575, 240, 0.6)]:
+ u.key(spline([(bx - 18 * s, by), (bx - 7 * s, by - 8 * s), (bx, by)], 6), 2.2)
+ u.key(spline([(bx, by), (bx + 7 * s, by - 8 * s), (bx + 18 * s, by)], 6), 2.2)
+u.cartouche(1740, 60, 100, 330, '富士曙')
+u.seal(1756, 420, 66, '春')
+u.save(out, stages_dir=stages)
+print('saved', out)
diff --git a/lib/core.py b/lib/core.py
index 744e833..33ddf94 100644
--- a/lib/core.py
+++ b/lib/core.py
@@ -65,7 +65,7 @@ def noise2d(h, w, scale, octaves=4, seed=0):
out = np.zeros((h, w), np.float32); amp = 1.0; tot = 0.0
for o in range(octaves):
gh, gw = max(2, int(h / scale * 2 ** o) + 2), max(2, int(w / scale * 2 ** o) + 2)
- g = Image.fromarray(r.random((gh, gw)).astype(np.float32), mode='F')
+ g = Image.fromarray(r.random((gh, gw)).astype(np.float32))
out += amp * np.asarray(g.resize((w, h), Image.BICUBIC), np.float32)
tot += amp; amp *= 0.5
out /= tot
diff --git a/lib/inkpaint.py b/lib/inkpaint.py
index 0a55615..3e523a1 100644
--- a/lib/inkpaint.py
+++ b/lib/inkpaint.py
@@ -47,7 +47,7 @@ class Painting:
out = np.zeros((self.H, self.W), np.float32); amp = 1.0; tot = 0.0
for o in range(octaves):
gh, gw = max(2, int(self.H / scale * 2 ** o) + 2), max(2, int(self.W / scale * 2 ** o) + 2)
- g = Image.fromarray(r.random((gh, gw)).astype(np.float32), mode='F')
+ g = Image.fromarray(r.random((gh, gw)).astype(np.float32))
out += amp * np.asarray(g.resize((self.W, self.H), Image.BICUBIC), np.float32)
tot += amp; amp *= 0.5
out /= tot
diff --git a/lib/oilpaint.py b/lib/oilpaint.py
new file mode 100644
index 0000000..3b1d5f3
--- /dev/null
+++ b/lib/oilpaint.py
@@ -0,0 +1,144 @@
+"""oilpaint — impasto oil painting with directional strokes and lit paint relief (numpy + Pillow only).
+
+Model (in the spirit of Van Gogh):
+ 1. you describe the scene as a *reference colour field* (numpy RGB) and a *flow field* (stroke angle per pixel);
+ 2. thousands of short strokes are laid in passes (big underpainting strokes, then smaller detail strokes),
+ each oriented by the flow field and coloured from the reference, with a little hue/value jitter;
+ 3. an ID map remembers which stroke is on top at every pixel, so each pixel knows where it sits inside
+ its stroke -> paint thickness (rounded ridge), bristle grooves along the stroke, thicker blobs at the start;
+ 4. the height map is lit (normals, raking light + small speculars) -> real impasto relief.
+
+ from oilpaint import OilPainting
+ o = OilPainting(1920, 1080, seed=1)
+ ref = ... # HxWx3 float colours
+ ang = ... # HxW stroke angles (radians)
+ o.layer(ref, ang, length=(40, 80), width=(14, 22)) # underpainting
+ o.layer(ref, ang, length=(18, 40), width=(7, 12)) # detail
+ o.save('out.png')
+"""
+import numpy as np
+from PIL import Image, ImageDraw
+from core import blur, noise2d, smoothstep
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+class OilPainting:
+ def __init__(self, W=1920, H=1080, seed=0):
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ self.ids = np.full((H, W), -1, np.int32)
+ self.cx = []; self.cy = []; self.dx = []; self.dy = []; self.hl = []; self.hw = []; self.col = []; self.ph = []; self.thick = []
+ self.stages = []
+ # canvas weave shows through where paint is thin
+ wx = np.sin(self.XX * 1.9) * 0.5 + 0.5; wy = np.sin(self.YY * 1.9) * 0.5 + 0.5
+ self.canvas = np.ones((H, W, 3), np.float32) * hexc('#e9dfc9') * (0.9 + 0.1 * (wx * wy))[..., None]
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ def noise(self, scale, octaves=3):
+ return noise2d(self.H, self.W, scale, octaves, self._seed())
+
+ # ------------------------------------------------------------ strokes
+ def layer(self, ref, angle, length=(30, 70), width=(10, 18), density=1.4, jitter=0.06, value_jitter=0.06, thickness=1.0, mask=None):
+ """lay one pass of strokes over the canvas (or only where mask > 0.5)"""
+ H, W = self.H, self.W
+ area = W * H if mask is None else float((mask > 0.5).sum())
+ mean = np.mean(length) * np.mean(width)
+ n = int(area / mean * density)
+ xs = self.rng.uniform(0, W, n); ys = self.rng.uniform(0, H, n)
+ if mask is not None:
+ keep = mask[ys.astype(int).clip(0, H - 1), xs.astype(int).clip(0, W - 1)] > 0.5
+ xs, ys = xs[keep], ys[keep]
+ im = Image.fromarray(self.ids.astype(np.int32))
+ d = ImageDraw.Draw(im)
+ base = len(self.cx)
+ for i in range(len(xs)):
+ x, y = xs[i], ys[i]
+ ix, iy = int(x), int(y)
+ a = angle[iy, ix] + self.rng.normal(0, jitter)
+ L = self.rng.uniform(*length) / 2; Wd = self.rng.uniform(*width) / 2
+ c = ref[iy, ix] * (1 + self.rng.normal(0, value_jitter)) + self.rng.normal(0, value_jitter * 0.4, 3)
+ dx, dy = np.cos(a), np.sin(a)
+ # rounded-rectangle outline of the stroke
+ pts = []
+ for t in np.linspace(-np.pi / 2, np.pi / 2, 6): # rounded head
+ pts.append((x + dx * L + (dx * np.cos(t) * Wd - dy * np.sin(t) * Wd) * 0.9, y + dy * L + (dy * np.cos(t) * Wd + dx * np.sin(t) * Wd) * 0.9))
+ for t in np.linspace(np.pi / 2, 3 * np.pi / 2, 6): # rounded tail
+ pts.append((x - dx * L + (dx * np.cos(t) * Wd - dy * np.sin(t) * Wd) * 0.9, y - dy * L + (dy * np.cos(t) * Wd + dx * np.sin(t) * Wd) * 0.9))
+ k = base + i
+ d.polygon(pts, fill=k)
+ self.cx.append(x); self.cy.append(y); self.dx.append(dx); self.dy.append(dy)
+ self.hl.append(L); self.hw.append(Wd); self.col.append(np.clip(c, 0, 1)); self.ph.append(self.rng.uniform(0, 6.28))
+ self.thick.append(thickness * self.rng.uniform(0.7, 1.15))
+ self.ids = np.asarray(im, np.int32)
+
+ def stroke_at(self, x, y, angle, length, width, colour, thickness=1.0):
+ """one explicit stroke (signatures, birds, accents)"""
+ c = hexc(colour) if isinstance(colour, str) else np.asarray(colour, np.float32)
+ ref = np.broadcast_to(c, (self.H, self.W, 3))
+ m = np.zeros((self.H, self.W), np.float32); m[int(y), int(x)] = 1
+ n0 = len(self.cx)
+ im = Image.fromarray(self.ids.astype(np.int32)); d = ImageDraw.Draw(im)
+ dx, dy = np.cos(angle), np.sin(angle); L = length / 2; Wd = width / 2
+ pts = []
+ for t in np.linspace(-np.pi / 2, np.pi / 2, 6):
+ pts.append((x + dx * L + (dx * np.cos(t) * Wd - dy * np.sin(t) * Wd) * 0.9, y + dy * L + (dy * np.cos(t) * Wd + dx * np.sin(t) * Wd) * 0.9))
+ for t in np.linspace(np.pi / 2, 3 * np.pi / 2, 6):
+ pts.append((x - dx * L + (dx * np.cos(t) * Wd - dy * np.sin(t) * Wd) * 0.9, y - dy * L + (dy * np.cos(t) * Wd + dx * np.sin(t) * Wd) * 0.9))
+ d.polygon(pts, fill=n0)
+ self.ids = np.asarray(im, np.int32)
+ self.cx.append(x); self.cy.append(y); self.dx.append(dx); self.dy.append(dy)
+ self.hl.append(L); self.hw.append(Wd); self.col.append(c); self.ph.append(self.rng.uniform(0, 6.28)); self.thick.append(thickness)
+
+ # ------------------------------------------------------------ render
+ def render(self, light=(-0.55, -0.65, 0.52), relief=2.4, spec=0.1, bristles=7):
+ ids = self.ids
+ painted = ids >= 0
+ k = np.where(painted, ids, 0)
+ cx = np.asarray(self.cx, np.float32)[k]; cy = np.asarray(self.cy, np.float32)[k]
+ dx = np.asarray(self.dx, np.float32)[k]; dy = np.asarray(self.dy, np.float32)[k]
+ hl = np.asarray(self.hl, np.float32)[k]; hw = np.asarray(self.hw, np.float32)[k]
+ ph = np.asarray(self.ph, np.float32)[k]; th = np.asarray(self.thick, np.float32)[k]
+ col = np.asarray(self.col, np.float32)[k]
+ px, py = self.XX - cx, self.YY - cy
+ along = (px * dx + py * dy) / (hl + hw) # -1 tail .. +1 head
+ across = (-px * dy + py * dx) / hw # -1 .. 1 across the stroke
+ ridge = smoothstep(0.0, 0.45, 1 - np.abs(across)) * (1 + 0.18 * np.abs(across) ** 3) # flat top, paint pushed to the edges
+ groove = 1 + 0.12 * np.sin(across * bristles * np.pi + ph) + 0.05 * np.sin(along * 11 + ph * 2)
+ start_blob = 1 + 0.35 * np.clip(1 - (along + 1) * 2.5, 0, 1) # paint piles up where the brush lands
+ end_fade = np.clip((1 - along) * 3, 0, 1) * 0.5 + 0.5
+ h = ridge * groove * start_blob * end_fade * th * painted
+ h = blur(h, 0.8)
+ gx = np.gradient(h, axis=1) * relief; gy = np.gradient(h, axis=0) * relief
+ nz = 1 / np.sqrt(gx ** 2 + gy ** 2 + 1)
+ nx, ny = -gx * nz, -gy * nz
+ L = np.asarray(light, np.float32); L = L / np.linalg.norm(L)
+ diffuse = np.clip(nx * L[0] + ny * L[1] + nz * L[2], 0, 1)
+ hv = L + np.array([0, 0, 1], np.float32); hv /= np.linalg.norm(hv)
+ specular = np.clip(nx * hv[0] + ny * hv[1] + nz * hv[2], 0, 1) ** 24
+ base = np.where(painted[..., None], col * (1 + 0.05 * (groove - 1))[..., None], self.canvas)
+ shade = (0.8 + 0.38 * diffuse)[..., None]
+ img = base * shade + spec * specular[..., None] * painted[..., None]
+ return np.clip(img, 0, 1)
+
+ def composite(self):
+ return Image.fromarray((self.render() * 255).astype(np.uint8))
+
+ def stage(self, name):
+ self.stages.append((name, self.composite()))
+
+ def save(self, path, stages_dir=None):
+ img = self.composite(); img.save(path)
+ if stages_dir:
+ import os
+ os.makedirs(stages_dir, exist_ok=True)
+ for i, (name, im) in enumerate(self.stages):
+ im.save(f"{stages_dir}/{i:02d}_{name}.png")
+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")
+ return img
diff --git a/lib/pixelart.py b/lib/pixelart.py
new file mode 100644
index 0000000..1377fd0
--- /dev/null
+++ b/lib/pixelart.py
@@ -0,0 +1,145 @@
+"""pixelart — retro pixel art at low resolution, upscaled crisply (numpy + Pillow only).
+
+The look: a small canvas (e.g. 320x180) painted pixel by pixel with a limited palette; gradients and
+glows use *ordered (Bayer) dithering* instead of smooth blends; hard 1-px outlines; tiny bitmap text;
+then a nearest-neighbour upscale (x6 -> 1920x1080) so every pixel stays a sharp square.
+
+ from pixelart import PixelArt
+ p = PixelArt(320, 180, scale=6, seed=1)
+ p.gradient(0, 0, 320, 120, '#141a33', '#2b2f5c')
+ p.rect(40, 60, 150, 140, '#6b3b3b')
+ p.glow(250, 80, 30, '#ffcf6b', 0.8)
+ p.text('CAFE', 70, 50, '#ff5fa2')
+ p.save('out.png')
+"""
+import numpy as np
+from PIL import Image, ImageDraw
+
+BAYER4 = np.array([[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]], np.float32) / 16 + 1 / 32
+
+FONT = { # 3x5 bitmap glyphs
+ 'A': ['010', '101', '111', '101', '101'], 'B': ['110', '101', '110', '101', '110'], 'C': ['011', '100', '100', '100', '011'],
+ 'D': ['110', '101', '101', '101', '110'], 'E': ['111', '100', '110', '100', '111'], 'F': ['111', '100', '110', '100', '100'],
+ 'G': ['011', '100', '101', '101', '011'], 'H': ['101', '101', '111', '101', '101'], 'I': ['111', '010', '010', '010', '111'],
+ 'K': ['101', '101', '110', '101', '101'], 'L': ['100', '100', '100', '100', '111'], 'M': ['101', '111', '111', '101', '101'],
+ 'N': ['110', '101', '101', '101', '101'], 'O': ['010', '101', '101', '101', '010'], 'P': ['110', '101', '110', '100', '100'],
+ 'R': ['110', '101', '110', '101', '101'], 'S': ['011', '100', '010', '001', '110'], 'T': ['111', '010', '010', '010', '010'],
+ 'U': ['101', '101', '101', '101', '011'], 'Y': ['101', '101', '010', '010', '010'], ' ': ['000'] * 5,
+ '0': ['111', '101', '101', '101', '111'], '1': ['010', '110', '010', '010', '111'], '2': ['110', '001', '010', '100', '111'],
+ '4': ['101', '101', '111', '001', '001'], '7': ['111', '001', '010', '010', '010'], '&': ['010', '101', '010', '101', '011'],
+}
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+class PixelArt:
+ def __init__(self, w=320, h=180, scale=6, seed=0, bg='#000000'):
+ self.w, self.h, self.scale = w, h, scale
+ self.rng = np.random.default_rng(seed)
+ self.YY, self.XX = np.mgrid[0:h, 0:w]
+ self.buf = np.ones((h, w, 3), np.float32) * _c(bg)
+ self.bayer = np.tile(BAYER4, (h // 4 + 1, w // 4 + 1))[:h, :w]
+ self.stages = []
+
+ # ------------------------------------------------------------ primitives (integer pixels)
+ def put(self, x, y, colour):
+ if 0 <= x < self.w and 0 <= y < self.h: self.buf[int(y), int(x)] = _c(colour)
+
+ def rect(self, x0, y0, x1, y1, colour):
+ self.buf[max(0, int(y0)):min(self.h, int(y1)), max(0, int(x0)):min(self.w, int(x1))] = _c(colour)
+
+ def mask_poly(self, pts):
+ im = Image.new('L', (self.w, self.h), 0)
+ ImageDraw.Draw(im).polygon([(float(x), float(y)) for x, y in pts], fill=1)
+ return np.asarray(im, bool)
+
+ def poly(self, pts, colour):
+ self.buf[self.mask_poly(pts)] = _c(colour)
+
+ def circle(self, cx, cy, r, colour):
+ self.buf[(self.XX - cx) ** 2 + (self.YY - cy) ** 2 <= r * r] = _c(colour)
+
+ def line(self, x0, y0, x1, y1, colour):
+ """Bresenham line"""
+ x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)
+ dx, dy = abs(x1 - x0), -abs(y1 - y0); sx = 1 if x0 < x1 else -1; sy = 1 if y0 < y1 else -1
+ err = dx + dy
+ while True:
+ self.put(x0, y0, colour)
+ if x0 == x1 and y0 == y1: break
+ e2 = 2 * err
+ if e2 >= dy: err += dy; x0 += sx
+ if e2 <= dx: err += dx; y0 += sy
+
+ def outline(self, mask, colour):
+ m = mask.astype(bool)
+ edge = m & ~(np.roll(m, 1, 0) & np.roll(m, -1, 0) & np.roll(m, 1, 1) & np.roll(m, -1, 1))
+ self.buf[edge] = _c(colour)
+
+ # ------------------------------------------------------------ dithering
+ def dither(self, mask, colour, alpha):
+ """ordered dither: paint `colour` where alpha beats the Bayer threshold (glows, fades, reflections)"""
+ on = mask.astype(bool) & (np.broadcast_to(alpha, (self.h, self.w)) > self.bayer)
+ self.buf[on] = _c(colour)
+
+ def gradient(self, x0, y0, x1, y1, c0, c1, steps=None):
+ """vertical gradient between two colours, banded through a small ramp and dithered between bands"""
+ m = np.zeros((self.h, self.w), bool); m[int(y0):int(y1), int(x0):int(x1)] = True
+ t = np.clip((self.YY - y0) / max(1, (y1 - y0)), 0, 1)
+ steps = steps or 5
+ ramp = [_c(c0) * (1 - k / (steps - 1)) + _c(c1) * (k / (steps - 1)) for k in range(steps)]
+ f = t * (steps - 1); lo = np.floor(f).astype(int); frac = f - lo
+ for k in range(steps):
+ sel = m & (lo == k)
+ self.buf[sel] = ramp[k]
+ if k + 1 < steps:
+ self.buf[sel & (frac > self.bayer)] = ramp[k + 1]
+
+ def glow(self, cx, cy, r, colour, strength=0.8, mask=None, squash=1.0):
+ d = np.hypot(self.XX - cx, (self.YY - cy) / squash) / r
+ a = np.clip(1 - d, 0, 1) ** 1.6 * strength
+ self.dither(np.ones((self.h, self.w), bool) if mask is None else mask, colour, a)
+
+ def text(self, s, x, y, colour, size=1, spacing=1):
+ cx = x
+ for ch in s.upper():
+ g = FONT.get(ch, FONT[' '])
+ for r, row in enumerate(g):
+ for c, bit in enumerate(row):
+ if bit == '1':
+ self.rect(cx + c * size, y + r * size, cx + (c + 1) * size, y + (r + 1) * size, colour)
+ cx += (3 + spacing) * size
+
+ def rain(self, n=220, colour='#8fa4c8', length=(4, 8), slant=1, box=None):
+ x0, y0, x1, y1 = box or (0, 0, self.w, self.h)
+ for _ in range(n):
+ x, y = int(self.rng.uniform(x0, x1)), int(self.rng.uniform(y0, y1))
+ L = int(self.rng.integers(*length))
+ for k in range(L):
+ if (k + x) % 2 == 0 or k < L - 1:
+ self.put(x - (k * slant) // 3, y + k, colour)
+
+ # ------------------------------------------------------------ output
+ def composite(self):
+ im = Image.fromarray((np.clip(self.buf, 0, 1) * 255).astype(np.uint8))
+ return im.resize((self.w * self.scale, self.h * self.scale), Image.NEAREST)
+
+ def stage(self, name):
+ self.stages.append((name, self.composite()))
+
+ def save(self, path, stages_dir=None):
+ img = self.composite(); img.save(path)
+ if stages_dir:
+ import os
+ os.makedirs(stages_dir, exist_ok=True)
+ for i, (name, im) in enumerate(self.stages):
+ im.save(f"{stages_dir}/{i:02d}_{name}.png")
+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")
+ return img
diff --git a/lib/ukiyoe.py b/lib/ukiyoe.py
new file mode 100644
index 0000000..5443ff9
--- /dev/null
+++ b/lib/ukiyoe.py
@@ -0,0 +1,164 @@
+"""ukiyoe — Japanese woodblock print (numpy + Pillow only).
+
+The look: every colour is its own carved block, printed flat onto washi with the wood grain showing
+through, slightly uneven pressure and a little registration drift; skies and seas use *bokashi*
+(a graded wipe of the block: strong at one edge, fading out); a black key block of confident outlines
+sits on top; a title cartouche and a red seal finish the print.
+
+ from ukiyoe import Ukiyoe
+ u = Ukiyoe(1920, 1080, seed=1)
+ u.bokashi(u.rect(0, 0, 1920, 600), '#2b4f8a', 0, 320) # sky: blue at the top fading down
+ u.block(u.poly(fuji), '#3d5a80')
+ u.key(fuji_outline)
+ u.cartouche(1640, 60, 110, 330, '富士曙')
+ u.save('out.png')
+"""
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from core import blur, fbm1d, spline, noise2d, smoothstep, polygon_mask, blob_pts, cjk_font
+
+
+def hexc(h):
+ h = h.lstrip('#')
+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
+
+
+def _c(c):
+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)
+
+
+class Ukiyoe:
+ def __init__(self, W=1920, H=1080, seed=0, washi='#efe2c4'):
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ p = np.ones((H, W, 3), np.float32) * _c(washi)
+ p *= (0.97 + 0.05 * noise2d(H, W, 220, 4, 1))[..., None] # age / foxing
+ fib = Image.new('L', (W, H), 0); d = ImageDraw.Draw(fib)
+ for _ in range(2200):
+ x, y = self.rng.uniform(0, W), self.rng.uniform(0, H); a = self.rng.uniform(0, np.pi); L = self.rng.uniform(6, 30)
+ d.line([(x, y), (x + np.cos(a) * L, y + np.sin(a) * L)], fill=int(self.rng.uniform(8, 20)), width=1)
+ p *= (1 - 0.3 * blur(np.asarray(fib, np.float32) / 255, 0.5))[..., None]
+ self.img = p
+ self.offsets = {}
+ self.texts = []
+ self.stages = []
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ------------------------------------------------------------ shapes
+ def poly(self, pts):
+ return polygon_mask(self.H, self.W, pts, ss=2)
+
+ def rect(self, x0, y0, x1, y1):
+ return ((self.XX >= x0) & (self.XX < x1) & (self.YY >= y0) & (self.YY < y1)).astype(np.float32)
+
+ def circle(self, cx, cy, r):
+ return np.clip(r - np.hypot(self.XX - cx, self.YY - cy) + 0.5, 0, 1)
+
+ # ------------------------------------------------------------ printing
+ def _register(self, m, key):
+ if key not in self.offsets:
+ self.offsets[key] = (int(self.rng.integers(-2, 3)), int(self.rng.integers(-2, 3)))
+ dx, dy = self.offsets[key]
+ out = np.zeros_like(m)
+ out[max(dy, 0):self.H + min(dy, 0), max(dx, 0):self.W + min(dx, 0)] = m[max(-dy, 0):self.H + min(-dy, 0), max(-dx, 0):self.W + min(-dx, 0)]
+ return out
+
+ def _wood(self, seed):
+ """wood grain: noise stretched along x, plus a little pressure unevenness"""
+ g = noise2d(max(2, self.H), max(2, self.W // 12), 3, 2, seed)
+ g = np.asarray(Image.fromarray(g.astype(np.float32)).resize((self.W, self.H), Image.BILINEAR))
+ return 0.88 + 0.12 * g + 0.06 * (noise2d(self.H, self.W, 160, 3, seed + 1) - 0.5)
+
+ def block(self, mask, colour, strength=0.95, key=None):
+ """print one flat colour block (opaque-ish pigment in water, shows wood grain)"""
+ col = _c(colour)
+ m = self._register(mask, key or (colour if isinstance(colour, str) else tuple(colour)))
+ a = np.clip(m * strength * self._wood(self._seed()), 0, 1)[..., None]
+ self.img = self.img * (1 - a) + col * a
+
+ def bokashi(self, mask, colour, y_strong, y_fade, strength=0.95, key=None):
+ """graded wipe: full colour at y_strong fading to nothing at y_fade (either direction)"""
+ t = np.clip((self.YY - y_strong) / (y_fade - y_strong), 0, 1)
+ grade = (1 - t) ** 1.4
+ self.block(mask * grade, colour, strength, key)
+
+ def key(self, pts, width=4, colour='#2a2320', closed=False):
+ """black key-block outline: crisp but slightly varying, printed on top"""
+ P = np.asarray(pts, np.float32)
+ if closed: P = np.vstack([P, P[:1]])
+ n = len(P)
+ wv = width * (0.85 + 0.3 * (fbm1d(n, max(3, n / 5), 2, self._seed()) + 1) / 2)
+ im = Image.new('L', (self.W * 2, self.H * 2), 0); d = ImageDraw.Draw(im)
+ for i in range(n - 1):
+ d.line([(P[i, 0] * 2, P[i, 1] * 2), (P[i + 1, 0] * 2, P[i + 1, 1] * 2)], fill=255, width=max(1, int(wv[i] * 2)))
+ r = wv[i]
+ d.ellipse((P[i + 1, 0] * 2 - r, P[i + 1, 1] * 2 - r, P[i + 1, 0] * 2 + r, P[i + 1, 1] * 2 + r), fill=255)
+ m = np.asarray(im.resize((self.W, self.H), Image.LANCZOS), np.float32) / 255
+ self.block(m, colour, 0.97, key='__key__')
+
+ # ------------------------------------------------------------ motifs
+ def cloud_band(self, x0, x1, y, h, colour='#f4ebd5', outline=True, glow=None):
+ """long stylised mist/cloud band with scalloped ends (Hiroshige style)"""
+ top = [(x, y - h / 2 + 4 * np.sin(x / 37)) for x in np.linspace(x0 + h / 2, x1 - h / 2, 30)]
+ right = [(x1 - h / 2 + np.cos(t) * h / 2, y + np.sin(t) * h / 2) for t in np.linspace(-np.pi / 2, np.pi / 2, 10)]
+ bot = [(x, y + h / 2 + 4 * np.sin(x / 41)) for x in np.linspace(x1 - h / 2, x0 + h / 2, 30)]
+ left = [(x0 + h / 2 + np.cos(t) * h / 2, y + np.sin(t) * h / 2) for t in np.linspace(np.pi / 2, 3 * np.pi / 2, 10)]
+ pts = top + right + bot + left
+ m = self.poly(pts)
+ self.block(m, colour, 1.15) # opaque: clouds cover what is behind
+ if glow: self.bokashi(m, glow, y + h / 2, y - h * 0.1, 0.55) # warm light on the underside
+ if outline: self.key(pts, 2.4, closed=True)
+
+ def seigaiha(self, mask, colour, r=34, width=2.2):
+ """overlapping-wave pattern (rows of concentric half-circles, lower rows cover upper ones)"""
+ ys = np.nonzero(mask.max(1) > 0)[0]
+ if len(ys) == 0: return
+ m = np.zeros((self.H, self.W), np.float32)
+ for row, cy in enumerate(np.arange(ys.min() - r, ys.max() + r, r * 0.5)):
+ off = (row % 2) * r
+ dx = np.mod(self.XX - off + r, 2 * r) - r
+ d = np.hypot(dx, self.YY - cy)
+ disk = (d < r) & (self.YY <= cy)
+ m[disk] = 0 # this row covers the arcs of the row above
+ for k in (1.0, 0.72, 0.44):
+ ring = np.clip(width / 2 - np.abs(d - r * k) + 0.5, 0, 1) * disk
+ m = np.maximum(m, ring)
+ self.block(m * mask, colour, 0.9)
+
+ def cartouche(self, x, y, w, h, text, colour='#f6e7c3', text_colour='#2a2320'):
+ """title cartouche: pale box, key-block outline, vertical title"""
+ self.block(self.rect(x, y, x + w, y + h), colour, 0.97, key='__cartouche__')
+ self.key([(x, y), (x + w, y), (x + w, y + h), (x, y + h)], 3, closed=True)
+ self.texts.append(('v', text, x + w * 0.16, y + w * 0.16, w * 0.68, text_colour))
+
+ def seal(self, x, y, size, text, colour='#b8372d'):
+ self.block(self.rect(x, y, x + size, y + size * 1.3), colour, 0.95, key='__seal__')
+ self.texts.append(('v', text, x + size * 0.18, y + size * 0.12, size * 0.62, '#f6e7c3'))
+
+ # ------------------------------------------------------------ output
+ def composite(self):
+ out = Image.fromarray((np.clip(self.img, 0, 1) * 255).astype(np.uint8))
+ fp = cjk_font()
+ if self.texts and fp:
+ dr = ImageDraw.Draw(out)
+ for kind, s, x, y, size, col in self.texts:
+ f = ImageFont.truetype(fp, int(size), index=0)
+ for i, ch in enumerate(s):
+ dr.text((x, y + i * size * 1.12), ch, font=f, fill=tuple(int(v * 255) for v in _c(col)))
+ return out
+
+ def stage(self, name):
+ self.stages.append((name, self.composite()))
+
+ def save(self, path, stages_dir=None):
+ img = self.composite(); img.save(path)
+ if stages_dir:
+ import os
+ os.makedirs(stages_dir, exist_ok=True)
+ for i, (name, im) in enumerate(self.stages):
+ im.save(f"{stages_dir}/{i:02d}_{name}.png")
+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")
+ return img
diff --git a/lib/watercolor.py b/lib/watercolor.py
index 01f4924..ded9849 100644
--- a/lib/watercolor.py
+++ b/lib/watercolor.py
@@ -78,7 +78,7 @@ class Watercolor:
r = m[src, :] * (ys[:, None] > y0)
r = blur(r, soft)
rip = noise2d(self.H, self.W, 4, 2, self._seed())
- rip = np.asarray(Image.fromarray(rip, mode='F').resize((self.W // 40, self.H), Image.BILINEAR).resize((self.W, self.H), Image.BILINEAR))
+ rip = np.asarray(Image.fromarray(rip.astype(np.float32)).resize((self.W // 40, self.H), Image.BILINEAR).resize((self.W, self.H), Image.BILINEAR))
return r * (1 - breakup + breakup * smoothstep(0.3, 0.7, rip))
def band(self, pts, width, soft=2.0):