stairscutter / cut_spines.py
amih's picture
StairsCutter + the fitter, from Seferehov
ae350f1 verified
Raw History Blame Contribute Delete
1.74 kB
"""Cut every book spine out of a shelf photo with StairsCutter and the fitter, the way Seferehov does.
pip install -r requirements.txt
python cut_spines.py examples/shelf.jpg out/
Writes out/spine-NN.jpg (each spine cut straight along its own rectangle, its length vertical),
out/outlines.jpg (the photo with every cut drawn) and out/spines.json (corners as fractions of the
photo, confidence, size). The rules around the model (duplicates, spines cut off by the photo's edge,
the fitter) are the app's own, in spine_server.py and fitter_app.py.
"""
import base64, json, os, sys
HERE = os.path.dirname(os.path.abspath(__file__))
os.environ.setdefault("SPINES_WEIGHTS", os.path.join(HERE, "stairscutter.pt"))
os.environ.setdefault("SPINES_FITTER_WEIGHTS", os.path.join(HERE, "fitter.pt"))
import cv2, numpy as np
import spine_server
src, out = sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "out"
os.makedirs(out, exist_ok=True)
data = open(src, "rb").read()
res = spine_server.cut_spines(data)
img = cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_COLOR)
H, W = img.shape[:2]
for k, s in enumerate(res["spines"]):
open(os.path.join(out, f"spine-{k:02d}.jpg"), "wb").write(base64.b64decode(s["jpeg"]))
pts = np.array([[x * W, y * H] for x, y in s["poly"]], np.int32)
cv2.polylines(img, [pts], True, (0, 200, 255), max(2, W // 400))
cv2.imwrite(os.path.join(out, "outlines.jpg"), img)
json.dump({k: v for k, v in res.items() if k != "spines"} | {"spines": [{k: v for k, v in s.items() if k != "jpeg"} for s in res["spines"]]},
open(os.path.join(out, "spines.json"), "w"), indent=1)
print(f"{len(res['spines'])} spines in {res['ms']} ms ({res.get('fitted', 0)} refitted by the fitter) -> {out}/")