forked from andrew/feedmill-recounter
feat(ui): interactive zone editor over the analysis frame
This commit is contained in:
1 parent
8abc103401
commit
c34ac85643
7 files changed
+682
-6
No files matched your search
@@ -30,7 +30,10 @@ from src.model_conversion import (
|
||||
MODEL_UPLOAD_EXTENSIONS,
|
||||
conversion_status_dict,
|
||||
)
|
||||
from src.preview import extract_thumbnail, extract_sample_frames, probe_video, resize_video_to_max_height
|
||||
from src.preview import (
|
||||
extract_thumbnail, extract_sample_frames, probe_video,
|
||||
resize_video_to_max_height, extract_frame_jpeg,
|
||||
)
|
||||
from src.pipeline import ANALYSIS_SIZE
|
||||
from src.truck_roi import TruckROI
|
||||
from src.validation import ValidationError
|
||||
@@ -437,6 +440,32 @@ def download(job_id, filename):
|
||||
return send_file(send_path, as_attachment=True, download_name=os.path.basename(send_path))
|
||||
|
||||
|
||||
@app.route("/calibrate")
|
||||
def calibrate_page():
|
||||
"""Interactive zone calibration page."""
|
||||
return render_template("calibrate.html")
|
||||
|
||||
|
||||
@app.route("/api/frame")
|
||||
def api_frame():
|
||||
"""One JPEG frame of an uploaded video, resized to the analysis size."""
|
||||
safe = secure_filename(request.args.get("video", ""))
|
||||
if not safe or not safe.lower().endswith(VIDEO_EXTENSIONS):
|
||||
return jsonify({"error": "invalid filename"}), 400
|
||||
path = os.path.join(UPLOAD_DIR, safe)
|
||||
if not os.path.isfile(path):
|
||||
return jsonify({"error": "not found"}), 404
|
||||
try:
|
||||
t = float(request.args.get("t", "0"))
|
||||
except ValueError:
|
||||
return jsonify({"error": "invalid t"}), 400
|
||||
try:
|
||||
jpeg = extract_frame_jpeg(path, t, ANALYSIS_SIZE)
|
||||
except (FileNotFoundError, RuntimeError, OSError) as exc:
|
||||
return jsonify({"error": str(exc)}), 500
|
||||
return Response(jpeg, mimetype="image/jpeg")
|
||||
|
||||
|
||||
@app.route("/api/videos")
|
||||
def api_videos():
|
||||
"""List previously uploaded videos."""
|
||||
|
||||
@@ -126,6 +126,33 @@ def extract_thumbnail(
|
||||
cap.release()
|
||||
|
||||
|
||||
def extract_frame_jpeg(
|
||||
video_path: str, time_sec: float = 0.0, size: tuple[int, int] = (1280, 720)
|
||||
) -> bytes:
|
||||
"""Return one frame of the video as JPEG bytes, resized to `size`.
|
||||
|
||||
`size` is the analysis frame size (1280x720) so the calibration overlay
|
||||
maps 1:1 onto the pixels the pipeline counts on.
|
||||
"""
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
raise FileNotFoundError(f"Cannot open video: {video_path}")
|
||||
try:
|
||||
fps = cap.get(cv2.CAP_PROP_FPS)
|
||||
frame_idx = int(max(0.0, time_sec) * fps) if fps and fps > 0 else 0
|
||||
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
|
||||
ret, frame = cap.read()
|
||||
if not ret:
|
||||
raise RuntimeError(f"Could not read frame at {time_sec}s")
|
||||
frame = cv2.resize(frame, size)
|
||||
ok, buf = cv2.imencode(".jpg", frame)
|
||||
if not ok:
|
||||
raise RuntimeError("Could not encode frame as JPEG")
|
||||
return buf.tobytes()
|
||||
finally:
|
||||
cap.release()
|
||||
|
||||
|
||||
def extract_sample_frames(
|
||||
video_path: str, output_dir: str, count: int = 6
|
||||
) -> list[str]:
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
/* Interactive zone editor.
|
||||
*
|
||||
* The backdrop is a frame already resized to the 1280x720 analysis space and
|
||||
* the SVG overlay uses the same viewBox, so a page pixel maps to an analysis
|
||||
* pixel with one uniform scale (plus the letterbox offset of "xMidYMid meet").
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const ZONE_SOURCE_W = 1280;
|
||||
const ZONE_SOURCE_H = 720;
|
||||
const ZONE_LINE_MARGIN = 20; // the counter's trigger band (margin=20)
|
||||
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
|
||||
// Area key -> visibility toggle key and colour.
|
||||
const AREAS = [
|
||||
{ key: 'counting_area', vis: 'counting', color: '#2563eb' },
|
||||
{ key: 'truck_area', vis: 'truck', color: '#d97706' }
|
||||
];
|
||||
|
||||
let zonesData = null;
|
||||
let zoneEditMode = false;
|
||||
let zoneDrag = null;
|
||||
const zoneVisibility = { counting: false, truck: false, counting_line: false };
|
||||
|
||||
let currentPreset = '';
|
||||
let frameTimer = null;
|
||||
|
||||
const $ = function (id) { return document.getElementById(id); };
|
||||
|
||||
function setStatus(text) {
|
||||
$('zone-status').textContent = text;
|
||||
}
|
||||
|
||||
function sourcePoint(ev) {
|
||||
const svg = document.getElementById('zoneOverlay');
|
||||
const r = svg.getBoundingClientRect();
|
||||
const scale = Math.min(r.width / ZONE_SOURCE_W, r.height / ZONE_SOURCE_H);
|
||||
const offsetX = (r.width - ZONE_SOURCE_W * scale) / 2;
|
||||
const offsetY = (r.height - ZONE_SOURCE_H * scale) / 2;
|
||||
const x = Math.round((ev.clientX - r.left - offsetX) / scale);
|
||||
const y = Math.round((ev.clientY - r.top - offsetY) / scale);
|
||||
return {
|
||||
x: Math.max(0, Math.min(ZONE_SOURCE_W, x)),
|
||||
y: Math.max(0, Math.min(ZONE_SOURCE_H, y))
|
||||
};
|
||||
}
|
||||
|
||||
function svgEl(name, attrs) {
|
||||
const node = document.createElementNS(SVG_NS, name);
|
||||
Object.keys(attrs).forEach(function (key) {
|
||||
node.setAttribute(key, attrs[key]);
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
function areaByKey(key) {
|
||||
for (let i = 0; i < AREAS.length; i++) {
|
||||
if (AREAS[i].key === key) return AREAS[i];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function makeHandle(id, color, cx, cy, radius, onDown) {
|
||||
const node = svgEl('circle', {
|
||||
id: id, cx: cx, cy: cy, r: radius,
|
||||
fill: color, stroke: '#ffffff', 'stroke-width': '2',
|
||||
'vector-effect': 'non-scaling-stroke'
|
||||
});
|
||||
node.classList.add('zone-handle');
|
||||
node.style.display = zoneEditMode ? '' : 'none';
|
||||
node.style.pointerEvents = zoneEditMode ? 'all' : 'none';
|
||||
node.addEventListener('mousedown', onDown);
|
||||
return node;
|
||||
}
|
||||
|
||||
function renderZones() {
|
||||
const layer = $('zoneLayer');
|
||||
layer.innerHTML = '';
|
||||
syncVisibilityUI();
|
||||
if (!zonesData) return;
|
||||
|
||||
AREAS.forEach(function (area) {
|
||||
const pts = zonesData[area.key];
|
||||
if (!zoneVisibility[area.vis] || !Array.isArray(pts) || pts.length < 3) return;
|
||||
layer.appendChild(svgEl('polygon', {
|
||||
id: 'zp-' + area.vis,
|
||||
points: pts.map(function (p) { return p[0] + ',' + p[1]; }).join(' '),
|
||||
fill: area.color + '22',
|
||||
stroke: area.color,
|
||||
'stroke-width': '3',
|
||||
'vector-effect': 'non-scaling-stroke'
|
||||
}));
|
||||
pts.forEach(function (pt, i) {
|
||||
layer.appendChild(makeHandle(
|
||||
'zh-' + area.vis + '-' + i, area.color, pt[0], pt[1], 8,
|
||||
function (ev) { startZoneDrag(ev, area.key, 'poly', i); }
|
||||
));
|
||||
});
|
||||
});
|
||||
|
||||
const line = zonesData.counting_line;
|
||||
if (zoneVisibility.counting_line && Array.isArray(line) && line.length === 2) {
|
||||
const lineY = Math.round((line[0][1] + line[1][1]) / 2);
|
||||
line[0][1] = lineY;
|
||||
line[1][1] = lineY;
|
||||
const xMin = Math.min(line[0][0], line[1][0]);
|
||||
const xMax = Math.max(line[0][0], line[1][0]);
|
||||
const bandTop = Math.max(0, lineY - ZONE_LINE_MARGIN);
|
||||
const bandBottom = Math.min(ZONE_SOURCE_H, lineY + ZONE_LINE_MARGIN);
|
||||
|
||||
const band = svgEl('rect', {
|
||||
id: 'zb-counting', x: xMin, y: bandTop,
|
||||
width: Math.max(1, xMax - xMin), height: Math.max(1, bandBottom - bandTop),
|
||||
fill: 'rgba(22, 163, 74, 0.16)', stroke: '#16a34a',
|
||||
'stroke-width': '1.5', 'stroke-dasharray': '6,4',
|
||||
'vector-effect': 'non-scaling-stroke'
|
||||
});
|
||||
band.style.pointerEvents = 'none';
|
||||
layer.appendChild(band);
|
||||
|
||||
const stroke = svgEl('line', {
|
||||
id: 'zl-counting', x1: line[0][0], y1: lineY, x2: line[1][0], y2: lineY,
|
||||
stroke: '#16a34a', 'stroke-width': '4', 'vector-effect': 'non-scaling-stroke'
|
||||
});
|
||||
stroke.style.pointerEvents = 'none';
|
||||
layer.appendChild(stroke);
|
||||
|
||||
line.forEach(function (pt, i) {
|
||||
layer.appendChild(makeHandle(
|
||||
'zh-line-' + i, '#16a34a', pt[0], lineY, 9,
|
||||
function (ev) { startZoneDrag(ev, 'counting_line', 'line', i); }
|
||||
));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function startZoneDrag(ev, key, kind, index) {
|
||||
if (!zoneEditMode) return;
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
zoneDrag = { key: key, kind: kind, index: index };
|
||||
document.addEventListener('mousemove', onZoneDrag);
|
||||
document.addEventListener('mouseup', endZoneDrag);
|
||||
}
|
||||
|
||||
function onZoneDrag(ev) {
|
||||
if (!zoneDrag) return;
|
||||
const pt = sourcePoint(ev);
|
||||
const info = zoneDrag;
|
||||
if (info.kind === 'poly') {
|
||||
zonesData[info.key][info.index] = [pt.x, pt.y];
|
||||
const area = areaByKey(info.key);
|
||||
const poly = document.getElementById('zp-' + area.vis);
|
||||
if (poly) {
|
||||
poly.setAttribute('points', zonesData[info.key].map(function (p) {
|
||||
return p[0] + ',' + p[1];
|
||||
}).join(' '));
|
||||
}
|
||||
const handle = document.getElementById('zh-' + area.vis + '-' + info.index);
|
||||
if (handle) {
|
||||
handle.setAttribute('cx', pt.x);
|
||||
handle.setAttribute('cy', pt.y);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// The count line stays horizontal: the dragged endpoint sets x, and
|
||||
// both endpoints take the dragged y.
|
||||
const line = zonesData.counting_line;
|
||||
line[info.index][0] = pt.x;
|
||||
line[0][1] = pt.y;
|
||||
line[1][1] = pt.y;
|
||||
const x0 = line[0][0];
|
||||
const x1 = line[1][0];
|
||||
const bandTop = Math.max(0, pt.y - ZONE_LINE_MARGIN);
|
||||
const bandBottom = Math.min(ZONE_SOURCE_H, pt.y + ZONE_LINE_MARGIN);
|
||||
const band = document.getElementById('zb-counting');
|
||||
if (band) {
|
||||
band.setAttribute('x', Math.min(x0, x1));
|
||||
band.setAttribute('y', bandTop);
|
||||
band.setAttribute('width', Math.max(1, Math.abs(x1 - x0)));
|
||||
band.setAttribute('height', Math.max(1, bandBottom - bandTop));
|
||||
}
|
||||
const stroke = document.getElementById('zl-counting');
|
||||
if (stroke) {
|
||||
stroke.setAttribute('x1', x0);
|
||||
stroke.setAttribute('y1', pt.y);
|
||||
stroke.setAttribute('x2', x1);
|
||||
stroke.setAttribute('y2', pt.y);
|
||||
}
|
||||
['zh-line-0', 'zh-line-1'].forEach(function (id, i) {
|
||||
const handle = document.getElementById(id);
|
||||
if (!handle) return;
|
||||
handle.setAttribute('cx', i === 0 ? x0 : x1);
|
||||
handle.setAttribute('cy', pt.y);
|
||||
});
|
||||
}
|
||||
|
||||
function endZoneDrag() {
|
||||
zoneDrag = null;
|
||||
document.removeEventListener('mousemove', onZoneDrag);
|
||||
document.removeEventListener('mouseup', endZoneDrag);
|
||||
}
|
||||
|
||||
function syncVisibilityUI() {
|
||||
const buttons = {
|
||||
counting: 'zone-vis-counting',
|
||||
truck: 'zone-vis-truck',
|
||||
counting_line: 'zone-vis-line'
|
||||
};
|
||||
Object.keys(buttons).forEach(function (key) {
|
||||
const btn = $(buttons[key]);
|
||||
if (!btn) return;
|
||||
const visible = Boolean(zoneVisibility[key]);
|
||||
btn.setAttribute('aria-pressed', visible ? 'true' : 'false');
|
||||
});
|
||||
const all = Object.keys(buttons).every(function (key) { return zoneVisibility[key]; });
|
||||
const global = $('zone-vis-all-btn');
|
||||
if (global) {
|
||||
global.setAttribute('aria-pressed', all ? 'true' : 'false');
|
||||
global.textContent = all ? 'Hide All ROIs' : 'Show All ROIs';
|
||||
}
|
||||
}
|
||||
|
||||
function toggleZoneEdit() {
|
||||
zoneEditMode = !zoneEditMode;
|
||||
if (zoneEditMode && !zoneVisibility.counting && !zoneVisibility.truck
|
||||
&& !zoneVisibility.counting_line) {
|
||||
zoneVisibility.counting = true;
|
||||
zoneVisibility.truck = true;
|
||||
zoneVisibility.counting_line = true;
|
||||
}
|
||||
$('zone-edit-btn').textContent = zoneEditMode ? 'Lock Edit' : 'Unlock Edit';
|
||||
setStatus(zoneEditMode ? 'Editing: drag handles, then Save' : 'Locked');
|
||||
renderZones();
|
||||
}
|
||||
|
||||
function toggleZoneItemVisibility(key) {
|
||||
if (!(key in zoneVisibility)) return;
|
||||
zoneVisibility[key] = !zoneVisibility[key];
|
||||
renderZones();
|
||||
}
|
||||
|
||||
function toggleAllZoneVisibility() {
|
||||
const all = Object.keys(zoneVisibility).every(function (key) { return zoneVisibility[key]; });
|
||||
Object.keys(zoneVisibility).forEach(function (key) {
|
||||
zoneVisibility[key] = !all;
|
||||
});
|
||||
renderZones();
|
||||
}
|
||||
|
||||
function applyPreset(preset) {
|
||||
const line = (preset && preset.count_line) || {};
|
||||
zonesData = {
|
||||
truck_area: (preset && preset.truck_area) || [],
|
||||
counting_area: (preset && preset.counting_area) || [],
|
||||
counting_line: [
|
||||
[Number(line.x_start) || 0, Number(line.y) || 0],
|
||||
[Number(line.x_end) || 0, Number(line.y) || 0]
|
||||
]
|
||||
};
|
||||
renderZones();
|
||||
}
|
||||
|
||||
async function loadPreset(name) {
|
||||
currentPreset = name;
|
||||
try {
|
||||
const res = await fetch('/api/zones/' + encodeURIComponent(name));
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
setStatus('Load failed: ' + (data.error || res.status));
|
||||
return;
|
||||
}
|
||||
applyPreset(data.preset || {});
|
||||
setStatus(zoneEditMode ? 'Editing: drag handles, then Save' : 'Locked');
|
||||
} catch (err) {
|
||||
setStatus('Load failed');
|
||||
}
|
||||
}
|
||||
|
||||
async function saveZones() {
|
||||
if (!zonesData || !currentPreset) {
|
||||
setStatus('Nothing to save');
|
||||
return;
|
||||
}
|
||||
const xs = zonesData.counting_line.map(function (p) { return p[0]; });
|
||||
const ys = zonesData.counting_line.map(function (p) { return p[1]; });
|
||||
const payload = {
|
||||
preset: {
|
||||
truck_area: zonesData.truck_area,
|
||||
counting_area: zonesData.counting_area,
|
||||
count_line: {
|
||||
x_start: Math.min.apply(null, xs),
|
||||
x_end: Math.max.apply(null, xs),
|
||||
y: Math.round(ys.reduce(function (a, b) { return a + b; }, 0) / ys.length)
|
||||
},
|
||||
reference_resolution: [ZONE_SOURCE_W, ZONE_SOURCE_H]
|
||||
}
|
||||
};
|
||||
try {
|
||||
const res = await fetch('/api/zones/' + encodeURIComponent(currentPreset), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await res.json().catch(function () { return {}; });
|
||||
if (!res.ok) {
|
||||
setStatus('Save failed: ' + (data.error || res.status));
|
||||
return;
|
||||
}
|
||||
await loadPreset(currentPreset);
|
||||
setStatus('Saved to zones.json');
|
||||
} catch (err) {
|
||||
setStatus('Save failed');
|
||||
}
|
||||
}
|
||||
|
||||
async function resetZones() {
|
||||
if (!currentPreset) return;
|
||||
try {
|
||||
const res = await fetch('/api/zones/' + encodeURIComponent(currentPreset) + '/reset', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
const data = await res.json().catch(function () { return {}; });
|
||||
if (!res.ok) {
|
||||
setStatus('Reset failed: ' + (data.error || res.status));
|
||||
return;
|
||||
}
|
||||
applyPreset(data.preset || {});
|
||||
setStatus('Reset to the shipped default');
|
||||
} catch (err) {
|
||||
setStatus('Reset failed');
|
||||
}
|
||||
}
|
||||
|
||||
function loadFrame() {
|
||||
const video = $('video-select').value;
|
||||
if (!video) return;
|
||||
const t = parseFloat($('time-slider').value) || 0;
|
||||
$('zone-backdrop').src = '/api/frame?video=' + encodeURIComponent(video) + '&t=' + t;
|
||||
}
|
||||
|
||||
async function loadVideos() {
|
||||
const select = $('video-select');
|
||||
try {
|
||||
const res = await fetch('/api/videos');
|
||||
const videos = await res.json();
|
||||
select.innerHTML = '';
|
||||
videos.forEach(function (video) {
|
||||
const option = document.createElement('option');
|
||||
option.value = video.filename;
|
||||
option.textContent = video.filename;
|
||||
select.appendChild(option);
|
||||
});
|
||||
if (!videos.length) {
|
||||
setStatus('No videos uploaded yet');
|
||||
return;
|
||||
}
|
||||
loadFrame();
|
||||
} catch (err) {
|
||||
setStatus('Could not load the video list');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPresets() {
|
||||
const select = $('preset-select');
|
||||
try {
|
||||
const res = await fetch('/api/zones');
|
||||
const presets = await res.json();
|
||||
select.innerHTML = '';
|
||||
presets.forEach(function (preset) {
|
||||
const option = document.createElement('option');
|
||||
option.value = preset.name;
|
||||
option.textContent = preset.name;
|
||||
select.appendChild(option);
|
||||
});
|
||||
if (!presets.length) {
|
||||
setStatus('No zone presets found');
|
||||
return;
|
||||
}
|
||||
await loadPreset(presets[0].name);
|
||||
} catch (err) {
|
||||
setStatus('Could not load the zone presets');
|
||||
}
|
||||
}
|
||||
|
||||
function init() {
|
||||
$('zone-edit-btn').addEventListener('click', toggleZoneEdit);
|
||||
$('zone-save-btn').addEventListener('click', saveZones);
|
||||
$('zone-reload-btn').addEventListener('click', function () {
|
||||
if (currentPreset) loadPreset(currentPreset);
|
||||
});
|
||||
$('zone-reset-btn').addEventListener('click', resetZones);
|
||||
$('zone-vis-all-btn').addEventListener('click', toggleAllZoneVisibility);
|
||||
$('zone-vis-counting').addEventListener('click', function () {
|
||||
toggleZoneItemVisibility('counting');
|
||||
});
|
||||
$('zone-vis-truck').addEventListener('click', function () {
|
||||
toggleZoneItemVisibility('truck');
|
||||
});
|
||||
$('zone-vis-line').addEventListener('click', function () {
|
||||
toggleZoneItemVisibility('counting_line');
|
||||
});
|
||||
$('preset-select').addEventListener('change', function () {
|
||||
loadPreset(this.value);
|
||||
});
|
||||
$('video-select').addEventListener('change', loadFrame);
|
||||
$('time-slider').addEventListener('input', function () {
|
||||
$('time-label').textContent = (parseFloat(this.value) || 0).toFixed(1) + ' s';
|
||||
if (frameTimer) clearTimeout(frameTimer);
|
||||
frameTimer = setTimeout(loadFrame, 150);
|
||||
});
|
||||
|
||||
renderZones();
|
||||
loadPresets();
|
||||
loadVideos();
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
@@ -1205,3 +1205,100 @@ main {
|
||||
max-width: 1024px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Zone calibration page ---------- */
|
||||
.calibrate-heading {
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
|
||||
.calibrate-heading h2 {
|
||||
margin-bottom: var(--space-1);
|
||||
}
|
||||
|
||||
.calibrate-heading p {
|
||||
color: var(--color-neutral-500);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.calibrate-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-4);
|
||||
margin-bottom: var(--space-3);
|
||||
background: #fff;
|
||||
border: 1px solid var(--color-neutral-200);
|
||||
border-radius: var(--radius-lg);
|
||||
}
|
||||
|
||||
.calibrate-toolbar label {
|
||||
font-size: var(--text-sm);
|
||||
font-weight: var(--font-semibold);
|
||||
color: var(--color-neutral-600);
|
||||
}
|
||||
|
||||
.calibrate-toolbar select {
|
||||
max-width: 200px;
|
||||
}
|
||||
|
||||
.calibrate-toolbar input[type="range"] {
|
||||
width: 170px;
|
||||
}
|
||||
|
||||
#time-label {
|
||||
min-width: 3.5rem;
|
||||
font-size: var(--text-sm);
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--color-neutral-600);
|
||||
}
|
||||
|
||||
.calibrate-status {
|
||||
margin-left: auto;
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-neutral-600);
|
||||
}
|
||||
|
||||
#zone-legend {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
margin-bottom: var(--space-3);
|
||||
}
|
||||
|
||||
#zone-legend .btn[aria-pressed="true"],
|
||||
#zone-vis-all-btn[aria-pressed="true"] {
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
|
||||
.calibrate-stage {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 16 / 9;
|
||||
overflow: hidden;
|
||||
background: var(--color-neutral-900);
|
||||
border: 1px solid var(--color-neutral-200);
|
||||
border-radius: var(--radius-lg);
|
||||
}
|
||||
|
||||
#zone-backdrop {
|
||||
position: relative;
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
#zoneOverlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
#zoneOverlay .zone-handle {
|
||||
cursor: grab;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Calibrate Zones - Feedmill Recounter{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="calibrate-heading">
|
||||
<h2>Zone Calibration</h2>
|
||||
<p>Drag the counting area, truck area and count line over a frame of an uploaded video, then save.
|
||||
Every coordinate is in the 1280×720 analysis space.</p>
|
||||
</div>
|
||||
|
||||
<div class="calibrate-toolbar">
|
||||
<label for="preset-select">Preset</label>
|
||||
<select id="preset-select" class="form-select"></select>
|
||||
|
||||
<label for="video-select">Video</label>
|
||||
<select id="video-select" class="form-select"></select>
|
||||
|
||||
<label for="time-slider">Time (s)</label>
|
||||
<input type="range" id="time-slider" min="0" max="60" step="0.5" value="0">
|
||||
<span id="time-label">0.0 s</span>
|
||||
|
||||
<button id="zone-edit-btn" type="button" class="btn btn-secondary btn-sm">Unlock Edit</button>
|
||||
<button id="zone-save-btn" type="button" class="btn btn-primary btn-sm">Save Zones</button>
|
||||
<button id="zone-reload-btn" type="button" class="btn btn-secondary btn-sm">Reload Zones</button>
|
||||
<button id="zone-reset-btn" type="button" class="btn btn-secondary btn-sm">Reset Zones</button>
|
||||
<button id="zone-vis-all-btn" type="button" class="btn btn-ghost btn-sm" aria-pressed="false">Show All ROIs</button>
|
||||
|
||||
<span id="zone-status" role="status" class="calibrate-status">Locked</span>
|
||||
</div>
|
||||
|
||||
<div id="zone-legend" role="group" aria-label="ROI visibility">
|
||||
<button type="button" id="zone-vis-counting" class="btn btn-secondary btn-sm" aria-pressed="false">Counting ROI</button>
|
||||
<button type="button" id="zone-vis-truck" class="btn btn-secondary btn-sm" aria-pressed="false">Truck ROI</button>
|
||||
<button type="button" id="zone-vis-line" class="btn btn-secondary btn-sm" aria-pressed="false">Count line</button>
|
||||
</div>
|
||||
|
||||
<div class="calibrate-stage">
|
||||
<img id="zone-backdrop" alt="Video frame under the zone overlay">
|
||||
<svg id="zoneOverlay" viewBox="0 0 1280 720" preserveAspectRatio="xMidYMid meet">
|
||||
<g id="zoneLayer"></g>
|
||||
</svg>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{{ url_for('static', filename='calibrate.js') }}"></script>
|
||||
{% endblock %}
|
||||
@@ -940,3 +940,39 @@ def test_post_zones_keeps_the_zones_file_mode(client, tmp_path, monkeypatch):
|
||||
resp = client.post("/api/zones/default", json={"preset": _route_preset()})
|
||||
assert resp.status_code == 200
|
||||
assert os.stat(zones).st_mode & 0o777 == 0o644
|
||||
|
||||
|
||||
# --- Interactive zone editor (Task 5) ---
|
||||
|
||||
|
||||
def test_calibrate_page_renders(client):
|
||||
resp = client.get("/calibrate")
|
||||
assert resp.status_code == 200
|
||||
assert b"zoneOverlay" in resp.data
|
||||
|
||||
|
||||
def test_api_frame_rejects_a_bad_filename(client, tmp_path, monkeypatch):
|
||||
import app as app_module
|
||||
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path))
|
||||
assert client.get("/api/frame?video=../etc/passwd").status_code == 400
|
||||
assert client.get("/api/frame?video=missing.mp4").status_code == 404
|
||||
|
||||
|
||||
def test_api_frame_returns_a_1280x720_jpeg(client, tmp_path, monkeypatch):
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
import app as app_module
|
||||
|
||||
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path))
|
||||
path = tmp_path / "clip.mp4"
|
||||
writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), 10, (1920, 1080))
|
||||
for _ in range(5):
|
||||
writer.write(np.zeros((1080, 1920, 3), dtype=np.uint8))
|
||||
writer.release()
|
||||
|
||||
resp = client.get("/api/frame?video=clip.mp4&t=0")
|
||||
assert resp.status_code == 200
|
||||
assert resp.mimetype == "image/jpeg"
|
||||
img = cv2.imdecode(np.frombuffer(resp.data, dtype=np.uint8), cv2.IMREAD_COLOR)
|
||||
assert img.shape[:2] == (720, 1280)
|
||||
+18
-5
@@ -7,6 +7,8 @@ Keys: s=save, c=clear/restart, q/ESC=quit.
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import cv2
|
||||
import numpy as np
|
||||
@@ -25,8 +27,13 @@ def load_zones(path: str) -> dict:
|
||||
|
||||
|
||||
def save_zones(config: dict, path: str):
|
||||
with open(path, "w") as f:
|
||||
if os.path.exists(path):
|
||||
shutil.copy2(path, path + ".bak")
|
||||
tmp = path + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(config, f, indent=2)
|
||||
f.write("\n")
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def draw_state(frame, points, current_zone, zone_idx, zone_sizes, zone_names):
|
||||
@@ -98,6 +105,10 @@ def run(video_path: str, preset_name: str, zones_path: str):
|
||||
h, w = frame.shape[:2]
|
||||
print(f"Video: {w}x{h}")
|
||||
|
||||
# The analysis space is 1280x720: resize before the clicks are taken, so
|
||||
# the mouse coordinates match the space zones.json is authored in.
|
||||
frame = cv2.resize(frame, (1280, 720))
|
||||
|
||||
points = []
|
||||
all_sizes = list(ZONE_SIZES) + [LINE_POINTS]
|
||||
all_names = list(ZONE_KEYS) + ["count_line"]
|
||||
@@ -147,10 +158,12 @@ def run(video_path: str, preset_name: str, zones_path: str):
|
||||
preset[ZONE_KEYS[i]] = [list(p) for p in points[offset : offset + sz]]
|
||||
offset += sz
|
||||
|
||||
x_start = points[offset][0]
|
||||
x_end = points[offset + 1][0]
|
||||
line_y = min(points[offset][1], points[offset + 1][1])
|
||||
preset["count_line"] = {"x_start": x_start, "x_end": x_end, "y": line_y}
|
||||
# FCP count-line semantics: the line stays horizontal at the
|
||||
# mean y of its two endpoints, and the x endpoints are sorted.
|
||||
xs = sorted([points[offset][0], points[offset + 1][0]])
|
||||
line_y = round((points[offset][1] + points[offset + 1][1]) / 2)
|
||||
preset["count_line"] = {"x_start": xs[0], "x_end": xs[1], "y": line_y}
|
||||
preset["reference_resolution"] = [1280, 720]
|
||||
|
||||
config = load_zones(zones_path)
|
||||
config.setdefault("presets", {})[preset_name] = preset
|
||||
|
||||
Reference in new issue
Block a user