import cv2 import numpy as np from PIL import Image, ImageDraw MAGENTA = (255, 0, 255) def stroke_width_for(img): short = min(img.size) return max(3, min(7, int(round(np.random.default_rng().uniform(0.004, 0.010) * short)))) def _contours(mask): m = (mask.astype(np.uint8) * 255) if mask.dtype == bool else mask cs, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) return cs def _smooth(poly, rng, amp): # Low-frequency wobble along a polyline. if len(poly) < 4: return poly p = poly.astype(np.float64) n = len(p) k = max(2, n // 12) phase = rng.uniform(0, 2 * np.pi) t = np.arange(n) tang = np.gradient(p, axis=0) nrm = tang / (np.linalg.norm(tang, axis=1, keepdims=True) + 1e-6) nrm = np.stack([-nrm[:, 1], nrm[:, 0]], axis=1) off = (amp * np.sin(2 * np.pi * t / k + phase))[:, None] * nrm return (p + off).astype(np.int32) def outline_polyline(mask, rng): cs = _contours(mask) if not cs: return None c = max(cs, key=cv2.contourArea) if len(c) < 8: return None eps = rng.uniform(0.002, 0.006) * cv2.arcLength(c, True) poly = cv2.approxPolyDP(c, eps, True).reshape(-1, 2) short = min(mask.shape[:2]) poly = _smooth(poly, rng, amp=rng.uniform(0.005, 0.02) * short) segs = [np.stack([poly[i], poly[i + 1]]) for i in range(len(poly) - 1)] if len(segs) > 2 and rng.random() < 0.5: for _ in range(rng.integers(0, 3)): i = int(rng.integers(0, len(segs))) segs.pop(i) if len(segs) < 2: break for seg in segs: d = seg[-1] - seg[0] L = max(float(np.hypot(d[0], d[1])), 1e-6) u = d / L e = rng.uniform(0.0, 0.015) * short if rng.random() < 0.4: seg[0] = (seg[0] - u * e).astype(seg.dtype) if rng.random() < 0.4: seg[-1] = (seg[-1] + u * e).astype(seg.dtype) return segs def interior_strokes(mask, gray, rng, max_strokes=4): H, W = mask.shape[:2] short = min(H, W) k = max(3, int(0.03 * short) | 1) er = cv2.erode(mask.astype(np.uint8) * 255, np.ones((k, k), np.uint8)) edges = cv2.Canny(cv2.GaussianBlur(gray, (3, 3), 0), 40, 120) edges[er == 0] = 0 n, lbl = cv2.connectedComponents((edges > 0).astype(np.uint8), connectivity=8) comps = [np.stack(np.where(lbl == i), axis=1) for i in range(1, n)] comps = [c for c in comps if len(c) >= 8] comps.sort(key=len, reverse=True) strokes = [] for c in comps[: int(rng.integers(1, max_strokes + 1))]: pts = c[np.linspace(0, len(c) - 1, min(len(c), 40)).astype(int)] pts = _smooth(pts.astype(np.int32), rng, amp=rng.uniform(0.004, 0.012) * short) strokes.append(pts) return strokes def blob_polyline(mask, rng): cs = _contours(mask) if not cs: return None pts = np.vstack([c.reshape(-1, 2) for c in cs]).astype(np.float64) hull = cv2.convexHull(pts.astype(np.int32)).reshape(-1, 2) cx, cy = pts.mean(axis=0) if len(hull) < 6: return None ang = np.arctan2(hull[:, 1] - cy, hull[:, 0] - cx) rad = np.hypot(hull[:, 1] - cy, hull[:, 0] - cx) o = np.argsort(ang) ang, rad = ang[o], rad[o] ang_s = np.linspace(-np.pi, np.pi, 28)[:-1] ang_ext = np.concatenate([ang, ang[:1] + 2 * np.pi]) rad_s = np.interp(ang_s, ang_ext, np.concatenate([rad, rad[:1]])) short = min(mask.shape[:2]) rad_s = rad_s * rng.uniform(0.92, 1.06) + rng.normal(0, 0.008 * short, rad_s.shape) return [np.stack([cx + rad_s * np.cos(ang_s), cy + rad_s * np.sin(ang_s)], axis=1).astype(np.int32)] def make_scribble(mask, gray, style, rng): if style == 'outline': pl = outline_polyline(mask, rng) return ([pl] if pl else []) or (blob_polyline(mask, rng) or []) if style == 'detailed': pl = outline_polyline(mask, rng) ins = interior_strokes(mask, gray, rng) return ([pl] if pl else []) + ins if style == 'blob': return blob_polyline(mask, rng) or outline_polyline(mask, rng) or [] raise ValueError(style) def draw_scribble(image, polylines, width, color=MAGENTA): d = ImageDraw.Draw(image) for pl in polylines: if isinstance(pl, np.ndarray): pl = [pl] # single closed chain, e.g. blob for chain in pl: pts = [tuple(int(v) for v in p) for p in chain.reshape(-1, 2)] if len(pts) >= 2: d.line(pts, fill=color, width=width, joint='curve') r = width / 2.0 for p in (pts[0], pts[-1]): d.ellipse([p[0] - r, p[1] - r, p[0] + r, p[1] + r], fill=color) return image