Spaces:
Running
Running
remove retro 64 renderer; cleaner pixel-art finish (flat cel bands, no dither noise, tight palette) - pydraw f25d6fb
Browse filesFiles changed (3)
- app.py+3-8
- pydraw/pixelart.py+102
- pydraw3d/retro64.pyDeleted-392
12 unmodified lines13141516171819202122232425262728293 unmodified lines33343536373839404128 unmodified lines707172737475767712 unmodified linesfrom PIL import Imagefrom pydraw import plot, CONCEPTSfrom pydraw3d import plot3dfrom pydraw3d.retro64 import retro64from pydraw3d.families import FAMILIES, TAXAEXAMPLES = ["an orange cat dressed as a chef", "a frog on a mushroom", "a red hot air balloon", "a narwhal swimming under an iceberg", "a quokka smiling at the camera", "an oil painting of a horse in a field","a red fox in an autumn forest", "a castle on a hill with a dragon flying above it at sunset","a pagoda beside a cherry blossom tree", "a pangolin walking on a dirt path", "a bowl of ramen with chopsticks","three yellow ducks swimming on a lake", "a watercolor painting of a lighthouse at night","a hedgehog curled up next to an acorn", "a violin leaning against a stack of old books","four green apples and a banana on a table", "a pencil sketch of a cat next to a vase"]RENDERERS = ["pixel", "retro 64", "3D", "smooth"]def to_pil(img):3 unmodified linesdef _draw(prompt, seed, renderer, size, variation, search=False):if renderer == "retro 64":im, tr = retro64(prompt, seed=seed, size=size, variation=variation, return_trace=True)return im, im.info.get("scene") or {}, trif renderer == "3D":im, tr = plot3d(prompt, seed=seed, size=size, res=min(size, 384), variation=variation, return_trace=True, search=search)return im, im.info.get("scene") or {}, tr28 unmodified lineswith gr.Blocks(title="pydraw") as demo:gr.Markdown("# pydraw\nText to image with rules only: no weights, no training, no image files. ""%d hand-made concepts, plus any common noun through WordNet and %d generator families (%d word entries). ""Renderers: pixel art; retro 64 (real 64 x 64 pixel-art sprites and scenes with a small palette, drawn from the 3D models, ~2 s); ""a 3D ray-marcher (slower, ~10-40 s on this CPU); or smooth. ""Style words work too: watercolor, pencil sketch, oil painting, comic, black and white, neon, pop art."% (len(CONCEPTS), len(FAMILIES), len(TAXA)))with gr.Row():12 unmodified lines131415161718192021222324252627283 unmodified lines32333435363728 unmodified lines6667686970717212 unmodified linesfrom PIL import Imagefrom pydraw import plot, CONCEPTSfrom pydraw3d import plot3dfrom pydraw3d.families import FAMILIES, TAXAEXAMPLES = ["a frog on a mushroom in a forest", "a narwhal swimming under an iceberg", "a quokka smiling at the camera", "an oil painting of a horse in a field","a red fox in an autumn forest", "a castle on a hill with a dragon flying above it at sunset","a pagoda beside a cherry blossom tree", "a pangolin walking on a dirt path", "a bowl of ramen with chopsticks","three yellow ducks swimming on a lake", "a watercolor painting of a lighthouse at night","a hedgehog curled up next to an acorn", "a violin leaning against a stack of old books","four green apples and a banana on a table", "a pencil sketch of a cat next to a vase"]RENDERERS = ["pixel", "3D", "smooth"]def to_pil(img):3 unmodified linesdef _draw(prompt, seed, renderer, size, variation, search=False):if renderer == "3D":im, tr = plot3d(prompt, seed=seed, size=size, res=min(size, 384), variation=variation, return_trace=True, search=search)return im, im.info.get("scene") or {}, tr28 unmodified lineswith gr.Blocks(title="pydraw") as demo:gr.Markdown("# pydraw\nText to image with rules only: no weights, no training, no image files. ""%d hand-made concepts, plus any common noun through WordNet and %d generator families (%d word entries). ""Renderers: pixel art, a 3D ray-marcher (slower, ~10-40 s on this CPU), or smooth. ""Style words work too: watercolor, pencil sketch, oil painting, comic, black and white, neon, pop art."% (len(CONCEPTS), len(FAMILIES), len(TAXA)))with gr.Row():
51 unmodified lines525354555657585959 unmodified lines11912012112212312451 unmodified linesreturn bestdef finish(cv, outline_ids, trace, dither=6.0):W, H = cv.w, cv.hpx, ids = cv.px, cv.ids# rule: selective outline - an object's silhouette pixels darken where it borders something behind itarea = {}59 unmodified linesq = nearest((p[0] + t, p[1] + t, p[2] + t))p[0], p[1], p[2] = qtrace.append("pixelart: snapped to %d-colour palette with 4x4 ordered dither" % len(PALETTE))def upscale(px, k):51 unmodified lines52535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115259 unmodified lines21221321421521621721821922022122222322422522651 unmodified linesreturn bestLOOK = _EXP.get("look", "clean") # "clean": flat cel bands, tight palette, no dither noise; "classic": the old finishdef _celband(px, ids, trace, k_obj=6):"""rule (clean pixel-art look): inside each object, colours collapse to a few flat clusters (k-means in RGB, k<=6):shading becomes 3-4 clean bands and texture noise disappears, while real markings (stripes, spots, a rug'spattern) survive as their own clusters"""import numpy as npA = np.asarray(px, float)I = np.asarray(ids)out = A.copy()n = 0for k in np.unique(I):if k == 0:continuem = I == kif m.sum() < 30:continueX = A[m]kk = min(k_obj, max(2, int(m.sum() ** .5 / 4)))# deterministic init: spread over luminancelum = X @ np.array([.3, .59, .11])order = np.argsort(lum)C = X[order[np.linspace(0, len(X) - 1, kk).astype(int)]].copy()for _ in range(8):d = ((X[:, None, :] - C[None]) ** 2).sum(-1)a = d.argmin(1)for j in range(kk):if (a == j).any():C[j] = X[a == j].mean(0)out[m] = C[a]n += 1trace.append("pixelart: flat cel bands inside %d objects" % n)return outdef _orphans(A, ids):"""rule: a lone pixel whose colour none of its 4 neighbours share, inside a run where 5+ of its 8 neighboursagree, takes that colour (noise, not a feature; features are 2+ pixels or a different object)"""import numpy as npH, W, _ = A.shapekey = (A[..., 0].astype(np.int64) << 16) | (A[..., 1].astype(np.int64) << 8) | A[..., 2].astype(np.int64)out = A.copy()n = 0for y in range(1, H - 1):for x in range(1, W - 1):c = key[y, x]if c == key[y - 1, x] or c == key[y + 1, x] or c == key[y, x - 1] or c == key[y, x + 1]:continueblk = key[y - 1:y + 2, x - 1:x + 2].ravel()iblk = ids[y - 1:y + 2, x - 1:x + 2].ravel()same = blk[iblk == ids[y, x]]same = same[same != c]if len(same) < 5:continuev, cnt = np.unique(same, return_counts=True)if cnt.max() >= 5:j = int(np.nonzero(blk == v[cnt.argmax()])[0][0])out[y, x] = A[y - 1 + j // 3, x - 1 + j % 3]n += 1return out, ndef _tight_palette(A, colors):"""rule: the whole picture uses one small palette (median cut, no dithering) - every pixel is one of ~48 colours"""import numpy as npfrom PIL import Image as _Iim = _I.fromarray(np.clip(A, 0, 255).astype(np.uint8))q = np.asarray(im.quantize(colors=colors, method=_I.Quantize.MEDIANCUT, dither=_I.Dither.NONE).convert("RGB"), float)# rule: near-identical shades (a wall's faint noise) merge into one colour - otherwise they posterize into# blotches; the more common colour absorbs the rarer onethr = float(_EXP.get("pmerge", 13.0))flat = q.reshape(-1, 3)cols, inv, cnt = np.unique(flat, axis=0, return_inverse=True, return_counts=True)inv = inv.ravel()order = np.argsort(-cnt)target = np.arange(len(cols))kept = []for j in order:for i in kept:d = cols[j] - cols[i]if (2 * d[0] ** 2 + 4 * d[1] ** 2 + 3 * d[2] ** 2) ** .5 / 3 < thr:target[j] = ibreakelse:kept.append(j)return cols[target[inv]].reshape(q.shape)def finish(cv, outline_ids, trace, dither=6.0):W, H = cv.w, cv.hif LOOK == "clean":import numpy as npcv.px = [[list(p) for p in row] for row in _celband(cv.px, cv.ids, trace)]dither = float(_EXP.get("cdither", 0.0)) # rule: no screen-door dither; gradients become clean bandspx, ids = cv.px, cv.ids# rule: selective outline - an object's silhouette pixels darken where it borders something behind itarea = {}59 unmodified linesq = nearest((p[0] + t, p[1] + t, p[2] + t))p[0], p[1], p[2] = qtrace.append("pixelart: snapped to %d-colour palette with 4x4 ordered dither" % len(PALETTE))if LOOK == "clean":import numpy as npA = np.asarray(px, float)A, n = _orphans(A, np.asarray(ids))A = _tight_palette(A, int(_EXP.get("ncol", 48)))for y in range(H):for x in range(W):px[y][x][0], px[y][x][1], px[y][x][2] = A[y, x]trace.append("pixelart: %d orphan pixels cleaned; tight %d-colour palette" % (n, int(_EXP.get("ncol", 48))))def upscale(px, k):
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392"""retro64: real 64 x 64 pixel art in the look of small pixel-art sprite models (in the spirit of Retro Diffusion'sRD Flow 64 samples), drawn purely in code.
Look we aim at (studied from that model card's published samples, no model involved):- a real 64 x 64 grid, every pixel one entry of a small palette (~16-40 colours), binary transparency;- a single subject: a transparent sprite, centred, filling most of the height with a clear margin; shown on a dark navy backdrop;- dark, hue-shifted outlines (a darker version of the local colour, not pure black), lighter lines between parts;- flat cel shading: 3-4 bands per material, light from the upper left, shadows shift toward blue / purple and get more saturated, highlights shift toward yellow, a bright rim on lit edges;- scenes (a place, a time of day): a full 64 x 64 frame with banded gradients and the same palette discipline.
Pipeline: the normal 3D layout (pydraw3d.plot3d, preview mode) gives the placed models; sprites are re-marched with anorthographic camera on a 3x supersampled 64 x 64 grid, with an object/part id per sample so small parts (eyes) wintheir pixel and outlines follow real part boundaries. Pure numpy; no image files, no learned weights."""import colorsysimport mathimport numpy as npfrom PIL import Image
BACKDROP = (23, 20, 32) # the dark navy the sprites are shown onN = 64
# ----------------------------------------------------------------------------------------------- colour helpersdef _hsv(c): return np.array(colorsys.rgb_to_hsv(*np.clip(c, 0, 1)))
def _rgb(h, s, v): return np.array(colorsys.hsv_to_rgb(h % 1.0, min(max(s, 0), 1), min(max(v, 0), 1)))
def _toward(h, target, amt): d = ((target - h + .5) % 1.0) - .5 return h + d * amt
def ramp_color(base, band): """rule (pixel art): one material colour -> a shading ramp. band -2 (deep shadow) .. +2 (highlight): shadows darken, gain saturation and shift hue toward blue-violet; highlights brighten, lose saturation and shift toward warm yellow. Grey/white materials get a cool shadow tint so they still read as lit.""" h, s, v = _hsv(base) if band < 0: k = -band if s < .12: # rule: neutral colours borrow a cool violet tint in shadow h, s = .70, s + .10 * k h = _toward(h, .70, .06 * k) s = s + .10 * k v = v * (1 - .20 * k) - .02 * k elif band > 0: k = band h = _toward(h, .14, .035 * k) s = s * (1 - .16 * k) v = v + (1 - v) * .35 * k + .05 * k return _rgb(h, s, v)
def outline_color(base): """rule: outline = a very dark, saturated, hue-shifted version of the local colour (dark brown for orange fur, deep navy for blue, near-black violet for black), never flat black""" h, s, v = _hsv(base) if s < .12: h, s = .72, .35 h = _toward(h, .72, .10) return _rgb(h, min(1, s + .25), min(.20, v * .28 + .06))
# ------------------------------------------------------------------------------------------------ 3D layoutdef _layout(text, seed, variation): """Run the normal 3D layout once, cheaply, and return its buffers (placed objects, scene).""" from . import plot3d im = plot3d(text, seed=seed, size=64, res=256, variation=variation, exp={"preview": "8", "msteps": "24", "shsteps": "2", "ncam": "0", "paint": "0", "fallback": "skip"}) return im.info.get("buffers"), im.info.get("scene") or {}, im.info.get("trace") or []
def _view_basis(tilt_deg=12.0): t = math.radians(tilt_deg) D = np.array([0.0, -math.sin(t), math.cos(t)]) up = np.array([0.0, math.cos(t), math.sin(t)]) right = np.array([1.0, 0.0, 0.0]) return D, up, right
def _march_ortho(sc, u, v, D, up, right, c0, back=40.0): from . import march O = c0[None, :] + u[:, None] * right[None, :] + v[:, None] * up[None, :] - D[None, :] * back Dm = np.tile(D, (len(O), 1)) t, hit = march(sc, O, Dm, 2 * back, steps=200) return O, Dm, t, hit
def render_sprite64(objs, ss=3, margin=5, light=(-.55, .70, -.45)): """Orthographic 64 x 64 sprite of the placed objects. Returns (ids (N,N) int: -1 empty, index into a part table), rgb (N,N,3) linear-ish 0-1 shaded and banded, part table).""" from . import Scene3D, normals, texture, pattern, lin sc = Scene3D(objs, ground=False) D, up, right = _view_basis() # framing pass: coarse grid around the bounding spheres -> the exact silhouette box cen = np.mean([o.center for o in objs], 0) ext = max(np.max(np.abs(o.center - cen)) + o.radius for o in objs) g = 72 gu, gv = np.meshgrid(np.linspace(-ext, ext, g), np.linspace(ext, -ext, g)) _, _, _, hit = _march_ortho(sc, gu.ravel(), gv.ravel(), D, up, right, cen) if not hit.any(): return None hu, hv = gu.ravel()[hit], gv.ravel()[hit] cell = 2 * ext / (g - 1) u0, u1, v0, v1 = hu.min() - cell, hu.max() + cell, hv.min() - cell, hv.max() + cell # rule (framing): the subject fills most of the frame with a clear margin on every side (whole subject visible) avail = N - 2 * margin px = max(u1 - u0, v1 - v0) / avail uc, vc = (u0 + u1) / 2, (v0 + v1) / 2 n = N * ss s = (np.arange(n) + .5) / ss - N / 2 U, V = np.meshgrid(uc + s * px, vc - s * px) # rule: sit the subject a little low (its feet on a ground line near the bottom margin) V = V + (N / 2 - margin - (v1 - v0) / px / 2) * px * .35 O, Dm, t, hit = _march_ortho(sc, U.ravel(), V.ravel(), D, up, right, cen) M = n * n pid = np.full(M, -1) alb = np.zeros((M, 3)) nrm = np.zeros((M, 3)) em = np.zeros(M) table = [] # (obj index, part index, base colour, part) hi = np.nonzero(hit)[0] if len(hi): P = O[hi] + Dm[hi] * t[hi, None] nrm[hi] = normals(sc, P, 1e-3 * max(o.scale for o in objs)) _, oid = sc.dist(P, want_id=True) for k, ob in enumerate(objs): mk = oid == k if not mk.any(): continue pi, q = ob.part_index(P[mk]) idx = hi[mk] for j, pt in enumerate(ob.parts): m = pi == j if not m.any(): continue tid = len(table) table.append((k, j, np.asarray(pt.color, float) / 255.0, pt)) pid[idx[m]] = tid a = texture(pt.tex, q[m], lin(pt.color), j) pat = getattr(pt, "pat", None) if pat: a = pattern(pat, q[m], a) alb[idx[m]] = np.clip(a, 0, 1) ** (1 / 2.2) em[idx[m]] = getattr(pt, "emit", 0.0) # ---- per output pixel: the winning part among its ss x ss samples pid_b = pid.reshape(N, ss, N, ss).transpose(0, 2, 1, 3).reshape(N, N, ss * ss) area = np.bincount(pid[pid >= 0], minlength=max(1, len(table))).astype(float) cover = (pid_b >= 0).sum(-1) out_id = np.full((N, N), -1) best = np.zeros((N, N)) for tid in np.unique(pid[pid >= 0]): c = (pid_b == tid).sum(-1).astype(float) # rule: a small part (an eye, a nose, a button) wins its pixel from fewer samples than a big one, so tiny # features survive the 64 px grid instead of averaging away score = c / (area[tid] ** .35 + 1e-6) * (c >= max(1, ss * ss // 4)) better = score > best out_id[better], best[better] = tid, score[better] out_id[cover < (ss * ss + 1) // 2] = -1 # rule: binary transparency, a pixel is in when most samples hit # rule: a pixel the coverage rule kept but no part won takes its most frequent part lost = (out_id < 0) & (cover >= (ss * ss + 1) // 2) if lost.any(): for y, x in zip(*np.nonzero(lost)): v = pid_b[y, x][pid_b[y, x] >= 0] out_id[y, x] = np.bincount(v).argmax() # mean albedo / normal of the winning part's samples alb_b = alb.reshape(N, ss, N, ss, 3).transpose(0, 2, 1, 3, 4).reshape(N, N, ss * ss, 3) nrm_b = nrm.reshape(N, ss, N, ss, 3).transpose(0, 2, 1, 3, 4).reshape(N, N, ss * ss, 3) w = (pid_b == out_id[..., None]).astype(float)[..., None] A = (alb_b * w).sum(2) / np.maximum(w.sum(2), 1e-6) Nn = (nrm_b * w).sum(2) Nn /= np.maximum(np.linalg.norm(Nn, axis=-1, keepdims=True), 1e-6) # depth per pixel (for interior lines: a part in front of another) tt = np.where(hit, t, np.inf).reshape(N, ss, N, ss).transpose(0, 2, 1, 3).reshape(N, N, ss * ss) Z = np.where(w[..., 0] > 0, tt, np.inf).min(-1) em_b = em.reshape(N, ss, N, ss).transpose(0, 2, 1, 3).reshape(N, N, ss * ss) E = (em_b * w[..., 0]).sum(-1) / np.maximum(w[..., 0].sum(-1), 1e-6) L = np.asarray(light, float) L /= np.linalg.norm(L) return dict(ids=out_id, alb=A, nrm=Nn, depth=Z, emit=E, table=table, L=L, px=px)
# ------------------------------------------------------------------------------------------------ stylisedef _bands(nrm, L, ids): """rule (cel shading): lambert -> 4 bands (-2 deep shadow, -1 shadow, 0 lit, +1 light) plus +2 rim highlights on the lit edge of each shape""" d = (nrm @ L) b = np.where(d > .55, 1, np.where(d > .12, 0, np.where(d > -.30, -1, -2))) # bright rim: a pixel whose up-left neighbour is empty or another part, facing the light sh = np.full_like(ids, -9) sh[1:, 1:] = ids[:-1, :-1] up = np.full_like(ids, -9) up[1:, :] = ids[:-1, :] rim = (ids >= 0) & ((sh != ids) | (up != ids)) & (d > .25) b = np.where(rim, np.maximum(b, 1) + (d > .5), b) return np.clip(b, -2, 2)
def _quantize(rgb, mask, colors): """rule: an exact small palette (median cut, no dithering): every pixel points at one palette entry""" pts = (np.clip(rgb[mask], 0, 1) * 255 + .5).astype(np.uint8) if len(pts) == 0: return rgb k = len(np.unique(pts.reshape(-1, 3), axis=0)) if k <= colors: out = rgb.copy() out[mask] = pts / 255.0 return out im = Image.fromarray(pts.reshape(1, -1, 3)) q = im.quantize(colors=colors, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE).convert("RGB") out = rgb.copy() out[mask] = np.asarray(q).reshape(-1, 3) / 255.0 return out
def _cleanup(rgb, mask, keep): """rule (pixel art): remove orphan pixels - a lone pixel whose colour no 4-neighbour shares, inside a region where 5+ of its 8 neighbours agree, takes that majority colour (texture noise, not features)""" key = (np.clip(rgb, 0, 1) * 255).astype(int) key = key[..., 0] * 65536 + key[..., 1] * 256 + key[..., 2] out = rgb.copy() H, W = mask.shape for y in range(1, H - 1): for x in range(1, W - 1): if not mask[y, x] or keep[y, x]: continue c = key[y, x] n4 = [key[y - 1, x], key[y + 1, x], key[y, x - 1], key[y, x + 1]] if c in n4: continue nb = key[y - 1:y + 2, x - 1:x + 2].ravel() nb = np.delete(nb, 4) vals, cnt = np.unique(nb, return_counts=True) if cnt.max() >= 5: v = vals[cnt.argmax()] yy, xx = np.nonzero(key[y - 1:y + 2, x - 1:x + 2] == v) out[y, x] = rgb[y - 1 + yy[0], x - 1 + xx[0]] return out
def stylise_sprite(r, colors=32): ids, A, Nn, Z, E, table, L = r["ids"], r["alb"], r["nrm"], r["depth"], r["emit"], r["table"], r["L"] mask = ids >= 0 band = _bands(Nn, L, ids) rgb = np.zeros((N, N, 3)) for y, x in zip(*np.nonzero(mask)): rgb[y, x] = ramp_color(A[y, x], int(band[y, x])) if E[y, x] > .3: # rule: glowing parts (flames, lamps) stay bright and unshaded rgb[y, x] = ramp_color(A[y, x], 1) # rule: small parts (eyes, noses, buttons) are features - keep them out of the orphan cleanup area = np.bincount(ids[mask], minlength=len(table)) feat = mask & (area[np.maximum(ids, 0)] <= 6) # rule: interior lines where one part sits in front of another (depth jump), drawn on the farther pixel in a # darker shade of its own colour - lighter than the silhouette outline (selective outline) line = np.zeros_like(mask) for dy, dx in ((0, 1), (1, 0), (0, -1), (-1, 0)): nid = np.roll(ids, (dy, dx), (0, 1)) nz = np.roll(Z, (dy, dx), (0, 1)) jump = mask & (nid >= 0) & (nid != ids) & (np.nan_to_num(Z - nz, nan=0.0, posinf=0.0, neginf=0.0) > 1.6 * r["px"]) & ~feat line |= jump for y, x in zip(*np.nonzero(line)): rgb[y, x] = ramp_color(A[y, x], -2) * .8 rgb = _quantize(rgb, mask, colors - 6) rgb = _cleanup(rgb, mask, feat | line) # rule: silhouette outline one pixel outside the shape, coloured from the neighbouring part (dark brown around # orange fur, deep blue around blue cloth); corners are filled only where two sides touch (clean diagonals) out_rgb = rgb.copy() alpha = mask.copy() for y in range(N): for x in range(N): if mask[y, x]: continue nbs = [(y + dy, x + dx) for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1)) if 0 <= y + dy < N and 0 <= x + dx < N and mask[y + dy, x + dx]] if nbs: cs = np.mean([A[p] for p in nbs], 0) out_rgb[y, x] = outline_color(cs) alpha[y, x] = True return out_rgb, alpha
# ------------------------------------------------------------------------------------------------ scenesdef stylise_scene(buf, colors=40): """Full-frame scene: the 3D preview buffers at 3x -> 64 x 64 (mode of object id per pixel, mean colour of the winning id), banded value, saturated / hue-shifted shadows, small palette, outlines around prompted subjects.""" rgb, ids = buf["rgb"], buf["ids"] n = rgb.shape[0] ss = n // N rb = rgb[:N * ss, :N * ss].reshape(N, ss, N, ss, 3).transpose(0, 2, 1, 3, 4).reshape(N, N, ss * ss, 3) ib = ids[:N * ss, :N * ss].reshape(N, ss, N, ss).transpose(0, 2, 1, 3).reshape(N, N, ss * ss) win = np.zeros((N, N), int) for y in range(N): for x in range(N): v, c = np.unique(ib[y, x], return_counts=True) win[y, x] = v[c.argmax()] w = (ib == win[..., None]).astype(float)[..., None] col = (rb * w).sum(2) / np.maximum(w.sum(2), 1e-6) # rule: pixel-art colour - more saturation and contrast than a photo, shadows pushed toward violet out = np.zeros_like(col) for y in range(N): for x in range(N): h, s, v = _hsv(col[y, x]) if v < .45: h = _toward(h, .70, .25 * (.45 - v) / .45) s = min(1, s * 1.15 + .06) s = min(1, s * 1.18) v = min(1, .5 + (v - .5) * 1.12) out[y, x] = _rgb(h, s, v) mask = np.ones((N, N), bool) out = _quantize(out, mask, colors) subj = np.zeros((N, N), bool) objs = buf["objs"] for k, o in enumerate(objs): if getattr(o, "ent", None) is not None: subj |= win == k out = _cleanup(out, mask, np.zeros_like(mask)) # rule: prompted subjects get a dark hue-shifted outline on their own edge pixels (scenery stays soft) edge = subj & ((np.roll(win, 1, 0) != win) | (np.roll(win, -1, 0) != win) | (np.roll(win, 1, 1) != win) | (np.roll(win, -1, 1) != win)) edge[0, :] = edge[-1, :] = False edge[:, 0] = edge[:, -1] = False for y, x in zip(*np.nonzero(edge)): out[y, x] = outline_color(col[y, x]) return out
# ------------------------------------------------------------------------------------------------ entry pointSCENE_WORDS = ("scene", "landscape", "background", "view of", "at night", "at sunset", "at sunrise", "at dawn", "at dusk", "underwater", "on a beach")
def is_sprite(text, scene): """rule: one subject (or a subject on a support) with no place / time / backdrop words -> transparent sprite; anything with a setting -> a full 64 x 64 scene""" t = " " + text.lower() + " " if scene.get("place") or any(w in t for w in SCENE_WORDS): return False return len(scene.get("entities", [])) <= 3
def retro64(text, seed=0, size=512, variation=1.0, mode="auto", colors=32, return_trace=False, backdrop=BACKDROP): """text -> (preview PIL image at `size` (nearest-neighbour upscale of the 64 x 64 art on the backdrop), and .info['pixels'] = the 64 x 64 RGBA art itself)""" buf, scene, trace = _layout(text, seed, variation) trace = list(trace) if buf is None and mode != "sprite": # rule: something has no 3D model -> pixelise the pixel renderer's own picture as a scene from pydraw import plot img = plot(text, seed=seed, size=192, variation=variation) a = np.array([p for row in img.pixels for p in row], float).reshape(img.height, img.width, 3) / 255.0 a = np.asarray(Image.fromarray((a * 255).astype(np.uint8)).resize((N * 3, N * 3), Image.NEAREST), float) / 255 buf = dict(rgb=a, ids=np.zeros((N * 3, N * 3), int), objs=[]) mode = "scene" trace.append("retro64: no 3D model for every object -> pixel renderer picture, pixelised") if mode == "auto": from pydraw.understanding import parse sprite = is_sprite(text, parse(text, [])) # rule: decide on what the prompt says, not the layout's default place else: sprite = mode == "sprite" if sprite: from .models import MODELS # rule: a sprite shows the prompted things that have a 3D model; a worn item without one (a chef costume) # is dropped rather than drawn as a placeholder box objs = [o for o in buf["objs"] if getattr(o, "ent", None) is not None and o.name in MODELS] or \ [o for o in buf["objs"] if getattr(o, "ent", None) is not None] or list(buf["objs"]) r = render_sprite64(objs) if r is None: sprite = False else: rgb, alpha = stylise_sprite(r, colors) trace.append("retro64: transparent 64x64 sprite of %d object(s), %d colours" % (len(objs), len(np.unique((rgb[alpha] * 255).astype(int), axis=0)))) if not sprite: from . import plot3d im = plot3d(text, seed=seed, size=192, res=512, variation=variation, exp={"preview": str(N * 3), "msteps": "140", "shsteps": "24", "ncam": "0", "paint": "0"}) b2 = im.info.get("buffers") or buf rgb = stylise_scene(b2, colors) alpha = np.ones((N, N), bool) trace.append("retro64: full-frame 64x64 scene") art = np.zeros((N, N, 4), np.uint8) art[..., :3] = (np.clip(rgb, 0, 1) * 255 + .5).astype(np.uint8) art[..., 3] = alpha * 255 bg = np.array(backdrop, float) comp = np.where(alpha[..., None], art[..., :3], bg).astype(np.uint8) im = Image.fromarray(comp).resize((size, size), Image.NEAREST) im.info["pixels"] = Image.fromarray(art, "RGBA") im.info["scene"] = scene return (im, trace) if return_trace else imapp.py+3-8
pydraw/pixelart.py+102
pydraw3d/retro64.pyDeleted-392