"""依頼270:make237.py を写して変えた。 (1) closeup270_<名前>.mp4:frames/<場面>/f_*.png(台本の video_from から終わりまで)に台本の秒の音(mix270_<場面>.wav)を重ねる。早回しは無し。 ⑩-2 はストレッチャーが動き出した時から 3 秒、左下に「ストレッチャーを待たせた ○秒」(止まってから動き出すまで。台本 c270.wait_label) (2) closeup270_<名前>_top.mp4:frames/<場面>_top に 236 の描き方で床の目印・通った跡・印・左上の字を重ねる。 目印:くぼみの輪郭(実線)・ハコブくんのふだんの線 x −0.33(点線)。床の目印は、ものごとに穴を埋めた外形(閉じる処理 半径 6 画素 → 中の穴埋め)の中には描かない。 もの:ハコブくん(赤)と、ストレッチャー・大城さん・寺島さん(緑)。大城さんと寺島さんは手をストレッチャーにのせたままなので、3 つを 1 つのものとして埋める(236 の「手を握りにのせている間は 1 つ」と同じ考え) 重ねる順:コマ → 床の目印(外形の所は消す)→ 通った跡 → 印 → 左上の字(動画の秒・ハコブくんとストレッチャー(人を含む)のすき間) 使い方: python3 make270.py <台本> <場面> <音の wav> <動画を置くフォルダ> <動画の名前>""" import csv, json, math, os, subprocess, sys, tempfile, wave import numpy as np, cv2 from scipy import ndimage from PIL import Image, ImageChops, ImageDraw, ImageFont FF = "/opt/homebrew/Caskroom/miniforge/base/envs/ros_env/bin/ffmpeg" D, SC, SHOT, WAV, VD, NAME = sys.argv[1:7] os.makedirs(os.path.join(VD, "stills"), exist_ok=True) SJ = json.load(open(SC)); shot = [s for s in SJ["shots"] if s["name"] == SHOT][0]; C = shot["c270"] FPS, W, H, S = 30, 1920, 1080, 2 f0 = int(round(C["video_from"] * FPS)); f1 = int(round(C["video_to"] * FPS)) seq = list(range(f0, f1 + 1)) FONT_PATH = "/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc" def font(px, s=1): return ImageFont.truetype(FONT_PATH, px * s) lab = C.get("wait_label") vmap = {f: (f - f0) / FPS for f in seq} # ---------------------------------------------------------------- (1) 本番の動画(TOP_ONLY=1 なら作らない=真上だけ作り直す時) TOP_ONLY = os.environ.get("TOP_ONLY") == "1" tmp = tempfile.mkdtemp(prefix="m270_", dir="/tmp") FB = font(40) info = {"frames": len(seq), "label": None} for k, f in enumerate([] if TOP_ONLY else seq): src = os.path.join(D, "frames", SHOT, f"f_{f:05d}.png"); assert os.path.exists(src), src t = f / FPS on = lab is not None and lab[0] - 1e-4 <= t < lab[1] - 1e-4 if not on: os.symlink(os.path.abspath(src), os.path.join(tmp, f"v_{k:05d}.png")); continue im = Image.open(src).convert("RGB"); d = ImageDraw.Draw(im) if info["label"] is None: info["label"] = vmap[f] s = f"ストレッチャーを待たせた {lab[2]:.1f}秒" bb = d.textbbox((0, 0), s, font=FB); w = bb[2] - bb[0] d.rounded_rectangle([24, H - 24 - 80, 24 + w + 50, H - 24], radius=12, fill=(242, 194, 48)) d.text((49, H - 24 - 40), s, font=FB, fill=(25, 25, 25), anchor="lm") im.save(os.path.join(tmp, f"v_{k:05d}.png")) if abs(t - (lab[0] + 1.0)) < 0.5 / FPS: im.save(os.path.join(VD, "stills", f"{SHOT}_s06_wait_label.png")) # 「ストレッチャーを待たせた」の字の所(動画のコマ) if not TOP_ONLY: wr = wave.open(WAV); SR = wr.getframerate(); x = np.frombuffer(wr.readframes(wr.getnframes()), np.int16) a0 = int(round(f0 / FPS * SR)); a1 = int(round((f1 + 1) / FPS * SR)) aud = x[a0:a1]; aud = np.pad(aud, (0, max(0, a1 - a0 - len(aud)))) aw = os.path.join(tmp, "a.wav"); w2 = wave.open(aw, "w"); w2.setnchannels(1); w2.setsampwidth(2); w2.setframerate(SR); w2.writeframes(aud.astype(np.int16).tobytes()); w2.close() vid = os.path.join(VD, f"{NAME}.mp4") subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp, "v_%05d.png"), "-i", aw, "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2", "-shortest", vid], check=True) json.dump({"seq_first": seq[0], "seq_last": seq[-1], "n": len(seq), "video_s": len(seq) / FPS, "video_from": C["video_from"], "label_video_s": info["label"], "label": lab}, open(os.path.join(D, f"vmap270_{SHOT}.json"), "w"), ensure_ascii=False) print("動画", vid, len(seq), "コマ", len(seq) / FPS, "秒・待たせた字", info["label"]) # ---------------------------------------------------------------- (2) 真上の動画 CAM = json.load(open(os.path.join(D, "top270_cam.json"))) HUD_PX, LINE_LABEL_PX, MARK_LABEL_PX = 60, 34, 36 COL = {"alcove": (142, 36, 170), "lane": (46, 173, 107), "st": (239, 108, 0), "robot": (0, 105, 92)} LW = {"alcove": 5, "dash": 5, "trail": 10, "mark_r": 13, "mark_edge": 3, "leader": 3} DASH, GAP = 28, 16 ox, oy = CAM["px_origin"]; xx, xy = CAM["px_per_x"]; zx, zy = CAM["px_per_z"] def to_px(x, z): return (ox + xx * x + zx * z, oy + xy * x + zy * z) def from_px(px, py): det = xx * zy - zx * xy; dx, dy = px - ox, py - oy return ((dx * zy - zx * dy) / det, (xx * dy - dx * xy) / det) rows = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "frames270.csv")))} top = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "top270.csv")))} EV = C["events"]; A = C["alcove"] back = SHOT == "stretcher_back" MARKS = [("robot", EV["detect"], "見つけた")] if back: MARKS += [("robot", EV["stop"], "止まった"), ("robot", EV["back0"], "下がり始め"), ("robot", EV["in_stop"], "くぼみで止まった"), ("st", C["stretcher_stop"][0], "止まった"), ("st", C["stretcher_stop"][1], "動き出した")] else: MARKS += [("robot", EV["in_stop"], "くぼみで止まった")] MARKS += [("robot", EV["exit"], "出た")] mark_f = [int(round(t * FPS)) for _, t, _ in MARKS] FL, FM, FH = font(LINE_LABEL_PX, S), font(MARK_LABEL_PX, S), font(HUD_PX, S) def sc(p): return (p[0] * S, p[1] * S) def text_box(d, xy, s, f, fg, anchor, pad=8, bg=(255, 255, 255, 235), edge=None): x, y = xy; bb = d.textbbox((x, y), s, font=f, anchor=anchor) d.rounded_rectangle([bb[0] - pad * S, bb[1] - pad * S, bb[2] + pad * S, bb[3] + pad * S], radius=6 * S, fill=bg, outline=edge, width=2 * S if edge else 0) d.text((x, y), s, font=f, fill=fg, anchor=anchor) def dashed(d, p0, p1, col, w): (x0, y0), (x1, y1) = sc(p0), sc(p1); L = math.hypot(x1 - x0, y1 - y0); ux, uy = (x1 - x0) / L, (y1 - y0) / L; s = 0.0 while s < L: e = min(L, s + DASH * S); d.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * e, y0 + uy * e)], fill=col, width=w * S); s += (DASH + GAP) * S def down(layer): return layer.resize((W, H), Image.LANCZOS) z_lo, z_hi = from_px(0, 0)[1], from_px(W, 0)[1] st = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(st) poly = [to_px(-0.90, A["z0"]), to_px(A["x_back"], A["z0"]), to_px(A["x_back"], A["z1"]), to_px(-0.90, A["z1"])] d.line([sc(p) for p in poly], fill=COL["alcove"] + (255,), width=LW["alcove"] * S, joint="curve") dashed(d, to_px(-0.90, A["z0"]), to_px(-0.90, A["z1"]), COL["alcove"] + (255,), 3) dashed(d, to_px(-0.33, z_lo), to_px(-0.33, z_hi), COL["lane"] + (255,), LW["dash"]) cx_al = to_px(A["x_back"], (A["z0"] + A["z1"]) / 2) text_box(d, sc((cx_al[0], cx_al[1] - 14)), f"くぼみ(奥行 {A['depth_m']:.2f} m・長さ {A['length_m']:.2f} m)", FL, COL["alcove"], "mb", edge=COL["alcove"]) lp = to_px(-0.33, z_hi) text_box(d, sc((W - 14, lp[1] + 10)), "ハコブくんのふだん −0.33", FL, COL["lane"], "rt", edge=COL["lane"]) static = down(st); static_A = static.getchannel("A") rail_lo_py = to_px(0.875, 0)[1]; rail_hi_py = to_px(A["x_back"] - 0.15, 0)[1] def mark_layer(shown): L = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(L) nr = 0; ns = 0 for i, (who, t, head) in enumerate(MARKS): if not shown[i]: continue r = top[mark_f[i]] px, py = (float(r["st_px"]), float(r["st_py"])) if who == "st" else (float(r["robot_px"]), float(r["robot_py"])) if who == "st": ly = rail_lo_py + 40 + 70 * (ns % 2); anchor = "mt"; ns += 1 else: ly = rail_hi_py - 30 - 62 * (nr % 3); anchor = "mb"; nr += 1 ly = max(ly, 215) # 左上の字(〜190 画素)の下に d.line([sc((px, py)), sc((px, ly))], fill=COL[who] + (255,), width=LW["leader"] * S) R = LW["mark_r"] * S; e = LW["mark_edge"] * S d.ellipse([px * S - R - e, py * S - R - e, px * S + R + e, py * S + R + e], fill=(255, 255, 255, 255)) d.ellipse([px * S - R, py * S - R, px * S + R, py * S + R], fill=COL[who] + (255,)) tv = vmap.get(mark_f[i], 0.0) lab_s = f"{head} {tv:.1f}秒"; bw = d.textbbox((0, 0), lab_s, font=FM)[2] / S lx = min(max(px, bw / 2 + 20), W - bw / 2 - 20) # 字が画面の外へ出ないように(引き出し線は印の所のまま) text_box(d, sc((lx, ly)), lab_s, FM, COL[who], anchor, edge=COL[who]) return down(L) def num_ok(s): try: v = float(s) except ValueError: return None return v if math.isfinite(v) and abs(v) < 1e6 else None def hud_lines(f): g = num_ok(rows[f]["gap_m"]) return [f"{vmap[f]:.1f} 秒", "ハコブくんとストレッチャー(人を含む)のすき間 " + (f"{g:.2f} m" if g is not None and g < 1.5 else "1.5 m より遠い")] RC = 6 KER = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * RC + 1, 2 * RC + 1)); PAD = RC + 24 def fill_obj(soft): ys, xs = np.nonzero(soft); added = np.zeros(soft.shape, bool) if len(xs) == 0: return added y0, y1 = max(0, ys.min() - PAD), min(H, ys.max() + PAD + 1); x0, x1 = max(0, xs.min() - PAD), min(W, xs.max() + PAD + 1) b = (soft[y0:y1, x0:x1] > 0).astype(np.uint8) bp = cv2.copyMakeBorder(b, PAD, PAD, PAD, PAD, cv2.BORDER_CONSTANT, value=0) cl = cv2.morphologyEx(bp, cv2.MORPH_CLOSE, KER, borderType=cv2.BORDER_CONSTANT, borderValue=0)[PAD:-PAD, PAD:-PAD].astype(bool) filled = ndimage.binary_fill_holes(cl | b.astype(bool)) added[y0:y1, x0:x1] = filled & ~b.astype(bool) return added tmpT = tempfile.mkdtemp(prefix="m270t_", dir="/tmp") trail = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); td = ImageDraw.Draw(trail) prev = {"st": None, "robot": None}; shown = [False] * len(MARKS); mcache = mark_layer(shown) per = []; top_stills = {} want = {int(round(s[0] * FPS)): s[2] for s in shot["stills"] if s[1] == "top"} k = 0 seqset = set(seq) for f in range(0, f1 + 1): r = top[f] for who, kx, ky in (("st", "st_px", "st_py"), ("robot", "robot_px", "robot_py")): p = (round(float(r[kx]) * S) / S, round(float(r[ky]) * S) / S) if prev[who] is not None: td.line([sc(prev[who]), sc(p)], fill=COL[who] + (255,), width=LW["trail"] * S) R = LW["trail"] * S / 2; td.ellipse([p[0] * S - R, p[1] * S - R, p[0] * S + R, p[1] * S + R], fill=COL[who] + (255,)) prev[who] = p if f not in seqset: continue changed = False for i in range(len(MARKS)): if not shown[i] and f >= mark_f[i]: shown[i] = True; changed = True if changed: mcache = mark_layer(shown) raw = Image.open(os.path.join(D, "frames", SHOT + "_top", f"f_{f:05d}.png")).convert("RGBA") mkn = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_mask", f"f_{f:05d}.png")).convert("L")) ob = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_obj", f"f_{f:05d}.png")).convert("RGBA")) groups = [ob[:, :, 0], ob[:, :, 1]] # 赤=ハコブくん・緑=ストレッチャーと 2 人(Closeup270.cs が 1 つの型に写す) add_any = np.zeros((H, W), bool) for g in groups: add_any |= fill_obj(g) Fn = np.maximum(mkn, np.where(add_any, 255, 0).astype(np.uint8)) st_m = static.copy(); st_m.putalpha(ImageChops.multiply(static_A, ImageChops.invert(Image.fromarray(Fn, "L")))) lines = hud_lines(f) hl = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); hd = ImageDraw.Draw(hl); x0, y0, lh = 30, 22, 78 wmax = max(hd.textbbox((0, 0), s, font=FH)[2] for s in lines) / S hd.rounded_rectangle([x0 * S - 8 * S, y0 * S - 6 * S, (x0 + wmax + 28) * S, (y0 + lh * 2 + 6) * S], radius=10 * S, fill=(255, 255, 255, 235)) for i, s in enumerate(lines): hd.text(((x0 + 10) * S, (y0 + i * lh) * S), s, font=FH, fill=(25, 25, 25)) im = raw.copy(); im.alpha_composite(st_m); im.alpha_composite(down(trail)); im.alpha_composite(mcache); im.alpha_composite(down(hl)) o = im.convert("RGB"); o.save(os.path.join(tmpT, f"v_{k:05d}.png")); k += 1 stA = np.array(st_m.getchannel("A")) per.append((f, int(((stA > 0) & (Fn == 255)).sum()), int(add_any.sum()))) if f in want: top_stills[want[f]] = o vidT = os.path.join(VD, f"{NAME}_top.mp4") subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmpT, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", vidT], check=True) sd = os.path.join(VD, "stills"); os.makedirs(sd, exist_ok=True) for nm, im in top_stills.items(): im.save(os.path.join(sd, f"{SHOT}_{nm}.png")) open(os.path.join(D, f"per270_{SHOT}.csv"), "w").write("frame,line_left_inside,added\n" + "".join(",".join(map(str, p)) + "\n" for p in per)) print("真上", vidT, k, "コマ・外形の中に残る目印の画素 合計", sum(p[1] for p in per))