ViViD-5k / scripts /make_plots.py
XZhi's picture
Apply final-review fixes to dataset card
3524642
Raw
History Blame Contribute Delete
4.51 kB
"""Render dataset-card statistics figures into assets/."""
import sys
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from tqdm import tqdm
sys.path.insert(0, str(Path(__file__).resolve().parent))
from vivid_utils import STYLE, apply_style
ROOT = Path(__file__).resolve().parents[1]
ASSETS = ROOT / "assets"
S = STYLE
def new_fig():
fig, ax = plt.subplots(figsize=S["figsize"], dpi=S["dpi"], facecolor="white")
ax.set_facecolor("white")
apply_style(ax)
return fig, ax
def save(fig, name):
fig.tight_layout()
fig.savefig(ASSETS / name, dpi=S["dpi"], facecolor="white", bbox_inches="tight")
plt.close(fig)
print("wrote", ASSETS / name)
def plot_hist(series, xlabel, title, name, callout=None):
fig, ax = new_fig()
ax.hist(series, bins=50, color=S["accent"], edgecolor="white", linewidth=0.4)
mean, med = series.mean(), series.median()
ax.axvline(mean, color=S["text"], linewidth=1.2, linestyle="--")
ax.axvline(med, color=S["secondary"], linewidth=1.2, linestyle=":")
ax.text(0.98, 0.95, f"mean {mean:.0f} · median {med:.0f}",
transform=ax.transAxes, ha="right", va="top", fontsize=10, color=S["text"])
if callout:
ax.text(0.98, 0.86, callout, transform=ax.transAxes, ha="right", va="top",
fontsize=11, fontweight="bold", color=S["accent"])
ax.text(0.98, 0.78, "x-axis clipped at 99th percentile", transform=ax.transAxes,
ha="right", va="top", fontsize=8, color=S["secondary"])
ax.set_xlabel(xlabel)
ax.set_ylabel("images")
ax.set_title(title, fontsize=12, loc="left")
ax.set_xlim(0, series.quantile(0.99))
save(fig, name)
def main():
ASSETS.mkdir(exist_ok=True)
meta = pd.read_csv(ROOT / "data" / "metadata.csv")
clusters = pd.read_csv(ROOT / "scripts" / "cache" / "clusters.csv")
total_berries = meta.berry_count.sum()
plot_hist(meta.berry_count, "berry keypoints per image",
"Berries per image", "berries_per_image.png",
callout=f"{total_berries:,} berries total")
fig, ax = new_fig()
counts = meta.cluster_count.value_counts().sort_index()
ax.bar(counts.index, counts.values, color=S["accent"], edgecolor="white", linewidth=0.4)
ax.set_xlabel("grape clusters per image")
ax.set_ylabel("images")
ax.set_title(f"Clusters per image · {meta.cluster_count.sum():,} total",
fontsize=12, loc="left")
save(fig, "clusters_per_image.png")
fig, ax = new_fig()
ax.scatter(meta.cluster_count, meta.berry_count, s=8, alpha=0.25,
color=S["accent"], edgecolors="none")
ax.set_xlabel("clusters per image")
ax.set_ylabel("berries per image")
ax.set_title("Berries vs clusters per image", fontsize=12, loc="left")
save(fig, "berries_vs_clusters.png")
fig, ax = new_fig()
ax.hist(clusters.rel_area * 100, bins=60, color=S["accent"],
edgecolor="white", linewidth=0.4)
ax.set_xlabel("cluster bbox area (% of image area)")
ax.set_ylabel("cluster instances")
ax.set_title("Cluster size distribution", fontsize=12, loc="left")
save(fig, "cluster_size_distribution.png")
dims = meta.set_index("file_name")[["width", "height"]]
xs, ys = [], []
for p in tqdm(sorted((ROOT / "data" / "anns" / "points").glob("*.npy")), desc="points"):
pts = np.load(p)
if len(pts) == 0:
continue
matches = meta[meta.file_name.str.startswith(p.stem + ".")]
if len(matches) != 1:
sys.exit(f"ABORT: {len(matches)} metadata rows match points file {p.name}")
w, h = dims.loc[matches.iloc[0].file_name]
# points are stored as (x, y) pixel coordinates
xs.append(pts[:, 0] / w)
ys.append(pts[:, 1] / h)
xs, ys = np.concatenate(xs), np.concatenate(ys)
assert xs.max() <= 1.05 and ys.max() <= 1.05
fig, ax = plt.subplots(figsize=(6, 6), dpi=S["dpi"], facecolor="white")
hb = ax.hist2d(xs, ys, bins=100, cmap="magma")
ax.invert_yaxis()
ax.set_xlabel("normalized x", color=S["text"])
ax.set_ylabel("normalized y", color=S["text"])
ax.set_title(f"Spatial density of {len(xs):,} berry centroids",
fontsize=12, loc="left", color=S["text"])
ax.tick_params(colors=S["text"], labelsize=9)
fig.colorbar(hb[3], ax=ax, shrink=0.85)
save(fig, "spatial_density.png")
if __name__ == "__main__":
main()