Public
Edited
Dec 13, 2023
1 fork
Insert cell
Insert cell
Insert cell
Insert cell
mutable img = {
const image = new Image;
image.crossOrigin = "anonymous";
image.src = imgDemoFile || await FileAttachment("test2.png").url()
await new Promise(resolve => image.onload = resolve)
return image;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
findcentriod_updated[0]
Insert cell
remove_intsession[1]
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
viewof csv_file_data = html`<input type=file accept="text/*">`
Insert cell
viewof dearraybutton = html`<form>${Object.assign(
html`<button type=button>Dearray TMA`,
{
onclick: (event) =>
event.currentTarget.dispatchEvent(
new CustomEvent("input", { bubbles: true })
)
}
)}`
Insert cell
Insert cell
wF = {
const w1 = Math.max(width, img.naturalWidth);
const h1 = img.naturalHeight;
return [w1, h1];
}
Insert cell
### Crop the cores Final Step
Insert cell
Insert cell
Insert cell
margin = ({ top: 10, right: 10, bottom: 10, left: 10 })
Insert cell
// Define the downloadButton view
viewof downloadButton = html`<form>${Object.assign(
html`<button type=button>Download Array</button>`,
{
onclick: (event) => {
// Call the downloadJson function only when the button is clicked
downloadJson();
event.preventDefault(); // Prevent form from submitting which is default action of button inside form
}
}
)}</form>`;

// Remove the direct call to downloadJson()

Insert cell
Insert cell
// https://talk.observablehq.com/t/organize-centroid-points-into-array-structure/7403/3
// array_centroid = {
// // Don't mutate original array.
// const points = newArray.slice();
// // Sort vertically.
// points.sort((a, b) => a.y - b.y);
// // Calculate vertical jumps.
// const yDeltas = points.map((p, i, arr) => p.y - arr[i - 1]?.y || 0);
// console.log(yDeltas);

// // Find safe threshold at which to start a new row.
// const threshold = d4
// .bin()
// .thresholds(2)(yDeltas)
// .reduce((max, bin) => Math.max(max, bin.x0), 0);
// // Split points into rows.
// const rows = yDeltas.reduce(
// (rows, d, i) => {
// // Difference exceeds threshold, create a new row.
// if (d >= threshold) rows.push([]);
// // Add point to most recent row.
// rows[rows.length - 1].push(points[i]);
// return rows;
// },

// [[]]
// );
// // Sort by x in each row.
// rows.forEach((arr) => arr.sort((a, b) => a.x - b.x));
// return rows;
// }
Insert cell
array_centroid = {
//const points_array = findcentriod_updated[2].slice();
const points_array = newArray.slice();
points_array.sort((a, b) => a.y - b.y);
//Define row_length as per the image and TMA rows
const row_length = new Array(arraylength).fill(arrayelement);
//const row_length = [22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22]; //TMA1,2,and 3
//const row_length = [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8]; //For individual sections
//const row_length = [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]; //For individual sections
//const row_length = [11, 11, 11, 11, 11, 11, 11]; //TMA4
//const row_length = [3, 3];
let last = 0;
const output = row_length.map((len) =>
points_array.slice(last, (last += len)).sort((a, b) => a.x - b.x)
);
return output;
}
Insert cell
Insert cell
newArray = closetsindexfinal_final[0].concat(remove_intsession[1])
Insert cell
newArray.map((item) => item.radius = coreRadius)
Insert cell
Insert cell
//https://stackoverflow.com/questions/75621696/remove-closest-points-in-javascript/75621844#75621844
closetsindexfinal_final = {
button;
const distance_final = (a, b) => {
return Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
};
const findClosestIndex_final = (list_final, point_final) => {
const distances_final = list_final.map((listPoint_final) => {
return distance_final(listPoint_final, point_final);
});
const min_final = Math.min(...distances_final);
return distances_final.findIndex((p_final) => {
return p_final === min_final;
});
};
const AWithClosestToBRemoved = remove_intsession[2].reduce(
(result_final, point_final) => {
const closestIndex_final = findClosestIndex_final(
result_final,
point_final
);
return result_final.filter((_, i) => {
return i !== closestIndex_final;
});
},
remove_intsession[3]
);
return [AWithClosestToBRemoved];
}
Insert cell
// //https://stackoverflow.com/questions/75621696/remove-closest-points-in-javascript/75621844#75621844
// closetsindexfinal_final = {
// const distance = (a, b) => {
// return Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
// };
// const findClosestIndex = (list, point) => {
// const distances = list.map((listPoint) => {
// return distance(listPoint, point);
// });
// const min = Math.min(...distances);
// return distances.findIndex((p) => {
// return p === min;
// });
// };
// const AWithClosestToBRemoved = remove_intsession[2].reduce(
// (result, point) => {
// const closestIndex = findClosestIndex(result, point);
// return result.filter((_, i) => {
// return i !== closestIndex;
// });
// },
// remove_intsession[3]
// );
// return [AWithClosestToBRemoved];
// }
Insert cell
Insert cell
remove_intsession = {
let pointSize = 5;
let pointSizeDelete = 10;
var points = [];
var Removpoint = [];
var timeout = 300;
var clicks = 0;
var dblclicks = 0;
let new_centropid_find = findcentriod_updated[2];
//console.log(new_centropid_find);
let interactive_canvas = findcentriod_updated[0];
var newFinalCentroid = []; // New array with centroid points after REMOVING the odd centroids
const ctx_int = interactive_canvas.getContext("2d"); //ctx_int = interactive canvas
let cw = Math.min(width, img.width);
let ch = ~~((img.height * cw) / img.width);
function getPosition(event) {
var rect = canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
}
function drawCoordinates(point, r) {
ctx_int.fillStyle = "#52FF33"; // Green color
ctx_int.beginPath();
ctx_int.arc(point.x, point.y, r, 0, Math.PI * 2, true);
ctx_int.fill();
}
function drawGreenCircle(point, r) {
//ctx_int.fillStyle = "#000000"; //
ctx_int.beginPath();
ctx_int.arc(point.x, point.y, r, 0, Math.PI * 2, true);
ctx_int.fill();
ctx_int.strokeStyle = "#000000";
//ctx_int.fillStyle = "#FFFFFF";
ctx_int.fillStyle = "rgba(0, 0, 0, 0)";
ctx_int.stroke();
}
function drawCoordinates2(point, r) {
ctx_int.fillStyle = "#F50606"; // Green color
ctx_int.beginPath();
ctx_int.arc(point.x, point.y, r, 0, Math.PI * 2, true);
ctx_int.fill();
}
canvas.addEventListener("click", function (e) {
clicks++;
var m = getPosition(e);
if (clicks == 1) {
setTimeout(function () {
if (clicks == 1) {
drawCoordinates(m, pointSize);
//drawGreenCircle(m, coreRadius);
points.push(m); // New Centroid points will be added to new array "points"
}
clicks = 0;
}, timeout);
}
});

canvas.addEventListener("dblclick", function (e) {
dblclicks++;
var RemM = getPosition(e);
drawCoordinates2(RemM, pointSize);
Removpoint.push(RemM);
});

return [
interactive_canvas, // canvas
points, //Points from SINGLE click and will be added
Removpoint, //Points from DOUBLE click and will be REMOVED
new_centropid_find // Automatically selected centroids
];
}
Insert cell
remove_intsession[2]
Insert cell
remove_intsession[3]
Insert cell
//new_centropid_find = findcentriod_updated[2]
Insert cell
//findcentriod_updated[2]
Insert cell
Insert cell
// {
// const ctx = DOM.context2d(150, 150);
// //for (let z = 0; z < centriod_sort11[0].length; z++) {
// //console.log(centroid_new[z]["x"]);
// ctx.putImageData(
// canvas
// .getContext("2d")
// .getImageData(centriod_sort11[0]["x"], centriod_sort11[0]["y"], 50, 50),
// 0,
// 0
// );
// //}
// return ctx.canvas;
// }
Insert cell
// centriod_sort11 = array_centroid[0].sort(function (a, b) {
// if (a.x == b.x) return a.y - b.y;
// return a.x - b.x;
// })
Insert cell
// new_sorted_centroid = {
// const nw_centroid = array_centroid.slice();
// nw_centroid.sort((c, d) => c.y - d.y);
// return nw_centroid;
// }
Insert cell
// array_centroid = {
// const points_array = findcentriod_updated[2].slice();
// points_array.sort((a, b) => a.y - b.y);
// //Define row_length as per the image and TMA rows
// //const row_length = [22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22];
// const row_length = [22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22];
// let last = 0;
// const output = row_length.map((len) =>
// points_array.slice(last, (last += len))
// );
// return output;
// }
Insert cell
//array_centroid[10][12]
Insert cell
d4 = require("d3@6")
Insert cell
//viewof csv_file_data = html`<input type=file accept="text/*">`
Insert cell
Insert cell
Insert cell
Insert cell
//Hovering activity tool
import { Tooltip } from "@clhenrick/tooltip-component"
Insert cell
Insert cell
viewof arraylength = new View(13)
Insert cell
viewof arrayelement = new View(8)
Insert cell
viewof coreArea = new View(400)
Insert cell
viewof coreRadius = new View(19)
Insert cell
viewof subsampleTol = new View (0)
Insert cell
viewof scale_factor = new View (1)
Insert cell
//viewof drawSettings = new View(['maskedImage', 'contour', 'centroids', 'selectCores', 'getTMACores'])
viewof drawSettings = new View([
"maskedImage",
"contour",
"centroids",
"selectCores"
])
Insert cell
mutable segmentation = null
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
import { bindSliderNumber, bindRadioGroup, bindCheckGroup, bindCheckbox, bindFile, View } from "@esperanc/inline-inputs"
Insert cell
import { comment } from "@esperanc/notebook-css-utilities"
Insert cell
Insert cell
## Load OpenCV
Insert cell
import {cv} from "@mootari/opencv-js"
Insert cell
d3 = require('d3-dsv')
Insert cell
Insert cell
Insert cell
Insert cell
downloadJson = () => {
const blob = new Blob([JSON.stringify(newArray, null, 2)], { type: 'application/json' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${imgfile[0].name.split('.')[0]}.json`;
a.click();
window.URL.revokeObjectURL(url);
};
Insert cell
{
dearraybutton;
const zip = new jsZip();
const zipFolderName = "dearrayedCores";
const imageFolderName = "img";
const imageFolder = zip.folder(imageFolderName);
const metadataFolderName = "metadata";
const metadataFolder = zip.folder(metadataFolderName);
//const scale_factor = 20;
const anchorTag = document.createElement("a");
//const ctxxx = canvas.getContext("2d");
//let w = Math.max(width, img.naturalWidth);
let w = img.naturalWidth
//let w = img.width;
//let h = ~~((img.height * w) / img.width);
let h = img.naturalHeight;
//let h = img;
let myCanvas = DOM.canvas(w, h, 1);
let ctxxx = myCanvas.getContext("2d");
ctxxx.drawImage(img, 0, 0, w, h);
await Promise.allSettled(
array_centroid.map((row, rowIndex) =>
Promise.allSettled(
row.map(async (column, columnIndex) => {
const correspondingMetadata = data_updated.find(
(metadata) =>
metadata.Row == `${rowIndex + 1}` &&
metadata.Col == `${columnIndex + 1}`
);
if (correspondingMetadata) {
const ctx = DOM.context2d(
2 * scale_factor * coreRadius,
2 * scale_factor * coreRadius,
1
);
// const ctx = DOM.context2d(2 * coreRadius, 2 * coreRadius, 1);
console.log(ctx.canvas.width);
//debugger;
ctx.putImageData(
ctxxx.getImageData(
column["x"] * scale_factor - coreRadius * scale_factor,
column["y"] * scale_factor - coreRadius * scale_factor,
2 * scale_factor * coreRadius,
2 * scale_factor * coreRadius
),
0,
0
);
// ctx.putImageData(
// ctxxx.getImageData(
// column["x"] - coreRadius,
// column["y"] - coreRadius,
// 2 * coreRadius, //150, 150 for figure "a" else 40
// 2 * coreRadius //150, 150 for figure "a" else 40
// ),
// 0,
// 0
// );
const imageBlob = await new Promise((resolve) =>
ctx.canvas.toBlob(resolve, "image/PNG", 1.0)
);
imageFolder.file(
`${correspondingMetadata["SPOT ID#"]}.png`,
imageBlob,
{ binary: true }
);
metadataFolder.file(
`${correspondingMetadata["SPOT ID#"]}.json`,
JSON.stringify(correspondingMetadata)
);
}
// if (rowIndex == centriod_sort.length - 1 && columnIndex == row.length - 1) {

// }
})
)
)
);
zip.generateAsync({ type: "blob" }).then((content) => {
const urlToBlob = URL.createObjectURL(content);
const anchorTag = document.createElement("a");
anchorTag.download = `${zipFolderName}.zip`;
anchorTag.href = urlToBlob;
anchorTag.click();
});
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more