Upload 4 files
Browse filesFiles changed (4)
- README.md+22-59
- app.py
- gt_canvas.jsAdded+752
- requirements.txt+4-17
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172---title: CellposeCellCounter_v5emoji: 🔬colorFrom: bluecolorTo: indigosdk: gradiosdk_version: 5.35.0app_file: app.pypinned: false---# CellposeCellCounterCell counting and viability from a phone photograph of a hemocytometer, using afine-tuned Cellpose-SAM model for segmentation and a single interpretable contrastthreshold for viability.## How to use it1. Photograph one 4×4 counting block through the phone adaptor.2. Upload it and **tap once in the centre of the block**. The app detects the fourcorners and crops to it. This step is not optional — an uncropped frame covers farmore than one block and the concentration would be wrong.3. Run segmentation. Live/dead and concentration are reported together.## SegmentationCellpose-SAM fine-tuned on 13 hand-corrected images (1,069 annotated cells) from thisimaging setup. Held-out performance on 6 further images (556 annotated cells, IoU 0.5):| model | count error | precision | recall | F1 ||---|---|---|---|---|| **this model** | **−1.1%** | **0.940** | 0.926 | **0.933** || previous fine-tune | +40.6% | 0.656 | 0.932 | 0.768 || Cellpose-SAM, off the shelf | −63.7% | 0.741 | 0.238 | 0.319 |The dominant error of the previous model was over-segmentation of debris: correctingits output required 336 deletions against 79 additions.## ViabilityEach cell's mean grey level is divided by the median grey of a background annulusaround it (20 px wide, 2 px gap, neighbouring cells excluded). Cells scoring below**1.0** — no brighter than the medium surrounding them — are called dead.The threshold is not fitted: 1.0 means the cell has lost all refractile contrastagainst its own local background. It was chosen from that reasoning and then testedagainst 1,625 hand-labelled cells. On 556 held-out cells: **accuracy 0.993**, AUC0.984, and per-field viability within **0.3 percentage points** of expert annotation.Accuracy is insensitive to the annulus geometry: across widths of 8–40 px and gaps of0–8 px, held-out accuracy varied by 0.7 points (four cells of 556).No training data, calibration, scaler or colour information is used for viability.## Note on the minimum size filterIt is **off by default** and should stay off. When enabled without an explicit valueit uses the 25th percentile of each image, so it always deletes a quarter of theobjects however clean the field is — measured on this dataset it removed 18–25% ofreal cells, cut the count by the same fraction, and inflated viability by ~2 pointsbecause dead cells are the smaller ones.## Limitations- Viability assumes brightfield imaging with an exclusion stain (live cells refractile,dead cells stained). It does not apply to fluorescence viability assays.- The threshold is calibration-free *given a segmentation convention*. Changing whatthe mask covers — a different model, a different working resolution — shifts themeasured ratio even though the cell has not changed.- Any dark object accepted as a cell by segmentation will be called dead, so accuracyis bounded by segmentation quality.1234567891011121314151617181920212223242526272829303132333435---title: Hemocytometer Ground Truthemoji: 🎯colorFrom: bluecolorTo: yellowsdk: gradiosdk_version: 5.35.0app_file: app.pypinned: false---# Hemocytometer ground truthAnnotation tool for building ground-truth counts of the 4×4 hemocytometer block.1. **Upload** one photo.2. **Click the 4 corners** of the 4×4 block (any order). Drag a handle to adjust it.3. **Segment.** The block is warped to an upright square (≤1024 px) and segmented with thefine-tuned hemocytometer Cellpose-SAM model.4. **Correct the count:**- click a cell → remove it (false positive); click again → restore- click empty space → add a dot (false negative)- click a dot → delete it- **Shift+click** → always add a dot, even on top of a cell (e.g. two cells merged into one mask)- **Ctrl+Z / Ctrl+Shift+Z** undo / redo · **Space** (hold) hide outlines · **F** fit- mouse wheel zooms, drag pansThe total is the count of detected objects, minus objects below the min size, minusobjects touching the left or bottom 1% exclusion zones, minus removed, plus added dots.Everything after segmentation runs in the browser, so clicks are instant. The pagekeeps nothing: write the count down before uploading the next image.Set hardware to **ZeroGPU** in the Space settings. To use local weights instead of theHub file, set `CPCC_LOCAL_MODEL=/path/to/weights.npy`.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752// Ground-truth annotation canvas.
//
// Everything after segmentation happens in the browser: hit-testing, drawing,
// undo, the min-size filter and the count. The server is only called to run
// Cellpose, so no click ever round-trips an image or shows a progress bar.
//
// The server hands over two images: the warped square (JPEG) and a label PNG
// whose R,G channels hold the 16-bit object id and whose B channel holds each
// pixel's distance, in px, to the object's edge. The distance lets the outline
// thickness follow the zoom level without recomputing anything.
(function () {
"use strict";
const LEFT_PCT = 1; // exclusion zone on the LEFT edge, % of width
const BOTTOM_PCT = 1; // exclusion zone on the BOTTOM edge, % of height
const RING_SCREEN_PX = 3; // outline thickness on screen, whatever the zoom
const DOT_R = 6; // added-dot radius, screen px
const DOT_HIT_PX = 9; // a click this close to a dot (screen px) hits it
const CORNER_HIT_PX = 12; // ditto for corner handles
const DRAG_PX = 4; // movement beyond this turns a click into a pan
const MAX_ZOOM = 40;
const S = {
mode: "empty", // "empty" | "corners" | "annotate"
seq: null,
view: { s: 1, tx: 0, ty: 0 },
// corner step (preview pixel space)
cimg: null, cW: 0, cH: 0, cscale: 1, corners: [],
// annotate step (warped-image pixel space)
img: null, W: 0, H: 0, lab: null, dist: null, nobj: 0,
area: null, minx: null, miny: null, maxx: null, maxy: null,
status: null, removed: null, colors: null,
dots: [], undo: [], redo: [], minSize: 0,
overlay: null, octx: null, oimg: null, tImg: 0,
hover: null, hoverCanvas: null, hoverId: 0,
hideOverlay: false, pointerIn: false, shift: false,
down: null, dragCorner: -1, panning: false,
dirty: true, ringDirty: false,
};
// status codes per object id
const COUNTED = 0, REMOVED = 1, SMALL = 2, EXCLUDED = 3, ABSENT = 4;
let root, cv, ctx, el = {};
// ---------------------------------------------------------------- setup
function init() {
const r = document.getElementById("gt-root");
if (!r) return false;
if (r === root) return true;
root = r;
cv = document.getElementById("gt-canvas");
ctx = cv.getContext("2d");
for (const id of ["total", "breakdown", "min", "minnum", "undo", "redo",
"fit", "resetc", "editc", "hint", "empty", "stage"]) {
el[id] = document.getElementById("gt-" + id);
}
cv.addEventListener("pointerdown", onDown);
cv.addEventListener("pointermove", onMove);
cv.addEventListener("pointerup", onUp);
cv.addEventListener("pointercancel", onUp);
cv.addEventListener("pointerenter", () => { S.pointerIn = true; });
cv.addEventListener("pointerleave", () => {
S.pointerIn = false; setHover(null); dirty();
});
cv.addEventListener("wheel", onWheel, { passive: false });
cv.addEventListener("contextmenu", (e) => e.preventDefault());
window.addEventListener("keydown", onKey, true);
window.addEventListener("keyup", onKeyUp, true);
el.min.addEventListener("input", () => setMin(+el.min.value));
el.minnum.addEventListener("input", () => setMin(+el.minnum.value || 0));
el.undo.addEventListener("click", undo);
el.redo.addEventListener("click", redo);
el.fit.addEventListener("click", () => { fit(); dirty(); });
el.resetc.addEventListener("click", resetCorners);
el.editc.addEventListener("click", backToCorners);
new ResizeObserver(() => { sizeCanvas(); dirty(); }).observe(el.stage);
sizeCanvas();
requestAnimationFrame(frame);
updateUI();
return true;
}
function sizeCanvas() {
const dpr = window.devicePixelRatio || 1;
const w = el.stage.clientWidth, h = el.stage.clientHeight;
if (cv.width !== Math.round(w * dpr) || cv.height !== Math.round(h * dpr)) {
const keep = cv.width > 0 && S.mode !== "empty";
cv.width = Math.round(w * dpr);
cv.height = Math.round(h * dpr);
if (!keep) fit();
}
}
function loadImage(src) {
return new Promise((res, rej) => {
const im = new Image();
im.onload = () => res(im);
im.onerror = rej;
im.src = src;
});
}
async function decodeLabels(src, W, H) {
// createImageBitmap with no colour conversion: the bytes ARE the ids, so
// any colour management would corrupt them.
let bmp;
try {
const blob = await (await fetch(src)).blob();
bmp = await createImageBitmap(blob, {
colorSpaceConversion: "none", premultiplyAlpha: "none" });
} catch (e) {
bmp = await loadImage(src);
}
const c = document.createElement("canvas");
c.width = W; c.height = H;
const x = c.getContext("2d", { willReadFrequently: true });
x.drawImage(bmp, 0, 0);
return x.getImageData(0, 0, W, H).data;
}
// ---------------------------------------------------------------- loading
async function load(payload) {
if (!init() || !payload) return;
let p;
try { p = JSON.parse(payload); } catch (e) { return; }
if (!p || p.seq === S.seq) return; // same payload re-delivered
S.seq = p.seq;
if (p.mode === "corners") {
S.cimg = await loadImage(p.img);
S.cW = p.w; S.cH = p.h; S.cscale = p.scale;
S.corners = [];
S.mode = "corners";
clearAnnotation();
fit();
} else if (p.mode === "annotate") {
await loadAnnotate(p);
}
updateUI();
dirty();
}
function clearAnnotation() {
S.img = null; S.lab = null; S.dots = []; S.undo = []; S.redo = [];
S.hover = null; S.hoverId = 0;
}
async function loadAnnotate(p) {
const [img, px] = await Promise.all([loadImage(p.img),
decodeLabels(p.lab, p.w, p.h)]);
const W = p.w, H = p.h, N = W * H;
const lab = new Uint16Array(N), dist = new Uint8Array(N);
let maxId = 0;
for (let i = 0, o = 0; i < N; i++, o += 4) {
const id = (px[o] << 8) | px[o + 1];
lab[i] = id; dist[i] = px[o + 2];
if (id > maxId) maxId = id;
}
const n = maxId + 1;
const area = new Int32Array(n);
const minx = new Int32Array(n).fill(W), miny = new Int32Array(n).fill(H);
const maxx = new Int32Array(n).fill(-1), maxy = new Int32Array(n).fill(-1);
const sumx = new Float64Array(n), sumy = new Float64Array(n);
for (let y = 0, i = 0; y < H; y++) {
for (let x = 0; x < W; x++, i++) {
const id = lab[i];
if (!id) continue;
area[id]++; sumx[id] += x; sumy[id] += y;
if (x < minx[id]) minx[id] = x;
if (x > maxx[id]) maxx[id] = x;
if (y < miny[id]) miny[id] = y;
if (y > maxy[id]) maxy[id] = y;
}
}
Object.assign(S, {
img, W, H, lab, dist, nobj: p.nobj, area, minx, miny, maxx, maxy,
cx: sumx.map((v, i) => area[i] ? v / area[i] + 0.5 : 0),
cy: sumy.map((v, i) => area[i] ? v / area[i] + 0.5 : 0),
status: new Uint8Array(n), removed: new Uint8Array(n),
colors: makeColors(n), dots: [], undo: [], redo: [],
hover: null, hoverId: 0, mode: "annotate",
});
if (maxId !== p.nobj) {
S.warn = "Label decode mismatch (" + maxId + " vs " + p.nobj +
" objects) - counts may be off. Try another browser.";
} else {
S.warn = "";
}
S.overlay = document.createElement("canvas");
S.overlay.width = W; S.overlay.height = H;
S.octx = S.overlay.getContext("2d");
S.oimg = S.octx.createImageData(W, H);
fit();
computeAllStatus();
rebuildOverlay();
}
function makeColors(n) {
// Golden-angle hues: ids numbered close together, which Cellpose tends to
// give to neighbours, land far apart on the colour wheel
const c = new Uint8Array(n * 3);
for (let id = 1; id < n; id++) {
// hues 25..335 deg only: red is reserved for removed cells
const h = (25 + (id * 137.508) % 310) / 60, x = 1 - Math.abs(h % 2 - 1);
const k = Math.floor(h);
const rgb = [[1, x, 0], [x, 1, 0], [0, 1, x], [0, x, 1], [x, 0, 1],
[1, 0, x]][k % 6];
c[id * 3] = rgb[0] * 255; c[id * 3 + 1] = rgb[1] * 255;
c[id * 3 + 2] = rgb[2] * 255;
}
return c;
}
// ---------------------------------------------------------------- status
function statusOf(id) {
if (!S.area[id]) return ABSENT;
if (S.area[id] < S.minSize) return SMALL;
const leftPx = Math.floor(S.W * LEFT_PCT / 100);
const botPx = Math.floor(S.H * BOTTOM_PCT / 100);
if (S.minx[id] < leftPx || S.maxy[id] >= S.H - botPx) return EXCLUDED;
return S.removed[id] ? REMOVED : COUNTED;
}
function computeAllStatus() {
for (let id = 1; id < S.status.length; id++) S.status[id] = statusOf(id);
}
// ---------------------------------------------------------------- overlay
function ringT() {
return Math.max(1, Math.min(12, Math.round(RING_SCREEN_PX / S.view.s)));
}
function paint(i, d) {
// d: RGBA buffer. Writes overlay pixel i from the object's status.
const id = S.lab[i], o = i * 4;
if (!id) { d[o + 3] = 0; return; }
const st = S.status[id], dd = S.dist[i], t = S.tImg;
const edge = dd <= 1 && t >= 2; // 1 px black separator
if (st === COUNTED) {
if (edge) { d[o] = d[o + 1] = d[o + 2] = 0; d[o + 3] = 255; return; }
d[o] = S.colors[id * 3]; d[o + 1] = S.colors[id * 3 + 1];
d[o + 2] = S.colors[id * 3 + 2];
d[o + 3] = dd <= t ? 255 : 40;
} else if (st === REMOVED) {
if (edge) { d[o] = d[o + 1] = d[o + 2] = 0; d[o + 3] = 255; return; }
d[o] = 235; d[o + 1] = 30; d[o + 2] = 30;
d[o + 3] = dd <= t ? 255 : 105;
} else if (st === SMALL) {
const on = dd <= Math.max(1, t - 1);
d[o] = d[o + 1] = d[o + 2] = 150; d[o + 3] = on ? 230 : 0;
} else if (st === EXCLUDED) {
const on = dd <= Math.max(1, t - 1);
d[o] = d[o + 1] = d[o + 2] = 255; d[o + 3] = on ? 150 : 0;
} else {
d[o + 3] = 0;
}
}
function rebuildOverlay() {
if (!S.oimg) return;
S.tImg = ringT();
const d = S.oimg.data, N = S.W * S.H;
for (let i = 0; i < N; i++) paint(i, d);
S.octx.putImageData(S.oimg, 0, 0);
S.hoverId = 0; // hover outline depends on tImg too
dirty();
}
function repaintObject(id) {
const d = S.oimg.data, W = S.W;
const x0 = S.minx[id], x1 = S.maxx[id], y0 = S.miny[id], y1 = S.maxy[id];
if (x1 < 0) return;
for (let y = y0; y <= y1; y++) {
for (let x = x0, i = y * W + x0; x <= x1; x++, i++) {
if (S.lab[i] === id) paint(i, d);
}
}
S.octx.putImageData(S.oimg, 0, 0, x0, y0, x1 - x0 + 1, y1 - y0 + 1);
}
function hoverOutline(id) {
if (S.hoverId === id && S.hoverCanvas) return S.hoverCanvas;
const x0 = S.minx[id], y0 = S.miny[id];
const w = S.maxx[id] - x0 + 1, h = S.maxy[id] - y0 + 1;
const c = document.createElement("canvas");
c.width = w; c.height = h;
const x = c.getContext("2d"), im = x.createImageData(w, h), d = im.data;
const t = Math.max(1, S.tImg) + 1;
for (let yy = 0; yy < h; yy++) {
for (let xx = 0; xx < w; xx++) {
const i = (y0 + yy) * S.W + x0 + xx, o = (yy * w + xx) * 4;
if (S.lab[i] !== id) continue;
d[o] = d[o + 1] = d[o + 2] = 255;
d[o + 3] = S.dist[i] <= t ? 255 : 70;
}
}
x.putImageData(im, 0, 0);
S.hoverCanvas = c; S.hoverId = id;
return c;
}
// ---------------------------------------------------------------- view
function curSize() {
if (S.mode === "corners") return [S.cW, S.cH];
if (S.mode === "annotate") return [S.W, S.H];
return [0, 0];
}
function fit() {
const [w, h] = curSize();
const cw = el.stage.clientWidth, ch = el.stage.clientHeight;
if (!w || !cw) return;
const s = Math.min(cw / w, ch / h) * 0.96;
S.view = { s, tx: (cw - w * s) / 2, ty: (ch - h * s) / 2 };
if (S.mode === "annotate" && ringT() !== S.tImg) rebuildOverlay();
}
function toImg(sx, sy) {
return [(sx - S.view.tx) / S.view.s, (sy - S.view.ty) / S.view.s];
}
function toScreen(ix, iy) {
return [ix * S.view.s + S.view.tx, iy * S.view.s + S.view.ty];
}
function evPos(e) {
const r = cv.getBoundingClientRect();
return [e.clientX - r.left, e.clientY - r.top];
}
function onWheel(e) {
if (S.mode === "empty") return;
e.preventDefault();
const [sx, sy] = evPos(e);
const [w, h] = curSize();
const fitS = Math.min(el.stage.clientWidth / w, el.stage.clientHeight / h);
const f = Math.pow(1.0015, -e.deltaY);
const s = Math.max(fitS * 0.5, Math.min(MAX_ZOOM, S.view.s * f));
const [ix, iy] = toImg(sx, sy);
S.view = { s, tx: sx - ix * s, ty: sy - iy * s };
if (S.mode === "annotate" && ringT() !== S.tImg) S.ringDirty = true;
refreshHover(sx, sy, e.shiftKey);
dirty();
}
// ---------------------------------------------------------------- pointer
function onDown(e) {
if (S.mode === "empty") return;
cv.setPointerCapture(e.pointerId);
root.focus({ preventScroll: true });
const [sx, sy] = evPos(e);
S.down = { sx, sy, tx: S.view.tx, ty: S.view.ty, button: e.button };
S.panning = e.button !== 0; // middle / right drag always pans
S.dragCorner = -1;
if (S.mode === "corners" && e.button === 0) {
S.dragCorner = cornerAt(sx, sy);
}
}
function onMove(e) {
const [sx, sy] = evPos(e);
S.shift = e.shiftKey;
if (!S.down) { refreshHover(sx, sy, e.shiftKey); return; }
const dx = sx - S.down.sx, dy = sy - S.down.sy;
if (S.dragCorner >= 0) {
const [ix, iy] = toImg(sx, sy);
S.corners[S.dragCorner] = [clamp(ix, 0, S.cW - 1), clamp(iy, 0, S.cH - 1)];
updateUI(); dirty();
return;
}
if (!S.panning && Math.hypot(dx, dy) > DRAG_PX) S.panning = true;
if (S.panning) {
S.view.tx = S.down.tx + dx; S.view.ty = S.down.ty + dy;
setHover(null);
dirty();
}
}
function onUp(e) {
if (!S.down) return;
const [sx, sy] = evPos(e);
const wasPan = S.panning, wasCorner = S.dragCorner >= 0, b = S.down.button;
S.down = null; S.panning = false; S.dragCorner = -1;
if (e.type === "pointercancel" || wasPan || wasCorner || b !== 0) {
refreshHover(sx, sy, e.shiftKey);
return;
}
if (S.mode === "corners") cornerClick(sx, sy);
else if (S.mode === "annotate") {
const a = hitTest(sx, sy, e.shiftKey);
if (a) { exec(a); S.undo.push(a); S.redo = []; afterEdit(); }
refreshHover(sx, sy, e.shiftKey);
}
}
function clamp(v, a, b) { return Math.max(a, Math.min(b, v)); }
// ---------------------------------------------------------------- corners
function cornerAt(sx, sy) {
let best = -1, bd = CORNER_HIT_PX;
S.corners.forEach(([x, y], k) => {
const [px, py] = toScreen(x, y);
const d = Math.hypot(px - sx, py - sy);
if (d <= bd) { bd = d; best = k; }
});
return best;
}
function cornerClick(sx, sy) {
if (S.corners.length >= 4) {
hint("All 4 corners placed: drag a handle to adjust, or press Reset " +
"corners. Then press Segment.");
return;
}
const [ix, iy] = toImg(sx, sy);
if (ix < 0 || iy < 0 || ix >= S.cW || iy >= S.cH) return;
S.corners.push([ix, iy]);
updateUI(); dirty();
}
function resetCorners() {
if (S.mode !== "corners") return;
S.corners = []; updateUI(); dirty();
}
function backToCorners() {
if (S.mode !== "annotate" || !S.cimg) return;
S.mode = "corners"; fit(); updateUI(); dirty();
}
function orderedCorners() {
// clockwise from the top-left, as the server's order_quad does
const c = S.corners;
if (c.length !== 4) return c;
const mx = c.reduce((a, p) => a + p[0], 0) / 4;
const my = c.reduce((a, p) => a + p[1], 0) / 4;
const o = c.slice().sort((a, b) => Math.atan2(a[1] - my, a[0] - mx) -
Math.atan2(b[1] - my, b[0] - mx));
let k = 0;
o.forEach((p, i) => { if (p[0] + p[1] < o[k][0] + o[k][1]) k = i; });
return o.slice(k).concat(o.slice(0, k));
}
function getCorners() {
// Called by the Segment button. Returns full-resolution coordinates.
if (!init()) return "";
if (S.mode === "annotate") {
const n = S.undo.length;
if (n && !window.confirm("Re-segmenting discards your " + n +
" edit(s) on this image. Continue?")) {
return "CANCEL";
}
if (S.cimg) { S.mode = "corners"; fit(); }
}
if (S.mode !== "corners" || S.corners.length !== 4) return "";
hint("Segmenting...");
return JSON.stringify(S.corners.map(([x, y]) =>
[x / S.cscale, y / S.cscale]));
}
// ---------------------------------------------------------------- edits
function hitTest(sx, sy, shift) {
const [ix, iy] = toImg(sx, sy);
if (ix < 0 || iy < 0 || ix >= S.W || iy >= S.H) return null;
if (!shift) {
// Dots first, with a tolerance in SCREEN pixels: zooming in shrinks it
// in image pixels, so crowded areas get more precise as you zoom.
let best = null, bd = DOT_HIT_PX;
for (const d of S.dots) {
const [px, py] = toScreen(d.x, d.y);
const dd = Math.hypot(px - sx, py - sy);
if (dd <= bd) { bd = dd; best = d; }
}
if (best) return { type: "deldot", dot: best };
// Masks are hit EXACTLY: only the pixel under the cursor counts, so a
// click on background between two touching cells always adds a dot.
const id = S.lab[Math.floor(iy) * S.W + Math.floor(ix)];
if (id) {
const st = S.status[id];
if (st === COUNTED) return { type: "remove", id };
if (st === REMOVED) return { type: "restore", id };
}
}
return { type: "add", dot: { x: ix, y: iy } };
}
function exec(a) {
if (a.type === "add") S.dots.push(a.dot);
else if (a.type === "deldot") {
const k = S.dots.indexOf(a.dot);
if (k >= 0) S.dots.splice(k, 1);
} else {
S.removed[a.id] = a.type === "remove" ? 1 : 0;
S.status[a.id] = statusOf(a.id);
repaintObject(a.id);
if (S.hoverId === a.id) S.hoverId = 0;
}
}
function inverse(a) {
const t = { add: "deldot", deldot: "add", remove: "restore",
restore: "remove" }[a.type];
return Object.assign({}, a, { type: t });
}
function undo() {
const a = S.undo.pop();
if (!a) return;
exec(inverse(a)); S.redo.push(a); afterEdit();
}
function redo() {
const a = S.redo.pop();
if (!a) return;
exec(a); S.undo.push(a); afterEdit();
}
function afterEdit() { updateUI(); dirty(); }
function setMin(v) {
v = Math.max(0, Math.round(v || 0));
S.minSize = v;
if (+el.min.value !== v) el.min.value = Math.min(v, +el.min.max);
if (+el.minnum.value !== v) el.minnum.value = v;
if (S.mode === "annotate") { computeAllStatus(); rebuildOverlay(); }
updateUI();
}
// ---------------------------------------------------------------- hover
function setHover(h) { S.hover = h; }
function refreshHover(sx, sy, shift) {
if (S.mode !== "annotate" || !S.pointerIn) { setHover(null); dirty(); return; }
const a = hitTest(sx, sy, shift);
setHover(a ? Object.assign({ sx, sy }, a) : null);
if (a) {
const msg = {
add: shift ? "Shift+click: add a dot here (even on a cell)"
: "Click: add a dot (missed cell)",
deldot: "Click: delete this dot",
remove: "Click: remove this cell (" + (a.id ? S.area[a.id] : 0) + " px)",
restore: "Click: restore this removed cell",
}[a.type];
hint(msg + " · Shift+click always adds · hold Space " +
"to hide outlines · Ctrl+Z undo");
}
dirty();
}
// ---------------------------------------------------------------- keys
function active() {
return S.pointerIn || (root && root.contains(document.activeElement));
}
function onKey(e) {
if (!root || S.mode === "empty" || !active()) return;
// With the mouse over the canvas, shortcuts win even if focus was left in
// the min-size box; otherwise let inputs keep their own keys.
const tag = (e.target && e.target.tagName) || "";
if (!S.pointerIn && (tag === "INPUT" || tag === "TEXTAREA")) return;
if (S.pointerIn && tag === "INPUT") e.target.blur();
const mod = e.ctrlKey || e.metaKey;
if (e.code === "Space") {
e.preventDefault();
if (!S.hideOverlay) { S.hideOverlay = true; dirty(); }
} else if (mod && e.key.toLowerCase() === "z") {
e.preventDefault(); e.shiftKey ? redo() : undo();
} else if (mod && e.key.toLowerCase() === "y") {
e.preventDefault(); redo();
} else if (e.key === "f" || e.key === "F") {
fit(); dirty();
} else if (e.key === "Shift" && S.hover) {
refreshHover(S.hover.sx, S.hover.sy, true);
}
}
function onKeyUp(e) {
if (e.code === "Space" && S.hideOverlay) {
S.hideOverlay = false; dirty();
} else if (e.key === "Shift" && S.hover) {
refreshHover(S.hover.sx, S.hover.sy, false);
}
}
// ---------------------------------------------------------------- UI text
function hint(t) { if (el.hint) el.hint.textContent = t; }
function counts() {
const c = [0, 0, 0, 0];
for (let id = 1; id < S.status.length; id++) {
const st = S.status[id];
if (st < 4) c[st]++;
}
return c;
}
function updateUI() {
if (!root) return;
el.empty.style.display = S.mode === "empty" ? "" : "none";
el.resetc.style.display = S.mode === "corners" ? "" : "none";
el.editc.style.display = S.mode === "annotate" && S.cimg ? "" : "none";
el.undo.disabled = !S.undo.length;
el.redo.disabled = !S.redo.length;
if (S.mode === "annotate") {
const [cnt, rem, small, excl] = counts();
const add = S.dots.length;
el.total.textContent = cnt + add;
el.breakdown.innerHTML =
S.nobj + " detected" +
(small ? " − " + small + " below " + S.minSize + " px" : "") +
(excl ? " − " + excl + " on exclusion lines" : "") +
" − <b class='gt-r'>" + rem + " removed</b>" +
" + <b class='gt-a'>" + add + " added</b>" +
(S.warn ? "<br><span class='gt-r'>" + S.warn + "</span>" : "");
if (!S.hover) {
hint("Click a cell to remove it · click empty space to add a dot " +
"· Shift+click always adds · wheel zooms, drag pans " +
"· hold Space to hide outlines · Ctrl+Z undo · F fit");
}
} else if (S.mode === "corners") {
el.total.textContent = "—";
el.breakdown.textContent = S.corners.length + " / 4 corners";
hint(S.corners.length < 4
? "Click corner " + (S.corners.length + 1) + " of the 4×4 block " +
"(any order) · wheel zooms, drag pans"
: "Drag any handle to fine-tune, then press Segment.");
} else {
el.total.textContent = "—";
el.breakdown.textContent = "";
hint("");
}
}
// ---------------------------------------------------------------- draw
function dirty() { S.dirty = true; }
function frame() {
requestAnimationFrame(frame);
if (S.ringDirty && !S.down) { S.ringDirty = false; rebuildOverlay(); }
if (!S.dirty || !ctx) return;
S.dirty = false;
draw();
}
function draw() {
const dpr = window.devicePixelRatio || 1;
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.fillStyle = "#1b1d22";
ctx.fillRect(0, 0, cv.width, cv.height);
if (S.mode === "empty") return;
const { s, tx, ty } = S.view;
ctx.setTransform(dpr * s, 0, 0, dpr * s, dpr * tx, dpr * ty);
ctx.imageSmoothingEnabled = s < 2; // crisp pixels when zoomed in
if (S.mode === "corners") {
ctx.drawImage(S.cimg, 0, 0);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
drawCorners();
return;
}
ctx.drawImage(S.img, 0, 0);
if (!S.hideOverlay) {
ctx.imageSmoothingEnabled = false;
ctx.drawImage(S.overlay, 0, 0);
// exclusion zones: left and bottom
ctx.fillStyle = "rgba(255,40,40,0.22)";
const lp = Math.floor(S.W * LEFT_PCT / 100);
const bp = Math.floor(S.H * BOTTOM_PCT / 100);
ctx.fillRect(0, 0, lp, S.H);
ctx.fillRect(0, S.H - bp, S.W, bp);
const h = S.hover;
if (h && (h.type === "remove" || h.type === "restore")) {
ctx.drawImage(hoverOutline(h.id), S.minx[h.id], S.miny[h.id]);
}
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
if (!S.hideOverlay) {
// removed cells: a red X sized to the cell, so "removed" never looks
// like a counted cell that happens to be drawn in a warm colour
ctx.lineCap = "round";
for (let id = 1; id < S.status.length; id++) {
if (S.status[id] !== REMOVED) continue;
const [px, py] = toScreen(S.cx[id], S.cy[id]);
const r = Math.max(5, Math.min(14, 0.35 * S.view.s *
Math.max(S.maxx[id] - S.minx[id], S.maxy[id] - S.miny[id])));
ctx.beginPath();
ctx.moveTo(px - r, py - r); ctx.lineTo(px + r, py + r);
ctx.moveTo(px + r, py - r); ctx.lineTo(px - r, py + r);
ctx.strokeStyle = "#000"; ctx.lineWidth = 5; ctx.stroke();
ctx.strokeStyle = "#ff2b2b"; ctx.lineWidth = 3; ctx.stroke();
}
ctx.lineCap = "butt";
ctx.lineWidth = 2;
for (const d of S.dots) {
const [px, py] = toScreen(d.x, d.y);
const hot = S.hover && S.hover.type === "deldot" && S.hover.dot === d;
ctx.beginPath();
ctx.arc(px, py, DOT_R, 0, 2 * Math.PI);
ctx.fillStyle = hot ? "#ff3b3b" : "#ffe600";
ctx.fill();
ctx.strokeStyle = "#000";
ctx.stroke();
}
const h = S.hover;
if (h && h.type === "add" && !S.down) {
const [px, py] = toScreen(h.dot.x, h.dot.y);
ctx.globalAlpha = 0.55;
ctx.beginPath();
ctx.arc(px, py, DOT_R, 0, 2 * Math.PI);
ctx.fillStyle = "#ffe600"; ctx.fill();
ctx.strokeStyle = "#000"; ctx.stroke();
ctx.globalAlpha = 1;
}
}
}
function drawCorners() {
const pts = S.corners.length === 4 ? orderedCorners() : S.corners;
const sp = pts.map(([x, y]) => toScreen(x, y));
ctx.lineWidth = 2;
ctx.strokeStyle = "#4aaaff";
if (sp.length >= 2) {
ctx.beginPath();
ctx.moveTo(sp[0][0], sp[0][1]);
for (const p of sp.slice(1)) ctx.lineTo(p[0], p[1]);
if (sp.length === 4) {
ctx.closePath();
ctx.fillStyle = "rgba(74,170,255,0.12)";
ctx.fill();
}
ctx.stroke();
}
ctx.font = "bold 12px sans-serif";
ctx.textAlign = "center"; ctx.textBaseline = "middle";
S.corners.forEach(([x, y], k) => {
const [px, py] = toScreen(x, y);
ctx.beginPath();
ctx.arc(px, py, 9, 0, 2 * Math.PI);
ctx.fillStyle = "#4aaaff"; ctx.fill();
ctx.strokeStyle = "#fff"; ctx.stroke();
// crosshair so the exact point is visible inside the handle
ctx.beginPath();
ctx.moveTo(px - 4, py); ctx.lineTo(px + 4, py);
ctx.moveTo(px, py - 4); ctx.lineTo(px, py + 4);
ctx.stroke();
});
}
window.GT = { load, getCorners, init, _state: S };
// gr.HTML mounts after this script runs; try until it exists.
const t = setInterval(() => { if (init()) clearInterval(t); }, 200);
})();123456789101112131415161718192021222324# Pinned deliberately. Two of these have already broken this app once:# gradio 6 removed show_download_button and the UI failed to build;# cellpose 4.0.1 deprecated the channels= argument, and a future major version# could change model loading again. The Space rebuilds from this file on every# restart, so an unpinned range means the app can break with no code change.cellpose==4.1.1gradio==5.35.0spacesopencv-pythonnumpyscipymatplotlibPillowhuggingface_hub# joblib and scikit-learn are needed ONLY if VIABILITY_METHOD is set back to# "model". The default local-contrast rule uses neither. Kept so that switch# still works; the sklearn pin matches the version viability_clf.pkl was fitted# under, since unpickling across versions is not guaranteed.joblibscikit-learn==1.6.1# xgboost removed: never imported by app.py. It was only used by an offline# comparison script, where it scored measurably worse than the linear model.1234567891011# Pinned to match the main CellposeCellCounter Space (see its requirements.txt# for why: unpinned gradio/cellpose have each broken that app once).cellpose==4.1.1gradio==5.35.0spacesopencv-pythonnumpyPillowhuggingface_hub# gradio 5.35 imports requests but recent huggingface_hub no longer pulls it inrequests
README.md+22-59
app.py
gt_canvas.jsAdded+752
requirements.txt+4-17