dwv 0.36.0-beta.3 → 0.36.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- class t{#t;#n;#s;#i(t){if(t<0)return t;let n=t;for(;this.#n[n]!==n;)n=this.#n[n];let s=t;for(;this.#n[s]!==s;){const t=this.#n[s];this.#n[s]=n,s=t}return n}#e(t,n){this.#n[this.#i(t)]=this.#i(n)}#l(t,n,s,i){void 0!==this.#t&&this.#t===i||(this.#t=i,this.#n=new Int32Array(i),this.#s=new Int32Array(i));for(let i=0;i<s[0];i++)for(let e=0;e<s[1];e++)for(let l=0;l<s[2];l++){const s=n[0]*i+n[1]*e+n[2]*l;this.#n[s]=s,this.#s[s]=-1;const o=t[s];if(o>0){const h=s-n[0],a=s-n[1],u=s-n[2];let r=0;i>0&&(r=t[h]);let f=0;e>0&&(f=t[a]);let d=0;l>0&&(d=t[u]);let b=0;i>0&&(b=this.#s[h]);let c=0;e>0&&(c=this.#s[a]);let g=0;l>0&&(g=this.#s[u]),r!==o&&f!==o&&d!==o?this.#s[s]=s:r===o&&f!==o&&d!==o?this.#s[s]=this.#i(b):r!==o&&f===o&&d!==o?this.#s[s]=this.#i(c):r!==o&&f!==o&&d===o?this.#s[s]=this.#i(g):r!==o&&f===o&&d===o?(this.#e(c,g),this.#s[s]=this.#i(c)):r===o&&f!==o&&d===o?(this.#e(b,g),this.#s[s]=this.#i(b)):r===o&&f===o&&d!==o?(this.#e(b,c),this.#s[s]=this.#i(b)):r===o&&f===o&&d===o&&(this.#e(b,c),this.#e(b,g),this.#s[s]=this.#i(b))}}}#o(t,n){const s=new Array(n.length);let i=t,e=0;for(let t=n.length-1;t>0;--t)e=n[t],s[t]=Math.floor(i/e),i-=s[t]*e;return s[0]=i,s}#h(t,n){const s={};for(let i=0;i<this.#s.length;i++){const e=this.#i(this.#s[i]);if(e>=0){const l=this.#o(i,n),o=s[e];void 0===o?s[e]={id:t[i],sum:l,count:1}:(o.sum[0]+=l[0],o.sum[1]+=l[1],o.sum[2]+=l[2],o.count++)}}return Object.values(s).map((t=>{const n=Array(t.sum.length).fill(0);for(let s=0;s<t.sum.length;s++)n[s]=t.sum[s]/t.count;return{id:t.id,centroidIndex:n,count:t.count}}))}run(t){const n=t.imageBuffer,s=t.unitVectors,i=t.sizes,e=t.totalSize;return this.#l(n,s,i,e),this.#h(n,s)}}self.addEventListener("message",(function(n){const s=new t;self.postMessage({labels:s.run(n.data)})}),!1);
1
+ class t{#t;#e;constructor(t,e){this.#t=t,this.#e=e}getX(){return this.#t}getY(){return this.#e}getValues(){return[this.#t,this.#e]}getCentroid(){return this}equals(t){return null!=t&&this.#t===t.getX()&&this.#e===t.getY()}toString(){return"("+this.#t+", "+this.#e+")"}getDistance(t){const e=this.#t-t.getX(),i=this.#e-t.getY();return Math.sqrt(e*e+i*i)}}class e{cleanBuffer(t){for(let e=0;e<t.length;e++)t[e]>=128&&(t[e]=t[e]-128)}#i(t,e,i){return e[0]*Math.round(t.getX()/i[0])+e[1]*Math.round(t.getY()/i[1])}#n(e,i,n,s,l){const o=s.getBegin(),r=s.getEnd(),h=s.getDeltaX(),g=Math.abs(s.getDeltaY());let a=2*g-h,d=o.getY();const c=o.getY()<r.getY()?1:-1;for(let s=o.getX();s<=r.getX();s++){const o=this.#i(new t(s,d),i,n)+i[2]*l;e[o]=e[o]+128,a>0&&(d+=c,a-=2*h),a+=2*g}}#s(e,i,n,s,l){const o=s.getBegin(),r=s.getEnd(),h=Math.abs(s.getDeltaX()),g=s.getDeltaY();let a=2*h-g,d=o.getX();const c=o.getX()<r.getX()?1:-1;for(let s=o.getY();s<=r.getY();s++){const o=this.#i(new t(d,s),i,n)+i[2]*l;e[o]=e[o]+128,a>0&&(d+=c,a-=2*g),a+=2*h}}#l(t,e,i,n,s){const l=n.getBegin(),o=n.getEnd();Math.abs(n.getDeltaY())<Math.abs(n.getDeltaX())?l.getX()<o.getX()?this.#n(t,e,i,n,s):this.#n(t,e,i,n.getFlipped(),s):l.getY()<o.getY()?this.#s(t,e,i,n,s):this.#s(t,e,i,n.getFlipped(),s)}drawDebugLines(t,e,i,n,s,l){Object.values(l).map((i=>{this.#l(t,e,n,i.major.line,i.zIndex),void 0!==i.minor&&this.#l(t,e,n,i.minor.line,i.zIndex)}))}}class i{#o;#r;constructor(t,e){this.#o=t,this.#r=e}getBegin(){return this.#o}getEnd(){return this.#r}equals(t){return null!==t&&this.getBegin().equals(t.getBegin())&&this.getEnd().equals(t.getEnd())}getDeltaX(){return this.getEnd().getX()-this.getBegin().getX()}getDeltaY(){return this.getEnd().getY()-this.getBegin().getY()}getLength(){return Math.sqrt(this.getDeltaX()*this.getDeltaX()+this.getDeltaY()*this.getDeltaY())}getWorldLength(t){let e=null;if(null!==t){const i=this.getDeltaX()*t.x,n=this.getDeltaY()*t.y;e=Math.sqrt(i*i+n*n)}return e}getMidpoint(){return new t((this.getBegin().getX()+this.getEnd().getX())/2,(this.getBegin().getY()+this.getEnd().getY())/2)}getCentroid(){return this.getMidpoint()}getSlope(){return this.getDeltaY()/this.getDeltaX()}getIntercept(){return(this.getEnd().getX()*this.getBegin().getY()-this.getBegin().getX()*this.getEnd().getY())/this.getDeltaX()}getInclination(){return 180-180*Math.atan2(this.getDeltaY(),this.getDeltaX())/Math.PI}getFlipped(){return new i(this.#r,this.#o)}quantify(t){const e={},i=t.get2DSpacing(),n=this.getWorldLength(i);return null!==n&&(e.length={value:n,unit:t.getLengthUnit()}),e}}class n{#h;#g;#a;#d;#c(t){if(t<0)return t;let e=t;for(;this.#g[e]!==e;)e=this.#g[e];let i=t;for(;this.#g[i]!==i;){const t=this.#g[i];this.#g[i]=e,i=t}return e}#u(t,e){this.#g[this.#c(t)]=this.#c(e)}#f(t,e,i,n){void 0!==this.#h&&this.#h===n||(this.#h=n,this.#g=new Int32Array(n),this.#a=new Int32Array(n),this.#d=new Int32Array(n));for(let n=0;n<i[2];n++){let s=0;for(let l=0;l<i[0];l++)for(let o=0;o<i[1];o++){const r=e[0]*l+e[1]*o+e[2]*n;this.#g[r]=r,this.#a[r]=-1;const h=t[r];if(h>0){const g=r-e[0],a=r-e[1],d=r-e[2],c=r+e[0],u=r+e[1];let f=0;l>0&&(f=t[g]);let b=0;o>0&&(b=t[a]);let m=0;n>0&&(m=t[d]);let p=0;l<i[0]-1&&(p=t[c]);let X=0;o<i[1]-1&&(X=t[u]);let D=0;l>0&&(D=this.#a[g]);let Y=0;o>0&&(Y=this.#a[a]);let w=0;n>0&&(w=this.#a[d]),f!==h&&b!==h&&m!==h?this.#a[r]=r:f===h&&b!==h&&m!==h?this.#a[r]=this.#c(D):f!==h&&b===h&&m!==h?this.#a[r]=this.#c(Y):f!==h&&b!==h&&m===h?this.#a[r]=this.#c(w):f!==h&&b===h&&m===h?(this.#u(Y,w),this.#a[r]=this.#c(Y)):f===h&&b!==h&&m===h?(this.#u(D,w),this.#a[r]=this.#c(D)):f===h&&b===h&&m!==h?(this.#u(D,Y),this.#a[r]=this.#c(D)):f===h&&b===h&&m===h&&(this.#u(D,Y),this.#u(D,w),this.#a[r]=this.#c(D)),f===h&&b===h&&p===h&&X===h||(this.#d[e[2]*n+s]=r,s++)}}this.#d[e[2]*n+s]=-1}}#b(t,e){const i=new Array(e.length);let n=t,s=0;for(let t=e.length-1;t>0;--t)s=e[t],i[t]=Math.floor(n/s),n-=i[t]*s;return i[0]=n,i}#m(t,e,i){const n={};for(let i=0;i<this.#a.length;i++){const s=this.#c(this.#a[i]);if(s>=0){const l=this.#b(i,e),o=n[s];if(void 0===o){const e={};e[l[2]]=1,n[s]={id:t[i],sum:l,count:1,sliceCounts:e,maxZ:l[2],minZ:l[2]}}else o.sum[0]+=l[0],o.sum[1]+=l[1],o.sum[2]+=l[2],o.count++,void 0!==o.sliceCounts[l[2]]?o.sliceCounts[l[2]]++:o.sliceCounts[l[2]]=1,o.maxZ=Math.max(o.maxZ,l[2]),o.minZ=Math.min(o.minZ,l[2])}}const s={};for(const[t,e]of Object.entries(n)){const n=Array(e.sum.length).fill(0);for(let t=0;t<e.sum.length;t++)n[t]=e.sum[t]/e.count;const l=Object.entries(e.sliceCounts),o=(()=>{if(l.length>1){const t=l.reduce((([t,e],[i,n])=>n>e?[i,n]:[t,e]))[0];return Number(t)}return Number(l[0][0])})();s[t]={id:e.id,centroidIndex:n,count:e.count,largestSliceZ:o,height:(e.maxZ-e.minZ+1)*i[2]}}return s}#p(e,i,n){let s=0,l=0;return i[0]>i[1]?(l=e%i[0]/i[1],s=Math.floor(e/i[0])):(s=e%i[1]/i[0],l=Math.floor(e/i[1])),s*=n[0],l*=n[1],new t(s,l)}#X(t,e){return t>90-e&&t<90+e}#D(t,e,n,s,l){const o={};for(let r=0;r<n[2];r++){const n=e[2]*r;let h=0;for(;this.#d[n+h]>=0;){const g=this.#d[n+h],a=this.#c(this.#a[g]);if(void 0!==l[a]&&l[a].largestSliceZ===r){const l=g-n,h=this.#p(l,e,s);let d=0;for(;this.#d[n+d]>=0;){const l=this.#d[n+d];if(a===this.#c(this.#a[l])){const d=l-n,c=this.#p(d,e,s),u=new i(h,c),f=u.getLength(),b=o[a];(void 0===b||b.major.diameter<f)&&(o[a]={id:t[g],major:{diameter:f,line:u,offset1:g,offset2:l},zIndex:r})}d++}}h++}}for(const[t,n]of Object.entries(o)){const l=e[2]*n.zIndex,o=n.major.line.getInclination();let r=0;for(;this.#d[l+r]>=0;){const h=this.#d[l+r],g=this.#c(this.#a[h]);if(g.toString()!==t){r++;continue}const a=h-l,d=this.#p(a,e,s);let c=0;for(;this.#d[l+c]>=0;){const r=this.#d[l+c],a=this.#c(this.#a[r]);if(a.toString()===t&&g===a){const t=r-l,g=this.#p(t,e,s),a=new i(d,g),c=a.getInclination(),u=Math.abs(c-o),f=a.getLength(),b=this.#X(u,.5),m=void 0!==n.minor&&!this.#X(n.minor.angleDiff,.5)&&this.#X(u,10);(void 0===n.minor||n.minor.diameter<f&&m||n.minor.diameter<f&&b)&&(n.minor={diameter:f,line:a,offset1:h,offset2:r,angleDiff:u})}c++}r++}}return o}run(t){const i=t.imageBuffer,n=t.unitVectors,s=t.sizes,l=t.spacing,o=t.totalSize;new e,this.#f(i,n,s,o);const r=this.#m(i,n,l),h=this.#D(i,n,s,l,r);return{labels:Object.entries(r).map((([t,e])=>{if(void 0!==h[t]){const i=h[t];delete i.id,delete i.zIndex,delete i.major.line,i.minor&&delete i.minor.line,e.diameters=i}return e}))}}}self.addEventListener("message",(function(t){const e=new n;self.postMessage(e.run(t.data))}),!1);
2
2
  //# sourceMappingURL=labeling.worker.min.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"assets/workers/labeling.worker.min.js","mappings":"AAYO,MAAMA,EAMX,GAOA,GAOA,GASA,GAAMC,GACJ,GAAIA,EAAQ,EACV,OAAOA,EAIT,IAAIC,EAAeD,EACnB,KAAOE,MAAK,EAAWD,KAAkBA,GACvCA,EAAeC,MAAK,EAAWD,GAIjC,IAAIE,EAAcH,EAClB,KAAOE,MAAK,EAAWC,KAAiBA,GAAa,CACnD,MAAMC,EAAWF,MAAK,EAAWC,GACjCD,MAAK,EAAWC,GAAeF,EAC/BE,EAAcC,CAChB,CAEA,OAAOH,CACT,CAQA,GAAOI,EAAQC,GAGbJ,MAAK,EAAWA,MAAK,EAAMG,IAAWH,MAAK,EAAMI,EACnD,CAWA,GAAkBC,EAAQC,EAAaC,EAAOC,QAKJ,IAA7BR,MAAK,GACdA,MAAK,IAAwBQ,IAE7BR,MAAK,EAAsBQ,EAI3BR,MAAK,EAAa,IAAIS,WAAWD,GACjCR,MAAK,EAAU,IAAIS,WAAWD,IAIhC,IAAK,IAAIE,EAAI,EAAGA,EAAIH,EAAM,GAAIG,IAC5B,IAAK,IAAIC,EAAI,EAAGA,EAAIJ,EAAM,GAAII,IAC5B,IAAK,IAAIC,EAAI,EAAGA,EAAIL,EAAM,GAAIK,IAAK,CAEjC,MAAMC,EACHP,EAAY,GAAKI,EACjBJ,EAAY,GAAKK,EACjBL,EAAY,G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AAAA,CAAIC,GACF,MAAMC,EAAcD,EAAKC,YACnB3C,EAAc0C,EAAK1C,YACnBC,EAAQyC,EAAKzC,MACbC,EAAYwC,EAAKxC,UAgBvB,OAbAR,MAAK,EACHiD,EACA3C,EACAC,EACAC,GAIiBR,MAAK,EACtBiD,EACA3C,EAIJ,EC5TF4C,KAAKC,iBAAiB,WAAW,SAAUC,GAEzC,MAAMC,EAAS,IAAIxD,EACnBqD,KAAKI,YAAY,CACfC,OAAQF,EAAON,IAAIK,EAAMJ,OAG7B,IAAG","sources":["webpack://dwv/./src/image/labelingFilter.js","webpack://dwv/./src/image/labeling.worker.js"],"sourcesContent":["/**\n * Filter for calculating labels.\n *\n * Labels a buffer using the Hoshen–Kopelman\n * algorithm to first label all of the connected components, then does\n * a second pass to count the number of voxels in each unique label.\n *\n * The Hoshen–Kopelman labelling is slightly modified to work with\n * non-binary 3D data, but is otherwise structured the same way.\n *\n * Ref: {@link https://en.wikipedia.org/wiki/Hoshen%E2%80%93Kopelman_algorithm}.\n */\nexport class LabelingFilter {\n /**\n * The last known image size.\n *\n * @type {number}\n */\n #lastKnownTotalSize;\n\n /**\n * A union-find (disjoint-set) representing the available labels.\n *\n * @type {Int32Array}\n */\n #unionFind;\n\n /**\n * A buffer containing the labels for each voxel.\n *\n * @type {Int32Array}\n */\n #labels;\n\n /**\n * Union-find find operation.\n * Ref: {@link https://en.wikipedia.org/wiki/Disjoint-set_data_structure}.\n *\n * @param {number} label The label to find the root of.\n * @returns {number} The root label.\n */\n #find(label) {\n if (label < 0) {\n return label;\n }\n\n // Find the root label\n let currentLabel = label;\n while (this.#unionFind[currentLabel] !== currentLabel) {\n currentLabel = this.#unionFind[currentLabel];\n }\n\n // Do an update pass to make this faster next time\n let updateLabel = label;\n while (this.#unionFind[updateLabel] !== updateLabel) {\n const newLabel = this.#unionFind[updateLabel];\n this.#unionFind[updateLabel] = currentLabel;\n updateLabel = newLabel;\n }\n\n return currentLabel;\n }\n\n /**\n * Union-find union operation.\n *\n * @param {number} label1 The child label to union.\n * @param {number} label2 The parent label to union.\n */\n #union(label1, label2) {\n // This will break if a non-label (-1) get passed in\n // however with the current implmentation this should never happen\n this.#unionFind[this.#find(label1)] = this.#find(label2);\n }\n\n /**\n * Label the buffer using the Hoshen–Kopelman algorithm.\n *\n * @param {TypedArray} buffer The image buffer to regenerate the labels for.\n * @param {number[]} unitVectors The unit vectors for index to offset\n * conversion.\n * @param {number[]} sizes The image dimensions.\n * @param {number} totalSize The total length of the buffer.\n */\n #regenerateLabels(buffer, unitVectors, sizes, totalSize) {\n // If we are re-calcing the labels of the same sized image as last time we\n // can save a little time on re-initializing memory. Makes it slightly\n // faster to use a seperate worker object per segmentation, at the\n // cost of extra memory.\n if (typeof this.#lastKnownTotalSize === 'undefined' ||\n this.#lastKnownTotalSize !== totalSize) {\n // The size of the image has changed, we need to reinitialize everything.\n this.#lastKnownTotalSize = totalSize;\n\n // Performance trade-off means this can use a fair bit of memory\n // on large images.\n this.#unionFind = new Int32Array(totalSize);\n this.#labels = new Int32Array(totalSize);\n }\n\n // Generate the Hoshen–Kopelman labels\n for (let x = 0; x < sizes[0]; x++) {\n for (let y = 0; y < sizes[1]; y++) {\n for (let z = 0; z < sizes[2]; z++) {\n\n const thisOffset =\n (unitVectors[0] * x) +\n (unitVectors[1] * y) +\n (unitVectors[2] * z);\n\n // Reset labels.\n this.#unionFind[thisOffset] = thisOffset;\n this.#labels[thisOffset] = -1;\n\n const thisValue = buffer[thisOffset];\n\n if (thisValue > 0) {\n // Neighbor offsets\n const xOffset = thisOffset - unitVectors[0];\n const yOffset = thisOffset - unitVectors[1];\n const zOffset = thisOffset - unitVectors[2];\n\n // Neighbor values\n let xValue = 0;\n if (x > 0) {\n xValue = buffer[xOffset];\n };\n let yValue = 0;\n if (y > 0) {\n yValue = buffer[yOffset];\n };\n let zValue = 0;\n if (z > 0) {\n zValue = buffer[zOffset];\n };\n\n // Neighbor labels\n let xLabel = 0;\n if (x > 0) {\n xLabel = this.#labels[xOffset];\n };\n let yLabel = 0;\n if (y > 0) {\n yLabel = this.#labels[yOffset];\n };\n let zLabel = 0;\n if (z > 0) {\n zLabel = this.#labels[zOffset];\n };\n\n // No neighbors with matching values\n if (\n xValue !== thisValue &&\n yValue !== thisValue &&\n zValue !== thisValue\n ) {\n this.#labels[thisOffset] = thisOffset; // Guaranteed unique label.\n\n // One neighbor with matching values\n } else if (\n xValue === thisValue &&\n yValue !== thisValue &&\n zValue !== thisValue\n ) {\n this.#labels[thisOffset] = this.#find(xLabel);\n } else if (\n xValue !== thisValue &&\n yValue === thisValue &&\n zValue !== thisValue\n ) {\n this.#labels[thisOffset] = this.#find(yLabel);\n } else if (\n xValue !== thisValue &&\n yValue !== thisValue &&\n zValue === thisValue\n ) {\n this.#labels[thisOffset] = this.#find(zLabel);\n\n // Two neighbor with matching values\n } else if (\n xValue !== thisValue &&\n yValue === thisValue &&\n zValue === thisValue\n ) {\n this.#union(yLabel, zLabel);\n this.#labels[thisOffset] = this.#find(yLabel);\n } else if (\n xValue === thisValue &&\n yValue !== thisValue &&\n zValue === thisValue\n ) {\n this.#union(xLabel, zLabel);\n this.#labels[thisOffset] = this.#find(xLabel);\n } else if (\n xValue === thisValue &&\n yValue === thisValue &&\n zValue !== thisValue\n ) {\n this.#union(xLabel, yLabel);\n this.#labels[thisOffset] = this.#find(xLabel);\n\n // All neighbors with matching values\n } else if (\n xValue === thisValue &&\n yValue === thisValue &&\n zValue === thisValue\n ) {\n this.#union(xLabel, yLabel);\n this.#union(xLabel, zLabel);\n this.#labels[thisOffset] = this.#find(xLabel);\n }\n }\n }\n }\n }\n }\n\n /**\n * Convert an offset in memory to an index.\n *\n * @param {number} offset The offset to convert.\n * @param {number[]} unitVectors The unit vectors for index to offset\n * conversion.\n * @returns {number[]} The index.\n */\n #offsetToIndex(offset, unitVectors) {\n const values = new Array(unitVectors.length);\n let off = offset;\n let dimSize = 0;\n for (let i = unitVectors.length - 1; i > 0; --i) {\n dimSize = unitVectors[i];\n values[i] = Math.floor(off / dimSize);\n off = off - values[i] * dimSize;\n }\n values[0] = off;\n return values;\n }\n\n /**\n * Quantify labels: count items and calculate centroid.\n *\n * @param {TypedArray} buffer The image buffer to regenerate the labels for.\n * @param {number[]} unitVectors The unit vectors for index to offset\n * conversion.\n *\n * @returns {object[]} The list of quantified labels.\n */\n #quantifyLabels(\n buffer,\n unitVectors,\n ) {\n const detailledInfos = {};\n\n // Count the number of voxels per unique label,\n // this has to be done as a second pass.\n for (let o = 0; o < this.#labels.length; o++) {\n const labelValue = this.#find(this.#labels[o]);\n\n if (labelValue >= 0) {\n const index = this.#offsetToIndex(o, unitVectors);\n const info = detailledInfos[labelValue];\n if (typeof info === 'undefined') {\n detailledInfos[labelValue] = {\n id: buffer[o],\n sum: index,\n count: 1\n };\n } else {\n info.sum[0] += index[0];\n info.sum[1] += index[1];\n info.sum[2] += index[2];\n info.count++;\n }\n }\n }\n\n const labelsInfo =\n Object.values(detailledInfos).map(\n (detailledInfo) => {\n const index = Array(detailledInfo.sum.length).fill(0);\n for (let d = 0; d < detailledInfo.sum.length; d++) {\n index[d] = detailledInfo.sum[d] / detailledInfo.count;\n }\n\n return {\n id: detailledInfo.id,\n centroidIndex: index,\n count: detailledInfo.count\n };\n }\n );\n\n return labelsInfo;\n }\n\n /**\n * Run the filter.\n *\n * @param {object} data The input data.\n * @returns {object[]} The list of quantified labels.\n */\n run(data) {\n const imageBuffer = data.imageBuffer;\n const unitVectors = data.unitVectors;\n const sizes = data.sizes;\n const totalSize = data.totalSize;\n\n // generate labels\n this.#regenerateLabels(\n imageBuffer,\n unitVectors,\n sizes,\n totalSize\n );\n\n // quantify labels\n const labelsInfo = this.#quantifyLabels(\n imageBuffer,\n unitVectors,\n );\n\n return labelsInfo;\n }\n} // class labelingFilter\n","/**\n * Labeling filter worker.\n */\n\nimport {LabelingFilter} from './labelingFilter.js';\n\nself.addEventListener('message', function (event) {\n\n const filter = new LabelingFilter();\n self.postMessage({\n labels: filter.run(event.data)\n });\n\n}, false);\n"],"names":["LabelingFilter","label","currentLabel","this","updateLabel","newLabel","label1","label2","buffer","unitVectors","sizes","totalSize","Int32Array","x","y","z","thisOffset","thisValue","xOffset","yOffset","zOffset","xValue","yValue","zValue","xLabel","yLabel","zLabel","offset","values","Array","length","off","dimSize","i","Math","floor","detailledInfos","o","labelValue","index","info","id","sum","count","Object","map","detailledInfo","fill","d","centroidIndex","run","data","imageBuffer","self","addEventListener","event","filter","postMessage","labels"],"sourceRoot":""}
1
+ {"version":3,"file":"assets/workers/labeling.worker.min.js","mappings":"AAMO,MAAMA,EAOX,GAOA,GAMAC,WAAAA,CAAYC,EAAGC,GACbC,MAAK,EAAKF,EACVE,MAAK,EAAKD,CACZ,CAOAE,IAAAA,GACE,OAAOD,MAAK,CACd,CAOAE,IAAAA,GACE,OAAOF,MAAK,CACd,CAOAG,SAAAA,GACE,MAAO,CAACH,MAAK,EAAIA,MAAK,EACxB,CAOAI,WAAAA,GACE,OAAOJ,IACT,CAQAK,MAAAA,CAAOC,GACL,OAAOA,SAELN,MAAK,IAAOM,EAAIL,QAChBD,MAAK,IAAOM,EAAIJ,MACpB,CAOAK,QAAAA,GACE,MAAO,IAAMP,MAAK,EAAK,KAAOA,MAAK,EAAK,GAC1C,CAQAQ,WAAAA,CAAYC,GACV,MAAMC,EAAKV,MAAK,EAAKS,EAAQR,OACvBU,EAAKX,MAAK,EAAKS,EAAQP,OAC7B,OAAOU,KAAKC,KAAKH,EAAKA,EAAKC,EAAKA,EAClC,ECtFK,MAAMG,EAOXC,WAAAA,CAAYC,GACV,IAAK,IAAIC,EAAI,EAAGA,EAAID,EAAYE,OAAQD,IAClCD,EAAYC,IAAM,MACpBD,EAAYC,GAAKD,EAAYC,GAAK,IAGxC,CAYA,GAAyBE,EAAOC,EAAaC,GAK3C,OAHGD,EAAY,GAAKR,KAAKU,MAAMH,EAAMlB,OAASoB,EAAQ,IACnDD,EAAY,GAAKR,KAAKU,MAAMH,EAAMjB,OAASmB,EAAQ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,MAAMiF,EAAYhH,EAAa+B,UAGxBiF,EAAU9C,UACV8C,EAAU1G,cAGV0G,EAAU3G,MAAMtB,KACnBiI,EAAUzG,cACLyG,EAAUzG,MAAMxB,KAGzBgI,EAAUC,UAAYA,CACxB,CAEA,OAAOD,CAAS,IAiBxB,EClrBFE,KAAKC,iBAAiB,WAAW,SAAUC,GAEzC,MAAMC,EAAS,IAAItF,EACnBmF,KAAKI,YAAYD,EAAOR,IAAIO,EAAMN,MAEpC,IAAG","sources":["webpack://dwv/./src/math/point.js","webpack://dwv/./src/image/labelingDebug.js","webpack://dwv/./src/math/line.js","webpack://dwv/./src/image/labelingFilter.js","webpack://dwv/./src/image/labeling.worker.js"],"sourcesContent":["import {isSimilar} from './matrix.js';\nimport {Vector3D} from './vector.js';\n\n/**\n * Immutable 2D point.\n */\nexport class Point2D {\n\n /**\n * X position.\n *\n * @type {number}\n */\n #x;\n\n /**\n * Y position.\n *\n * @type {number}\n */\n #y;\n\n /**\n * @param {number} x The X coordinate for the point.\n * @param {number} y The Y coordinate for the point.\n */\n constructor(x, y) {\n this.#x = x;\n this.#y = y;\n }\n\n /**\n * Get the X position of the point.\n *\n * @returns {number} The X position of the point.\n */\n getX() {\n return this.#x;\n }\n\n /**\n * Get the Y position of the point.\n *\n * @returns {number} The Y position of the point.\n */\n getY() {\n return this.#y;\n }\n\n /**\n * Get the values of this point.\n *\n * @returns {number[]} The array of values.\n */\n getValues() {\n return [this.#x, this.#y];\n }\n\n /**\n * Get the centroid of the point, ie itself.\n *\n * @returns {Point2D} The centroid point.\n */\n getCentroid() {\n return this;\n }\n\n /**\n * Check for Point2D equality.\n *\n * @param {Point2D} rhs The other point to compare to.\n * @returns {boolean} True if both points are equal.\n */\n equals(rhs) {\n return rhs !== null &&\n typeof rhs !== 'undefined' &&\n this.#x === rhs.getX() &&\n this.#y === rhs.getY();\n }\n\n /**\n * Get a string representation of the Point2D.\n *\n * @returns {string} The point as a string.\n */\n toString() {\n return '(' + this.#x + ', ' + this.#y + ')';\n }\n\n /**\n * Get the distance to another Point2D.\n *\n * @param {Point2D} point2D The input point.\n * @returns {number} Ths distance to the input point.\n */\n getDistance(point2D) {\n const dx = this.#x - point2D.getX();\n const dy = this.#y - point2D.getY();\n return Math.sqrt(dx * dx + dy * dy);\n }\n\n} // Point2D class\n\n/**\n * Immutable 3D point.\n */\nexport class Point3D {\n\n /**\n * X position.\n *\n * @type {number}\n */\n #x;\n\n /**\n * Y position.\n *\n * @type {number}\n */\n #y;\n\n /**\n * Z position.\n *\n * @type {number}\n */\n #z;\n\n /**\n * @param {number} x The X coordinate for the point.\n * @param {number} y The Y coordinate for the point.\n * @param {number} z The Z coordinate for the point.\n */\n constructor(x, y, z) {\n this.#x = x;\n this.#y = y;\n this.#z = z;\n }\n\n /**\n * Get the X position of the point.\n *\n * @returns {number} The X position of the point.\n */\n getX() {\n return this.#x;\n }\n\n /**\n * Get the Y position of the point.\n *\n * @returns {number} The Y position of the point.\n */\n getY() {\n return this.#y;\n }\n\n /**\n * Get the Z position of the point.\n *\n * @returns {number} The Z position of the point.\n */\n getZ() {\n return this.#z;\n }\n\n /**\n * Get the values of this point.\n *\n * @returns {number[]} The array of values.\n */\n getValues() {\n return [this.#x, this.#y, this.#z];\n }\n\n /**\n * Check for Point3D equality.\n *\n * @param {Point3D} rhs The other point to compare to.\n * @returns {boolean} True if both points are equal.\n */\n equals(rhs) {\n return rhs !== null &&\n this.#x === rhs.getX() &&\n this.#y === rhs.getY() &&\n this.#z === rhs.getZ();\n }\n\n /**\n * Check for Point3D similarity.\n *\n * @param {Point3D} rhs The other point to compare to.\n * @param {number} [tol] Optional number comparison tolerance,\n * defaults to Number.EPSILON.\n * @returns {boolean} True if both points are similar.\n */\n isSimilar(rhs, tol) {\n return rhs !== null &&\n isSimilar(this.#x, rhs.getX(), tol) &&\n isSimilar(this.#y, rhs.getY(), tol) &&\n isSimilar(this.#z, rhs.getZ(), tol);\n }\n\n /**\n * Get a string representation of the Point3D.\n *\n * @returns {string} The point as a string.\n */\n toString() {\n return '(' + this.#x +\n ', ' + this.#y +\n ', ' + this.#z + ')';\n }\n\n /**\n * Get the distance to another Point3D.\n *\n * @param {Point3D} point3D The input point.\n * @returns {number} Ths distance to the input point.\n */\n getDistance(point3D) {\n return Math.sqrt(this.#getSquaredDistance(point3D));\n }\n\n /**\n * Get the square of the distance between this and\n * an input point. Used for sorting.\n *\n * @param {Point3D} point3D The input point.\n * @returns {number} The square of the distance.\n */\n #getSquaredDistance(point3D) {\n const dx = this.#x - point3D.getX();\n const dy = this.#y - point3D.getY();\n const dz = this.#z - point3D.getZ();\n return dx * dx + dy * dy + dz * dz;\n }\n\n /**\n * Get the closest point to this in a Point3D list.\n *\n * @param {Point3D[]} pointList The list to check.\n * @returns {number} The index of the closest point in the input list.\n */\n getClosest(pointList) {\n let minIndex = 0;\n // the order between squared distances and distances is the same\n let minDist = this.#getSquaredDistance(pointList[minIndex]);\n for (let i = 0; i < pointList.length; ++i) {\n const dist = this.#getSquaredDistance(pointList[i]);\n if (dist < minDist) {\n minIndex = i;\n minDist = dist;\n }\n }\n return minIndex;\n }\n\n /**\n * Get the difference to another Point3D.\n *\n * @param {Point3D} point3D The input point.\n * @returns {Vector3D} The 3D vector from the input point to this one.\n */\n minus(point3D) {\n return new Vector3D(\n (this.#x - point3D.getX()),\n (this.#y - point3D.getY()),\n (this.#z - point3D.getZ()));\n }\n\n} // Point3D class\n\n/**\n * Get an array find callback for an equal input point.\n *\n * @param {Point3D} point The point to compare to.\n * @returns {Function} A function that compares, using `equals`,\n * its input point to the one given as input to this function.\n */\nexport function getEqualPoint3DFunction(point) {\n return function (element) {\n return element.equals(point);\n };\n}\n\n/**\n * Immutable point.\n * Warning: the input array is NOT cloned, modifying it will\n * modify the point values.\n */\nexport class Point {\n\n /**\n * Point values.\n *\n * @type {number[]}\n */\n #values;\n\n /**\n * @param {number[]} values The point values.\n */\n constructor(values) {\n if (!values || typeof values === 'undefined') {\n throw new Error('Cannot create point with no values.');\n }\n if (values.length === 0) {\n throw new Error('Cannot create point with empty values.');\n }\n const valueCheck = function (val) {\n return !isNaN(val);\n };\n if (!values.every(valueCheck)) {\n throw new Error('Cannot create point with non number values.');\n }\n this.#values = values;\n }\n\n /**\n * Get the point value at the given array index.\n *\n * @param {number} i The index to get.\n * @returns {number} The value.\n */\n get(i) {\n return this.#values[i];\n }\n\n /**\n * Get the length of the point.\n *\n * @returns {number} The length.\n */\n length() {\n return this.#values.length;\n }\n\n /**\n * Get a string representation of the point.\n *\n * @returns {string} The point as a string.\n */\n toString() {\n return '(' + this.#values.toString() + ')';\n }\n\n /**\n * Get the values of this point.\n *\n * @returns {number[]} The array of values.\n */\n getValues() {\n return this.#values.slice();\n }\n\n /**\n * Check if the input point can be compared to this one.\n *\n * @param {Point} rhs The point to compare to.\n * @returns {boolean} True if both points are comparable.\n */\n canCompare(rhs) {\n // check input\n if (!rhs) {\n return false;\n }\n // check length\n if (this.length() !== rhs.length()) {\n return false;\n }\n // seems ok!\n return true;\n }\n\n /**\n * Check for Point equality.\n *\n * @param {Point} rhs The point to compare to.\n * @returns {boolean} True if both points are equal.\n */\n equals(rhs) {\n // check if can compare\n if (!this.canCompare(rhs)) {\n return false;\n }\n // check values\n for (let i = 0, leni = this.length(); i < leni; ++i) {\n if (this.get(i) !== rhs.get(i)) {\n return false;\n }\n }\n // seems ok!\n return true;\n }\n\n /**\n * Compare points and return different dimensions.\n *\n * @param {Point} rhs The point to compare to.\n * @returns {number[]} The list of different dimensions.\n */\n compare(rhs) {\n // check if can compare\n if (!this.canCompare(rhs)) {\n return null;\n }\n // check values\n const diffDims = [];\n for (let i = 0, leni = this.length(); i < leni; ++i) {\n if (this.get(i) !== rhs.get(i)) {\n diffDims.push(i);\n }\n }\n return diffDims;\n }\n\n /**\n * Get the 3D part of this point.\n *\n * @returns {Point3D} The Point3D.\n */\n get3D() {\n return new Point3D(this.get(0), this.get(1), this.get(2));\n }\n\n /**\n * Add another point to this one.\n *\n * @param {Point} rhs The point to add.\n * @returns {Point} The point representing the sum of both points.\n */\n add(rhs) {\n // check if can compare\n if (!this.canCompare(rhs)) {\n return null;\n }\n const values = [];\n const values0 = this.getValues();\n const values1 = rhs.getValues();\n for (let i = 0; i < values0.length; ++i) {\n values.push(values0[i] + values1[i]);\n }\n return new Point(values);\n }\n\n /**\n * Merge this point with a Point3D to create a new point.\n *\n * @param {Point3D} rhs The Point3D to merge with.\n * @returns {Point} The merge result.\n */\n mergeWith3D(rhs) {\n const values = this.getValues();\n values[0] = rhs.getX();\n values[1] = rhs.getY();\n values[2] = rhs.getZ();\n return new Point(values);\n }\n\n} // Point class\n","import {Point2D} from '../math/point.js';\n\n// doc imports\n/* eslint-disable no-unused-vars */\nimport {Line} from '../math/line.js';\n/* eslint-enable no-unused-vars */\n\n/**\n * Helper for the LabelingFilter, provides a debug display for diameters and\n * contours.\n *\n * Temporary until a proper way of rendering them is added.\n */\nexport class LabelingDebug {\n\n /**\n * Cleans buffer of debug lines before calculations.\n *\n * @param {TypedArray} imageBuffer The image buffer to clean.\n */\n cleanBuffer(imageBuffer) {\n for (let i = 0; i < imageBuffer.length; i++) {\n if (imageBuffer[i] >= 128) {\n imageBuffer[i] = imageBuffer[i] - 128;\n }\n }\n }\n\n /**\n * Convert a slice local world coordinate to a slice local offset value.\n *\n * @param {Point2D} point Point on the slice, scaled.\n * @param {number[]} unitVectors The unit vectors for index to offset\n * conversion.\n * @param {number[]} spacing The pixel spacing of the image.\n *\n * @returns {number} Offset relative to the offset at the start of the slice.\n */\n #sliceWorldToSliceOffset(point, unitVectors, spacing) {\n const offset =\n (unitVectors[0] * Math.round(point.getX() / spacing[0])) +\n (unitVectors[1] * Math.round(point.getY() / spacing[1]));\n\n return offset;\n }\n\n /**\n * Draw a debug line segment of an angle less that 45 degrees.\n * Points should be in slice world space.\n *\n * @param {TypedArray} imageBuffer The image buffer to draw debug lines on.\n * @param {number[]} unitVectors The unit vectors for index to offset\n * conversion.\n * @param {number[]} spacing The pixel spacing of the image.\n * @param {Line} line The line segment to plot.\n * @param {number} z The slice index.\n */\n #plotLineLow(imageBuffer, unitVectors, spacing, line, z) {\n const p0 = line.getBegin();\n const p1 = line.getEnd();\n const dx = line.getDeltaX();\n const dy = Math.abs(line.getDeltaY());\n let D = 2 * dy - dx;\n let y = p0.getY();\n const yi = (p0.getY() < p1.getY()) ? 1 : -1;\n\n for (let x = p0.getX(); x <= p1.getX(); x++) {\n const sliceOffset =\n this.#sliceWorldToSliceOffset(new Point2D(x, y), unitVectors, spacing);\n const offset = sliceOffset + (unitVectors[2] * z);\n imageBuffer[offset] = imageBuffer[offset] + 128;\n\n if (D > 0) {\n y = y + yi;\n D = D - 2 * dx;\n }\n D = D + 2 * dy;\n }\n }\n\n /**\n * Draw a debug line segment of an angle greater that 45 degrees.\n * Points should be in slice world space.\n *\n * @param {TypedArray} imageBuffer The image buffer to draw debug lines on.\n * @param {number[]} unitVectors The unit vectors for index to offset\n * conversion.\n * @param {number[]} spacing The pixel spacing of the image.\n * @param {Line} line The line segment to plot.\n * @param {number} z The slice index.\n */\n #plotLineHigh(imageBuffer, unitVectors, spacing, line, z) {\n const p0 = line.getBegin();\n const p1 = line.getEnd();\n const dx = Math.abs(line.getDeltaX());\n const dy = line.getDeltaY();\n let D = 2 * dx - dy;\n let x = p0.getX();\n const xi = (p0.getX() < p1.getX()) ? 1 : -1;\n\n for (let y = p0.getY(); y <= p1.getY(); y++) {\n const sliceOffset =\n this.#sliceWorldToSliceOffset(new Point2D(x, y), unitVectors, spacing);\n const offset = sliceOffset + (unitVectors[2] * z);\n imageBuffer[offset] = imageBuffer[offset] + 128;\n\n if (D > 0) {\n x = x + xi;\n D = D - 2 * dy;\n }\n D = D + 2 * dx;\n }\n }\n\n /**\n * Draw a debug line segment.\n * Points should be in slice world space.\n *\n * @param {TypedArray} imageBuffer The image buffer to draw debug lines on.\n * @param {number[]} unitVectors The unit vectors for index to offset\n * conversion.\n * @param {number[]} spacing The pixel spacing of the image.\n * @param {Line} line The line segment to plot.\n * @param {number} z The slice index.\n */\n #plotPoints(imageBuffer, unitVectors, spacing, line, z) {\n const p0 = line.getBegin();\n const p1 = line.getEnd();\n if (Math.abs(line.getDeltaY()) < Math.abs(line.getDeltaX())) {\n if (p0.getX() < p1.getX()) {\n this.#plotLineLow(\n imageBuffer,\n unitVectors,\n spacing,\n line,\n z\n );\n } else {\n this.#plotLineLow(\n imageBuffer,\n unitVectors,\n spacing,\n line.getFlipped(),\n z\n );\n }\n } else {\n if (p0.getY() < p1.getY()) {\n this.#plotLineHigh(\n imageBuffer,\n unitVectors,\n spacing,\n line,\n z\n );\n } else {\n this.#plotLineHigh(\n imageBuffer,\n unitVectors,\n spacing,\n line.getFlipped(),\n z\n );\n }\n }\n }\n\n /**\n * Renders debug lines for contours and diameters.\n * The pixel value of the debug lines are the segmentation label of the\n * segment + 128.\n *\n * @param {TypedArray} imageBuffer The image buffer to draw debug lines on.\n * @param {number[]} unitVectors The unit vectors for index to offset\n * conversion.\n * @param {number[]} sizes The image dimensions.\n * @param {number[]} spacing The pixel spacing of the image.\n * @param {TypedArray} borders The buffer containing the border pixel arrays.\n * @param {object} maxDiameters The dictionary of calculated diameters.\n */\n drawDebugLines(\n imageBuffer,\n unitVectors,\n sizes,\n spacing,\n borders,\n maxDiameters\n ) {\n Object.values(maxDiameters).map((diameter) => {\n this.#plotPoints(\n imageBuffer,\n unitVectors,\n spacing,\n diameter.major.line,\n diameter.zIndex\n );\n\n if (typeof diameter.minor !== 'undefined') {\n this.#plotPoints(\n imageBuffer,\n unitVectors,\n spacing,\n diameter.minor.line,\n diameter.zIndex\n );\n }\n });\n }\n\n} //class LabelingDebug","import {Point2D} from './point.js';\nimport {\n isSimilar,\n REAL_WORLD_EPSILON,\n} from './matrix.js';\n\n// doc imports\n/* eslint-disable no-unused-vars */\nimport {ViewController} from '../app/viewController.js';\nimport {Scalar2D} from './scalar.js';\n/* eslint-enable no-unused-vars */\n\n/**\n * Line shape.\n */\nexport class Line {\n\n /**\n * Line begin point.\n *\n * @type {Point2D}\n */\n #begin;\n\n /**\n * Line end point.\n *\n * @type {Point2D}\n */\n #end;\n\n /**\n * @param {Point2D} begin A Point2D representing the beginning\n * of the line.\n * @param {Point2D} end A Point2D representing the end of the line.\n */\n constructor(begin, end) {\n this.#begin = begin;\n this.#end = end;\n }\n\n /**\n * Get the begin point of the line.\n *\n * @returns {Point2D} The beginning point of the line.\n */\n getBegin() {\n return this.#begin;\n }\n\n /**\n * Get the end point of the line.\n *\n * @returns {Point2D} The ending point of the line.\n */\n getEnd() {\n return this.#end;\n }\n\n /**\n * Check for equality.\n *\n * @param {Line} rhs The object to compare to.\n * @returns {boolean} True if both objects are equal.\n */\n equals(rhs) {\n return rhs !== null &&\n this.getBegin().equals(rhs.getBegin()) &&\n this.getEnd().equals(rhs.getEnd());\n }\n\n /**\n * Get the line delta in the X direction.\n *\n * @returns {number} The delta in the X direction.\n */\n getDeltaX() {\n return this.getEnd().getX() - this.getBegin().getX();\n }\n\n /**\n * Get the line delta in the Y direction.\n *\n * @returns {number} The delta in the Y direction.\n */\n getDeltaY() {\n return this.getEnd().getY() - this.getBegin().getY();\n }\n\n /**\n * Get the length of the line.\n *\n * @returns {number} The length of the line.\n */\n getLength() {\n return Math.sqrt(\n this.getDeltaX() * this.getDeltaX() +\n this.getDeltaY() * this.getDeltaY()\n );\n }\n\n /**\n * Get the length of the line according to a spacing.\n *\n * @param {Scalar2D} spacing2D The 2D spacing.\n * @returns {number} The length of the line with spacing\n * or null for null spacings.\n */\n getWorldLength(spacing2D) {\n let wlen = null;\n if (spacing2D !== null) {\n const dxs = this.getDeltaX() * spacing2D.x;\n const dys = this.getDeltaY() * spacing2D.y;\n wlen = Math.sqrt(dxs * dxs + dys * dys);\n }\n return wlen;\n }\n\n /**\n * Get the mid point of the line.\n *\n * @returns {Point2D} The mid point of the line.\n */\n getMidpoint() {\n return new Point2D(\n (this.getBegin().getX() + this.getEnd().getX()) / 2,\n (this.getBegin().getY() + this.getEnd().getY()) / 2\n );\n }\n\n /**\n * Get the centroid of the line.\n *\n * @returns {Point2D} THe centroid point.\n */\n getCentroid() {\n return this.getMidpoint();\n }\n\n /**\n * Get the slope of the line.\n *\n * @returns {number} The slope of the line.\n */\n getSlope() {\n return this.getDeltaY() / this.getDeltaX();\n }\n\n /**\n * Get the intercept of the line.\n *\n * @returns {number} The slope of the line.\n */\n getIntercept() {\n return (\n this.getEnd().getX() * this.getBegin().getY() -\n this.getBegin().getX() * this.getEnd().getY()\n ) / this.getDeltaX();\n }\n\n /**\n * Get the inclination of the line.\n *\n * @returns {number} The inclination of the line.\n */\n getInclination() {\n // tan(theta) = slope\n const angle =\n Math.atan2(this.getDeltaY(), this.getDeltaX()) * 180 / Math.PI;\n // shift?\n return 180 - angle;\n }\n\n /**\n * Get a new line with the start and end flipped.\n *\n * @returns {Line} The new flipped line.\n */\n getFlipped() {\n return new Line(this.#end, this.#begin);\n }\n\n /**\n * Quantify a line according to view information.\n *\n * @param {ViewController} viewController The associated view controller.\n * @returns {object} A quantification object.\n */\n quantify(viewController) {\n const quant = {};\n // length\n const spacing2D = viewController.get2DSpacing();\n const length = this.getWorldLength(spacing2D);\n if (length !== null) {\n quant.length = {\n value: length,\n unit: viewController.getLengthUnit()\n };\n }\n // return\n return quant;\n }\n\n} // Line class\n\n/**\n * Get the angle between two lines in degree.\n *\n * @param {Line} line0 The first line.\n * @param {Line} line1 The second line.\n * @returns {number} The angle.\n */\nexport function getAngle(line0, line1) {\n const dx0 = line0.getDeltaX();\n const dy0 = line0.getDeltaY();\n const dx1 = line1.getDeltaX();\n const dy1 = line1.getDeltaY();\n // dot = ||a||*||b||*cos(theta)\n const dot = dx0 * dx1 + dy0 * dy1;\n // cross = ||a||*||b||*sin(theta)\n const det = dx0 * dy1 - dy0 * dx1;\n // tan = sin / cos\n const angle = Math.atan2(det, dot) * 180 / Math.PI;\n // complementary angle\n // shift?\n return 360 - (180 - angle);\n}\n\n/**\n * Check if two lines are orthogonal.\n *\n * @param {Line} line0 The first line.\n * @param {Line} line1 The second line.\n * @returns {boolean} True if both lines are orthogonal.\n */\nexport function areOrthogonal(line0, line1) {\n const dx0 = line0.getDeltaX();\n const dy0 = line0.getDeltaY();\n const dx1 = line1.getDeltaX();\n const dy1 = line1.getDeltaY();\n // dot = ||a||*||b||*cos(theta)\n return (dx0 * dx1 + dy0 * dy1) === 0;\n}\n\n/**\n * Check if a point is in a line coordinate range.\n *\n * @param {Point2D} point The input point.\n * @param {Line} line The input line.\n * @returns {boolean} True if the input point is in the line coordinate range.\n */\nexport function isPointInLineRange(point, line) {\n const minX = Math.min(line.getBegin().getX(), line.getEnd().getX());\n const maxX = Math.max(line.getBegin().getX(), line.getEnd().getX());\n const minY = Math.min(line.getBegin().getY(), line.getEnd().getY());\n const maxY = Math.max(line.getBegin().getY(), line.getEnd().getY());\n return point.getX() >= minX &&\n point.getX() <= maxX &&\n point.getY() >= minY &&\n point.getY() <= maxY;\n}\n\n/**\n * Get a perpendicular line to an input one at a given point.\n *\n * @param {Line} line The line to be perpendicular to.\n * @param {Point2D} point The middle point of the perpendicular line.\n * @param {number} length The length of the perpendicular line.\n * @param {Scalar2D} [spacing] Optional image spacing, default to [1,1].\n * @returns {Line} The perpendicular line.\n */\nexport function getPerpendicularLine(line, point, length, spacing) {\n if (typeof spacing === 'undefined') {\n spacing = {x: 1, y: 1};\n }\n const sx2 = spacing.x * spacing.x;\n const sy2 = spacing.y * spacing.y;\n // a0 * a1 = -1 (in square space)\n const perpSlope = -sx2 / (sy2 * line.getSlope());\n // y0 = a1*x0 + b1 -> b1 = y0 - a1*x0\n const prepIntercept = point.getY() - perpSlope * point.getX();\n // return\n return getLineFromEquation(perpSlope, prepIntercept, point, length, spacing);\n}\n\n/**\n * Get a perpendicular line to an input one at a given distance\n * of its begin point.\n *\n * @param {Line} line The line to be perpendicular to.\n * @param {number} distance The distance to the input line begin point.\n * @param {number} length The length of the perpendicular line.\n * @param {Scalar2D} [spacing] Optional image spacing, default to [1,1].\n * @returns {Line} The perpendicular line.\n */\nexport function getPerpendicularLineAtDistance(\n line, distance, length, spacing) {\n // get a line along the input one and centered on begin point\n const lineFromEq = getLineFromEquation(\n line.getSlope(),\n line.getIntercept(),\n line.getBegin(),\n distance,\n spacing\n );\n // select the point on the input line\n let startPoint;\n if (isPointInLineRange(lineFromEq.getBegin(), line)) {\n startPoint = lineFromEq.getBegin();\n } else {\n startPoint = lineFromEq.getEnd();\n }\n // use it as base for a perpendicular line\n return getPerpendicularLine(line, startPoint, length, spacing);\n}\n\n/**\n * Get a line from an equation, a middle point and a length.\n *\n * @param {number} slope The line slope.\n * @param {number} intercept The line intercept.\n * @param {Point2D} point The middle point of the line.\n * @param {number} length The line length.\n * @param {Scalar2D} [spacing] Optional image spacing, default to [1,1].\n * @returns {Line} The resulting line.\n */\nexport function getLineFromEquation(slope, intercept, point, length, spacing) {\n if (typeof spacing === 'undefined') {\n spacing = {x: 1, y: 1};\n }\n // begin point\n let beginX = 0;\n let beginY = 0;\n // end point\n let endX = 0;\n let endY = 0;\n\n if (isSimilar(slope, 0, REAL_WORLD_EPSILON)) {\n // slope = ~0 -> horizontal input line\n beginX = point.getX() - length / (2 * spacing.x);\n beginY = point.getY();\n endX = point.getX() + length / (2 * spacing.x);\n endY = point.getY();\n } else if (Math.abs(slope) > 1e6) {\n // slope = ~(+/-)Infinity -> vertical input line\n beginX = point.getX();\n beginY = point.getY() - length / (2 * spacing.y);\n endX = point.getX();\n endY = point.getY() + length / (2 * spacing.y);\n } else {\n const sx2 = spacing.x * spacing.x;\n const sy2 = spacing.y * spacing.y;\n\n // 1. [length] sx^2 * (x - x0)^2 + sy^2 * (y - y0)^2 = d^2\n // 2. [slope] a = (y - y0) / (x - x0) -> y - y0 = a*(x - x0)\n // -> sx^2 * (x - x0)^2 + sy^2 * a^2 * (x - x0)^2 = d^2\n // -> (x - x0)^2 = d^2 / (sx^2 + sy^2 * a^2)\n // -> x = x0 +- d / sqrt(sx^2 + sy^2 * a^2)\n\n // length is the distance between begin and end,\n // point is half way between both -> d = length / 2\n const dx = length / (2 * Math.sqrt(sx2 + sy2 * slope * slope));\n\n // begin point\n beginX = point.getX() - dx;\n beginY = slope * beginX + intercept;\n // end point\n endX = point.getX() + dx;\n endY = slope * endX + intercept;\n }\n return new Line(\n new Point2D(beginX, beginY),\n new Point2D(endX, endY));\n}\n","import {LabelingDebug} from './labelingDebug.js';\nimport {Point2D} from '../math/point.js';\nimport {Line} from '../math/line.js';\n\n// Set this to true to show the debug contour and diameter display\nconst DIAMETER_DEBUG = false;\n\n/**\n * Filter for calculating labels.\n *\n * Labels a buffer using the Hoshen–Kopelman\n * algorithm to first label all of the connected components, then does\n * a second pass to count the number of voxels in each unique label.\n *\n * The Hoshen–Kopelman labelling is slightly modified to work with\n * non-binary 3D data, but is otherwise structured the same way.\n *\n * Ref: {@link https://en.wikipedia.org/wiki/Hoshen%E2%80%93Kopelman_algorithm}.\n */\nexport class LabelingFilter {\n /**\n * The last known image size.\n *\n * @type {number}\n */\n #lastKnownTotalSize;\n\n /**\n * A union-find (disjoint-set) representing the available labels.\n *\n * @type {Int32Array}\n */\n #unionFind;\n\n /**\n * A buffer containing the labels for each voxel.\n *\n * @type {Int32Array}\n */\n #labels;\n\n /**\n * A buffer containing a list of border pixels for each layer.\n *\n * @type {Int32Array}\n */\n #borders;\n\n /**\n * Union-find find operation.\n * Ref: {@link https://en.wikipedia.org/wiki/Disjoint-set_data_structure}.\n *\n * @param {number} label The label to find the root of.\n * @returns {number} The root label.\n */\n #find(label) {\n if (label < 0) {\n return label;\n }\n\n // Find the root label\n let currentLabel = label;\n while (this.#unionFind[currentLabel] !== currentLabel) {\n currentLabel = this.#unionFind[currentLabel];\n }\n\n // Do an update pass to make this faster next time\n let updateLabel = label;\n while (this.#unionFind[updateLabel] !== updateLabel) {\n const newLabel = this.#unionFind[updateLabel];\n this.#unionFind[updateLabel] = currentLabel;\n updateLabel = newLabel;\n }\n\n return currentLabel;\n }\n\n /**\n * Union-find union operation.\n *\n * @param {number} label1 The child label to union.\n * @param {number} label2 The parent label to union.\n */\n #union(label1, label2) {\n // This will break if a non-label (-1) get passed in\n // however with the current implmentation this should never happen\n this.#unionFind[this.#find(label1)] = this.#find(label2);\n }\n\n /**\n * Label the buffer using the Hoshen–Kopelman algorithm.\n *\n * @param {TypedArray} buffer The image buffer to regenerate the labels for.\n * @param {number[]} unitVectors The unit vectors for index to offset\n * conversion.\n * @param {number[]} sizes The image dimensions.\n * @param {number} totalSize The total length of the buffer.\n */\n #regenerateLabels(buffer, unitVectors, sizes, totalSize) {\n // If we are re-calcing the labels of the same sized image as last time we\n // can save a little time on re-initializing memory. Makes it slightly\n // faster to use a seperate worker object per segmentation, at the\n // cost of extra memory.\n if (typeof this.#lastKnownTotalSize === 'undefined' ||\n this.#lastKnownTotalSize !== totalSize) {\n // The size of the image has changed, we need to reinitialize everything.\n this.#lastKnownTotalSize = totalSize;\n\n // Performance trade-off means this can use a fair bit of memory\n // on large images.\n this.#unionFind = new Int32Array(totalSize);\n this.#labels = new Int32Array(totalSize);\n this.#borders = new Int32Array(totalSize);\n }\n\n // Generate the Hoshen–Kopelman labels\n for (let z = 0; z < sizes[2]; z++) {\n\n let borderOffset = 0;\n\n for (let x = 0; x < sizes[0]; x++) {\n for (let y = 0; y < sizes[1]; y++) {\n\n const thisOffset =\n (unitVectors[0] * x) +\n (unitVectors[1] * y) +\n (unitVectors[2] * z);\n\n // Reset labels.\n this.#unionFind[thisOffset] = thisOffset;\n this.#labels[thisOffset] = -1;\n\n const thisValue = buffer[thisOffset];\n\n if (thisValue > 0) {\n // Neighbor offsets\n const xOffset = thisOffset - unitVectors[0];\n const yOffset = thisOffset - unitVectors[1];\n const zOffset = thisOffset - unitVectors[2];\n\n const xOffsetp = thisOffset + unitVectors[0];\n const yOffsetp = thisOffset + unitVectors[1];\n\n // Neighbor values\n let xValue = 0;\n if (x > 0) {\n xValue = buffer[xOffset];\n };\n let yValue = 0;\n if (y > 0) {\n yValue = buffer[yOffset];\n };\n let zValue = 0;\n if (z > 0) {\n zValue = buffer[zOffset];\n };\n\n let xValuep = 0;\n if (x < sizes[0] - 1) {\n xValuep = buffer[xOffsetp];\n };\n let yValuep = 0;\n if (y < sizes[1] - 1) {\n yValuep = buffer[yOffsetp];\n };\n\n // Neighbor labels\n let xLabel = 0;\n if (x > 0) {\n xLabel = this.#labels[xOffset];\n };\n let yLabel = 0;\n if (y > 0) {\n yLabel = this.#labels[yOffset];\n };\n let zLabel = 0;\n if (z > 0) {\n zLabel = this.#labels[zOffset];\n };\n\n // No neighbors with matching values\n if (\n xValue !== thisValue &&\n yValue !== thisValue &&\n zValue !== thisValue\n ) {\n this.#labels[thisOffset] = thisOffset; // Guaranteed unique label.\n\n // One neighbor with matching values\n } else if (\n xValue === thisValue &&\n yValue !== thisValue &&\n zValue !== thisValue\n ) {\n this.#labels[thisOffset] = this.#find(xLabel);\n } else if (\n xValue !== thisValue &&\n yValue === thisValue &&\n zValue !== thisValue\n ) {\n this.#labels[thisOffset] = this.#find(yLabel);\n } else if (\n xValue !== thisValue &&\n yValue !== thisValue &&\n zValue === thisValue\n ) {\n this.#labels[thisOffset] = this.#find(zLabel);\n\n // Two neighbor with matching values\n } else if (\n xValue !== thisValue &&\n yValue === thisValue &&\n zValue === thisValue\n ) {\n this.#union(yLabel, zLabel);\n this.#labels[thisOffset] = this.#find(yLabel);\n } else if (\n xValue === thisValue &&\n yValue !== thisValue &&\n zValue === thisValue\n ) {\n this.#union(xLabel, zLabel);\n this.#labels[thisOffset] = this.#find(xLabel);\n } else if (\n xValue === thisValue &&\n yValue === thisValue &&\n zValue !== thisValue\n ) {\n this.#union(xLabel, yLabel);\n this.#labels[thisOffset] = this.#find(xLabel);\n\n // All neighbors with matching values\n } else if (\n xValue === thisValue &&\n yValue === thisValue &&\n zValue === thisValue\n ) {\n this.#union(xLabel, yLabel);\n this.#union(xLabel, zLabel);\n this.#labels[thisOffset] = this.#find(xLabel);\n }\n\n // Border check\n if (\n xValue !== thisValue ||\n yValue !== thisValue ||\n xValuep !== thisValue ||\n yValuep !== thisValue\n ) {\n this.#borders[(unitVectors[2] * z) + borderOffset] = thisOffset;\n borderOffset++;\n }\n }\n }\n }\n\n this.#borders[(unitVectors[2] * z) + borderOffset] = -1;\n\n }\n }\n\n /**\n * Convert an offset in memory to an index.\n *\n * @param {number} offset The offset to convert.\n * @param {number[]} unitVectors The unit vectors for index to offset\n * conversion.\n * @returns {number[]} The index.\n */\n #offsetToIndex(offset, unitVectors) {\n const values = new Array(unitVectors.length);\n let off = offset;\n let dimSize = 0;\n for (let i = unitVectors.length - 1; i > 0; --i) {\n dimSize = unitVectors[i];\n values[i] = Math.floor(off / dimSize);\n off = off - values[i] * dimSize;\n }\n values[0] = off;\n return values;\n }\n\n /**\n * Quantify labels: count items, calculate centroid, and calculate height.\n *\n * @param {TypedArray} buffer The image buffer to quantify the labels for.\n * @param {number[]} unitVectors The unit vectors for index to offset\n * conversion.\n * @param {number[]} spacing The pixel spacing of the image.\n *\n * @returns {object} The dictionary of quantified labels.\n */\n #quantifyLabels(\n buffer,\n unitVectors,\n spacing\n ) {\n const detailledInfos = {};\n\n // Count the number of voxels per unique label,\n // this has to be done as a second pass.\n for (let o = 0; o < this.#labels.length; o++) {\n const labelValue = this.#find(this.#labels[o]);\n\n if (labelValue >= 0) {\n const index = this.#offsetToIndex(o, unitVectors);\n const info = detailledInfos[labelValue];\n if (typeof info === 'undefined') {\n const sliceCounts = {};\n sliceCounts[index[2]] = 1;\n detailledInfos[labelValue] = {\n id: buffer[o],\n sum: index,\n count: 1,\n sliceCounts: sliceCounts,\n maxZ: index[2],\n minZ: index[2]\n };\n } else {\n info.sum[0] += index[0];\n info.sum[1] += index[1];\n info.sum[2] += index[2];\n info.count++;\n if (typeof info.sliceCounts[index[2]] !== 'undefined') {\n info.sliceCounts[index[2]]++;\n } else {\n info.sliceCounts[index[2]] = 1;\n }\n info.maxZ = Math.max(info.maxZ, index[2]);\n info.minZ = Math.min(info.minZ, index[2]);\n }\n }\n }\n\n const labelsInfo = {};\n\n for (const [label, detailledInfo] of Object.entries(detailledInfos)) {\n const index = Array(detailledInfo.sum.length).fill(0);\n for (let d = 0; d < detailledInfo.sum.length; d++) {\n index[d] = detailledInfo.sum[d] / detailledInfo.count;\n }\n\n const sliceCounts = Object.entries(detailledInfo.sliceCounts);\n const largestSliceZ = (() => {\n if (sliceCounts.length > 1) {\n const largest =\n sliceCounts\n .reduce((\n [largestSlice, largestCount],\n [currentSlice, currentCount]\n ) => {\n if (currentCount > largestCount) {\n return [currentSlice, currentCount];\n } else {\n return [largestSlice, largestCount];\n }\n })[0];\n return Number(largest);\n } else {\n return Number(sliceCounts[0][0]);\n }\n })();\n\n labelsInfo[label] = {\n id: detailledInfo.id,\n centroidIndex: index,\n count: detailledInfo.count,\n largestSliceZ: largestSliceZ,\n height: (detailledInfo.maxZ - detailledInfo.minZ + 1) * spacing[2]\n };\n }\n\n return labelsInfo;\n }\n\n /**\n * Convert a slice local offset value to a slice local world coordinate.\n *\n * @param {number} sliceOffset Offset relative to the offset at the\n * start of the slice.\n * @param {number []} unitVectors The unit vectors for index to offset\n * conversion.\n * @param {number []} spacing The pixel spacing of the image.\n *\n * @returns {Point2D} Point on the slice, scaled.\n */\n #sliceOffsetToSliceWorld(sliceOffset, unitVectors, spacing) {\n let x = 0;\n let y = 0;\n if (unitVectors[0] > unitVectors[1]) {\n y = (sliceOffset % unitVectors[0]) / unitVectors[1];\n x = Math.floor(sliceOffset / unitVectors[0]);\n } else {\n x = (sliceOffset % unitVectors[1]) / unitVectors[0];\n y = Math.floor(sliceOffset / unitVectors[1]);\n }\n\n x = x * spacing[0];\n y = y * spacing[1];\n\n return new Point2D(x, y);\n }\n\n /**\n * Check if an angle is reasonably close to 90 degrees.\n *\n * @param {number} angle The angle to test.\n * @param {number} epsilon How close to 90 degrees it needs to be.\n * @returns {boolean} Is the angle close enough to 90 degrees.\n */\n #goodPerpendicularAngle(angle, epsilon) {\n return angle > (90 - epsilon) && angle < (90 + epsilon);\n }\n\n /**\n * Calculate the major and minor (perpendicular) diameters of each segment.\n *\n * @param {TypedArray} buffer The image buffer to calculate diameters for.\n * @param {number[]} unitVectors The unit vectors for index to offset\n * conversion.\n * @param {number[]} sizes The image dimensions.\n * @param {number[]} spacing The pixel spacing of the image.\n * @param {object} labelInfos The quantified labelInfos of the segments.\n *\n * @returns {object} The dictionary of calculated diameters.\n */\n #calculateDiameters(\n buffer,\n unitVectors,\n sizes,\n spacing,\n labelInfos\n ) {\n const maxDiameters = {};\n\n // Get the major diameter\n for (let z = 0; z < sizes[2]; z++) {\n const zOffset = unitVectors[2] * z;\n\n // TODO: It would be more efficient to calculate the convex hull, use\n // rotating calipers to get antipodal points, and then calculate the\n // major diameter from those.\n // For now the naive way is fast enough for an initial implementation.\n\n let borderOffset1 = 0;\n while (this.#borders[zOffset + borderOffset1] >= 0) {\n const offset1 = this.#borders[zOffset + borderOffset1];\n const label1 = this.#find(this.#labels[offset1]);\n\n // We only care about the diameter of the largest slice,\n // we can skip everything else.\n if (\n typeof labelInfos[label1] !== 'undefined' &&\n labelInfos[label1].largestSliceZ === z\n ) {\n const sliceOffset1 = offset1 - zOffset;\n const slicePosition1 =\n this.#sliceOffsetToSliceWorld(sliceOffset1, unitVectors, spacing);\n\n let borderOffset2 = 0;\n while (this.#borders[zOffset + borderOffset2] >= 0) {\n const offset2 = this.#borders[zOffset + borderOffset2];\n const label2 = this.#find(this.#labels[offset2]);\n\n if (label1 === label2) {\n const sliceOffset2 = offset2 - zOffset;\n const slicePosition2 =\n this.#sliceOffsetToSliceWorld(\n sliceOffset2,\n unitVectors,\n spacing\n );\n\n const sliceLine = new Line(slicePosition1, slicePosition2);\n const distance = sliceLine.getLength();\n\n const maxDiameter = maxDiameters[label1];\n if (\n typeof maxDiameter === 'undefined' ||\n maxDiameter.major.diameter < distance\n ) {\n maxDiameters[label1] = {\n id: buffer[offset1],\n major: {\n diameter: distance,\n line: sliceLine,\n offset1: offset1,\n offset2: offset2,\n },\n zIndex: z\n };\n }\n }\n\n borderOffset2++;\n }\n\n }\n\n borderOffset1++;\n }\n }\n\n // Get the minor (perpendicular) diameter\n for (const [label, diameter] of Object.entries(maxDiameters)) {\n const zOffset = unitVectors[2] * diameter.zIndex;\n const diameterLine = diameter.major.line;\n const diameterAngle = diameterLine.getInclination();\n\n // TODO: This could also be made faster by using a modified antipodal\n // point algorithm that uses perpedicularity to the initial diameter\n // instead of parallel tangents (we can't use the convex hull for this\n // one, so the normal algorithm doesn't work).\n // For now the naive way is fast enough for an initial implementation.\n\n let borderOffset1 = 0;\n while (this.#borders[zOffset + borderOffset1] >= 0) {\n const offset1 = this.#borders[zOffset + borderOffset1];\n const label1 = this.#find(this.#labels[offset1]);\n\n if (label1.toString() !== label) {\n borderOffset1++;\n continue;\n }\n\n const sliceOffset1 = offset1 - zOffset;\n const slicePosition1 =\n this.#sliceOffsetToSliceWorld(sliceOffset1, unitVectors, spacing);\n\n let borderOffset2 = 0;\n while (this.#borders[zOffset + borderOffset2] >= 0) {\n const offset2 = this.#borders[zOffset + borderOffset2];\n const label2 = this.#find(this.#labels[offset2]);\n if (label2.toString() === label && label1 === label2) {\n const sliceOffset2 = offset2 - zOffset;\n const slicePosition2 =\n this.#sliceOffsetToSliceWorld(\n sliceOffset2,\n unitVectors,\n spacing\n );\n\n // Check angle for perpendicularity\n const sliceLine = new Line(slicePosition1, slicePosition2);\n const angle = sliceLine.getInclination();\n\n const angleDifference = Math.abs(angle - diameterAngle);\n\n const distance = sliceLine.getLength();\n\n const isGoodAngle =\n this.#goodPerpendicularAngle(angleDifference, 0.5);\n\n // If we can't find any angles close to 90 degrees then\n // prioritize finding something remotely useable.\n // This only really happens on very small/thin segments.\n const isReasonableWithoutBetter =\n typeof diameter.minor !== 'undefined' &&\n (!this.#goodPerpendicularAngle(\n diameter.minor.angleDiff,\n 0.5\n )) &&\n (this.#goodPerpendicularAngle(\n angleDifference,\n 10\n ));\n\n if (\n typeof diameter.minor === 'undefined' ||\n (\n diameter.minor.diameter < distance &&\n isReasonableWithoutBetter\n ) ||\n (\n diameter.minor.diameter < distance &&\n isGoodAngle\n )\n ) {\n diameter.minor = {\n diameter: distance,\n line: sliceLine,\n offset1: offset1,\n offset2: offset2,\n angleDiff: angleDifference\n };\n }\n }\n\n borderOffset2++;\n }\n\n borderOffset1++;\n }\n }\n\n return maxDiameters;\n }\n\n /**\n * Run the filter.\n *\n * @param {object} data The input data.\n * @returns {object[]} The list of quantified labels.\n */\n run(data) {\n const imageBuffer = data.imageBuffer;\n const unitVectors = data.unitVectors;\n const sizes = data.sizes;\n const spacing = data.spacing;\n const totalSize = data.totalSize;\n\n //TODO: This is temporary until a proper method of displaying\n // them is implmented.\n // ------\n const debug = new LabelingDebug();\n if (DIAMETER_DEBUG) {\n debug.cleanBuffer(imageBuffer);\n }\n // ------\n\n // generate labels\n this.#regenerateLabels(\n imageBuffer,\n unitVectors,\n sizes,\n totalSize\n );\n\n // quantify labels\n const labelsInfo = this.#quantifyLabels(\n imageBuffer,\n unitVectors,\n spacing\n );\n\n // calculate diameters\n const maxDiameters = this.#calculateDiameters(\n imageBuffer,\n unitVectors,\n sizes,\n spacing,\n labelsInfo\n );\n\n //TODO: This is temporary until a proper method of displaying\n // them is implmented.\n // ------\n if (DIAMETER_DEBUG) {\n debug.drawDebugLines(\n imageBuffer,\n unitVectors,\n sizes,\n spacing,\n this.#borders,\n maxDiameters\n );\n }\n // ------\n\n // merge calculations\n const mergedLabelsInfo =\n Object.entries(labelsInfo).map(\n ([label, labelInfo]) => {\n if (typeof maxDiameters[label] !== 'undefined') {\n const diameters = maxDiameters[label];\n\n // Duplicate information\n delete diameters.id;\n delete diameters.zIndex;\n\n // These are in weird units and aren't helpful to pass back\n delete diameters.major.line;\n if (diameters.minor) {\n delete diameters.minor.line;\n }\n\n labelInfo.diameters = diameters;\n }\n\n return labelInfo;\n }\n );\n\n const returnEvent = {\n labels: mergedLabelsInfo,\n };\n\n //TODO: This is temporary until a proper method of displaying\n // them is implmented.\n // ------\n if (DIAMETER_DEBUG) {\n returnEvent.buffer = imageBuffer;\n }\n // ------\n\n return returnEvent;\n }\n} // class labelingFilter\n","/**\n * Labeling filter worker.\n */\n\nimport {LabelingFilter} from './labelingFilter.js';\n\nself.addEventListener('message', function (event) {\n\n const filter = new LabelingFilter();\n self.postMessage(filter.run(event.data));\n\n}, false);\n"],"names":["Point2D","constructor","x","y","this","getX","getY","getValues","getCentroid","equals","rhs","toString","getDistance","point2D","dx","dy","Math","sqrt","LabelingDebug","cleanBuffer","imageBuffer","i","length","point","unitVectors","spacing","round","line","z","p0","getBegin","p1","getEnd","getDeltaX","abs","getDeltaY","D","yi","offset","xi","getFlipped","drawDebugLines","sizes","borders","maxDiameters","Object","values","map","diameter","major","zIndex","minor","Line","begin","end","getLength","getWorldLength","spacing2D","wlen","dxs","dys","getMidpoint","getSlope","getIntercept","getInclination","atan2","PI","quantify","viewController","quant","get2DSpacing","value","unit","getLengthUnit","LabelingFilter","label","currentLabel","updateLabel","newLabel","label1","label2","buffer","totalSize","Int32Array","borderOffset","thisOffset","thisValue","xOffset","yOffset","zOffset","xOffsetp","yOffsetp","xValue","yValue","zValue","xValuep","yValuep","xLabel","yLabel","zLabel","Array","off","dimSize","floor","detailledInfos","o","labelValue","index","info","sliceCounts","id","sum","count","maxZ","minZ","max","min","labelsInfo","detailledInfo","entries","fill","d","largestSliceZ","largest","reduce","largestSlice","largestCount","currentSlice","currentCount","Number","centroidIndex","height","sliceOffset","angle","epsilon","labelInfos","borderOffset1","offset1","sliceOffset1","slicePosition1","borderOffset2","offset2","sliceOffset2","slicePosition2","sliceLine","distance","maxDiameter","diameterAngle","angleDifference","isGoodAngle","isReasonableWithoutBetter","angleDiff","run","data","labels","labelInfo","diameters","self","addEventListener","event","filter","postMessage"],"sourceRoot":""}
package/dist/dwv.d.ts CHANGED
@@ -465,6 +465,13 @@ export declare class App {
465
465
  * @returns {string[]} The list of dataIds that contain the UIDs.
466
466
  */
467
467
  getDataIdsFromSopUids(uids: string[]): string[];
468
+ /**
469
+ * Get the first data id with the given SeriesInstanceUID.
470
+ *
471
+ * @param {string} uid The SeriesInstanceUID.
472
+ * @returns {string} The data id.
473
+ */
474
+ getDataIdFromSeriesUid(uid: string): string;
468
475
  /**
469
476
  * Can the data (of the active view of the active layer) be scrolled?
470
477
  *
@@ -697,6 +704,8 @@ export declare class App {
697
704
  *
698
705
  * @param {string} uri The input uri, for example: 'window.location.href'.
699
706
  * @param {object} [options] Optional url request options.
707
+ * @deprecated Since v0.36, please extract the file list and
708
+ * pass it to loadURLs. State from uri is no longer supported.
700
709
  * @function
701
710
  */
702
711
  loadFromUri: (uri: string, options?: object) => void;
@@ -1079,6 +1088,24 @@ export declare class AppOptions {
1079
1088
  rootDocument: DocumentFragment;
1080
1089
  }
1081
1090
 
1091
+ /**
1092
+ * Class to store a boolean result and a message.
1093
+ */
1094
+ export declare class BooleanResult {
1095
+ /**
1096
+ * @param {boolean} success The success flag.
1097
+ */
1098
+ constructor(success: boolean);
1099
+ /**
1100
+ * @type {boolean}
1101
+ */
1102
+ success: boolean;
1103
+ /**
1104
+ * @type {string|undefined}
1105
+ */
1106
+ message: string | undefined;
1107
+ }
1108
+
1082
1109
  /**
1083
1110
  * Build a multipart message.
1084
1111
  *
@@ -1310,7 +1337,8 @@ export declare namespace custom {
1310
1337
  };
1311
1338
  };
1312
1339
  let openRoiDialog: any;
1313
- let getTagTime: any;
1340
+ let getVolumeIdTagValue: any;
1341
+ let getPostLoadVolumeIdTagValue: any;
1314
1342
  let getTagPixelUnit: any;
1315
1343
  }
1316
1344
 
@@ -1506,17 +1534,42 @@ export declare class DicomData {
1506
1534
  */
1507
1535
  buffer: any | undefined;
1508
1536
  /**
1509
- * Set the image complete flag (for image data).
1537
+ * Number of files/urls associated to the data.
1510
1538
  *
1511
- * @param {boolean} flag True if the image is complete.
1539
+ * @type {number}
1512
1540
  */
1513
- setComplete(flag: boolean): void;
1541
+ numberOfFiles: number;
1542
+ /**
1543
+ * List of data creation warning.
1544
+ *
1545
+ * @type {string[]}
1546
+ */
1547
+ warn: string[];
1514
1548
  /**
1515
1549
  * Get the image complete flag (for image data).
1516
1550
  *
1517
1551
  * @returns {boolean|undefined} True if the image is complete.
1518
1552
  */
1519
1553
  getComplete(): boolean | undefined;
1554
+ /**
1555
+ * Set the image complete flag (for image data).
1556
+ *
1557
+ * @param {boolean} flag True if the image is complete.
1558
+ */
1559
+ setComplete(flag: boolean): void;
1560
+ /**
1561
+ * Get the duplicate origin flag.
1562
+ *
1563
+ * @returns {boolean} The flag.
1564
+ */
1565
+ hasDuplicateOrigin(): boolean;
1566
+ /**
1567
+ * Append slice and update meta data.
1568
+ *
1569
+ * @param {DicomData} data The data to append.
1570
+ */
1571
+ appendData(data: DicomData): void;
1572
+ #private;
1520
1573
  }
1521
1574
 
1522
1575
  /**
@@ -2245,6 +2298,15 @@ export declare class Ellipse {
2245
2298
  #private;
2246
2299
  }
2247
2300
 
2301
+ /**
2302
+ * Check for window level equality.
2303
+ *
2304
+ * @param {WindowLevel} wl0 The first window level.
2305
+ * @param {WindowLevel} wl1 The second window level.
2306
+ * @returns {boolean} True if both objects are equal.
2307
+ */
2308
+ export declare function equalWl(wl0: WindowLevel, wl1: WindowLevel): boolean;
2309
+
2248
2310
  /**
2249
2311
  * 2D/3D Geometry class.
2250
2312
  */
@@ -2258,12 +2320,24 @@ export declare class Geometry {
2258
2320
  * @param {number} [time] Optional time index.
2259
2321
  */
2260
2322
  constructor(origins: Point3D[], size: Size, spacing: Spacing, orientation?: Matrix33, time?: number);
2323
+ /**
2324
+ * Clone the geometry.
2325
+ *
2326
+ * @returns {Geometry} A clone of this geometry.
2327
+ */
2328
+ clone(): Geometry;
2261
2329
  /**
2262
2330
  * Get the time value that was passed at construction.
2263
2331
  *
2264
2332
  * @returns {number} The time value.
2265
2333
  */
2266
2334
  getInitialTime(): number;
2335
+ /**
2336
+ * Set the initial time.
2337
+ *
2338
+ * @param {number} time The new time.
2339
+ */
2340
+ setInitialTime(time: number): void;
2267
2341
  /**
2268
2342
  * Get the total number of slices.
2269
2343
  * Can be different from what is stored in the size object
@@ -2358,6 +2432,24 @@ export declare class Geometry {
2358
2432
  * @returns {number} The slice index.
2359
2433
  */
2360
2434
  getSliceIndex(point: Point3D, time?: number): number;
2435
+ /**
2436
+ * Check if another geometry is compatible with this one, ie that
2437
+ * slices with these geometries can be merged into one volume.
2438
+ *
2439
+ * @param {Geometry} rhs The geometry to check.
2440
+ * @returns {BooleanResult} Result with success set to true if
2441
+ * the geometry is compatible.
2442
+ */
2443
+ canAppend(rhs: Geometry): BooleanResult;
2444
+ /**
2445
+ * Check if an origin can be appended to this geometry.
2446
+ *
2447
+ * @param {Point3D} origin The origin to append.
2448
+ * @param {number} [time] Optional time index.
2449
+ * @returns {BooleanResult} Result with success set to true if
2450
+ * the origin is compatible.
2451
+ */
2452
+ canAppendOrigin(origin: Point3D, time?: number): BooleanResult;
2361
2453
  /**
2362
2454
  * Append an origin to the geometry.
2363
2455
  *
@@ -2555,6 +2647,16 @@ export declare function getPixelDataTag(): Tag;
2555
2647
  */
2556
2648
  export declare function getRectangleIndices(center: Index, size: number[], dir: number[]): Index[];
2557
2649
 
2650
+ /**
2651
+ * Get the referenced series UID from the data elements.
2652
+ *
2653
+ * @param {Object<string, DataElement>} dataElements The data elements.
2654
+ * @returns {string|undefined} The referenced series UID.
2655
+ */
2656
+ export declare function getReferencedSeriesUID(dataElements: {
2657
+ [x: string]: DataElement;
2658
+ }): string | undefined;
2659
+
2558
2660
  /**
2559
2661
  * Get patient orientation label in the reverse direction.
2560
2662
  *
@@ -2624,6 +2726,25 @@ export declare function getTypedArray(bitsAllocated: number, pixelRepresentation
2624
2726
  */
2625
2727
  export declare function getUID(tagName: string): string;
2626
2728
 
2729
+ /**
2730
+ * Get a list of URLs from a uri containing key-value pairs as in:
2731
+ * `[dwv root]?input=encodeURIComponent([root]?key0=value0&key1=value1)`.
2732
+ *
2733
+ * @param {string} uri The input URI.
2734
+ * @returns {string[]|undefined} The list of URLs.
2735
+ */
2736
+ export declare function getURLsFromKeyValueUri(uri: string): string[] | undefined;
2737
+
2738
+ /**
2739
+ * Handle (ie call callback) with the list of urls contained in
2740
+ * a WEASIS XML manifest provided via a uri as in:
2741
+ * `[dwv root]?input=encodeURIComponent('[manifest file]')&type=manifest`.
2742
+ *
2743
+ * @param {string} uri The input URI.
2744
+ * @param {Function} callback The function to call with the decoded file urls.
2745
+ */
2746
+ export declare function handleURLsFromWeasisXMLManifest(uri: string, callback: Function): void;
2747
+
2627
2748
  /**
2628
2749
  * Check that an input buffer includes the DICOM prefix 'DICM'
2629
2750
  * after the 128 bytes preamble.
@@ -2909,6 +3030,14 @@ declare class Image_2 {
2909
3030
  * @returns {Image} A clone of this image.
2910
3031
  */
2911
3032
  clone(): Image_2;
3033
+ /**
3034
+ * Check if another image can be appended to this one.
3035
+ *
3036
+ * @param {Image} rhs The image to check.
3037
+ * @returns {BooleanResult} Result with success set to true if
3038
+ * the image can be appended.
3039
+ */
3040
+ canAppend(rhs: Image_2): BooleanResult;
2912
3041
  /**
2913
3042
  * Append a slice to the image.
2914
3043
  *
@@ -3096,6 +3225,27 @@ declare class Image_2 {
3096
3225
  * Note: Uses the raw buffer values.
3097
3226
  */
3098
3227
  compose(rhs: Image_2, operator: Function): Image_2;
3228
+ /**
3229
+ * Initialize the contour buffer.
3230
+ * Should be called on every segmentation image, or any image where
3231
+ * contour rendering needs to be supported.
3232
+ */
3233
+ initializeContour(): void;
3234
+ /**
3235
+ * Get whether or not the contour buffer has been initialized.
3236
+ *
3237
+ * @returns {boolean} True if buffer has been initialized.
3238
+ */
3239
+ countourIsInitialized(): boolean;
3240
+ /**
3241
+ * Calculate the distance to the nearest border pixel.
3242
+ * (or return the cached distance).
3243
+ *
3244
+ * @param {number} index Index/offset of the pixel to check.
3245
+ * @param {Matrix33} viewOrientation The orientation of the view.
3246
+ * @returns {number} The distance to the nearest border pixel or 0.
3247
+ */
3248
+ getContourDistance(index: number, viewOrientation: Matrix33): number;
3099
3249
  /**
3100
3250
  * Recalculate labels.
3101
3251
  */
@@ -5570,6 +5720,35 @@ export declare class View {
5570
5720
  * @param {Matrix33} mat33 The orientation matrix.
5571
5721
  */
5572
5722
  setOrientation(mat33: Matrix33): void;
5723
+ /**
5724
+ * Get the fill opacity relative to the global opacity.
5725
+ *
5726
+ * @returns {number} The fill opacity (between 0 and 1).
5727
+ */
5728
+ getFillOpacity(): number;
5729
+ /**
5730
+ * Set the fill opacity relative to the global opacity.
5731
+ * This only has an effect on segmentation views, or any other alpha
5732
+ * function that makes use of it.
5733
+ *
5734
+ * @param {number} opacity The fill opacity (between 0 and 1).
5735
+ */
5736
+ setFillOpacity(opacity: number): void;
5737
+ /**
5738
+ * Get the thickness of the contour in pixels.
5739
+ *
5740
+ * @returns {number} The contour thickness (0 <= integer <= MAX_CONTOUR_SIZE).
5741
+ */
5742
+ getContourThickness(): number;
5743
+ /**
5744
+ * Set the thickness of the contour in pixels.
5745
+ * This only has an effect on segmentation views, or any other alpha
5746
+ * function that makes use of it.
5747
+ *
5748
+ * @param {number} thickness The contour thickness
5749
+ * (0 <= integer <= MAX_CONTOUR_SIZE).
5750
+ */
5751
+ setContourThickness(thickness: number): void;
5573
5752
  /**
5574
5753
  * Initialise the view: set initial index.
5575
5754
  */
@@ -6254,6 +6433,34 @@ export declare class ViewController {
6254
6433
  * @param {alphaFn} func The function.
6255
6434
  */
6256
6435
  setViewAlphaFunction(func: (value: number[] | number, index: number) => number): void;
6436
+ /**
6437
+ * Get the fill opacity relative to the global opacity.
6438
+ *
6439
+ * @returns {number} The fill opacity (between 0 and 1).
6440
+ */
6441
+ getFillOpacity(): number;
6442
+ /**
6443
+ * Set the fill opacity relative to the global opacity.
6444
+ * This only has an effect on segmentation views, or any other alpha
6445
+ * function that makes use of it.
6446
+ *
6447
+ * @param {number} opacity The fill opacity (between 0 and 1).
6448
+ */
6449
+ setFillOpacity(opacity: number): void;
6450
+ /**
6451
+ * Get the thickness of the contour in pixels.
6452
+ *
6453
+ * @returns {number} The contour thickness (integer >= 1).
6454
+ */
6455
+ getContourThickness(): number;
6456
+ /**
6457
+ * Set the thickness of the contour in pixels.
6458
+ * This only has an effect on segmentation views, or any other alpha
6459
+ * function that makes use of it.
6460
+ *
6461
+ * @param {number} thickness The contour thickness (integer >= 1).
6462
+ */
6463
+ setContourThickness(thickness: number): void;
6257
6464
  /**
6258
6465
  * Bind the view image to the provided layer.
6259
6466
  *
@@ -6391,6 +6598,34 @@ export declare class ViewLayer {
6391
6598
  * @param {number} alpha The opacity ([0:1] range).
6392
6599
  */
6393
6600
  setOpacity(alpha: number): void;
6601
+ /**
6602
+ * Get the fill opacity relative to the global opacity.
6603
+ *
6604
+ * @returns {number} The fill opacity (between 0 and 1).
6605
+ */
6606
+ getFillOpacity(): number;
6607
+ /**
6608
+ * Set the fill opacity relative to the global opacity.
6609
+ * This only has an effect on segmentation views, or any other alpha
6610
+ * function that makes use of it.
6611
+ *
6612
+ * @param {number} opacity The fill opacity (between 0 and 1).
6613
+ */
6614
+ setFillOpacity(opacity: number): void;
6615
+ /**
6616
+ * Get the thickness of the contour in pixels.
6617
+ *
6618
+ * @returns {number} The contour thickness (integer >= 1).
6619
+ */
6620
+ getContourThickness(): number;
6621
+ /**
6622
+ * Set the thickness of the contour in pixels.
6623
+ * This only has an effect on segmentation views, or any other alpha
6624
+ * function that makes use of it.
6625
+ *
6626
+ * @param {number} thickness The contour thickness (integer >= 1).
6627
+ */
6628
+ setContourThickness(thickness: number): void;
6394
6629
  /**
6395
6630
  * Add a flip offset along the layer X axis.
6396
6631
  */
@@ -6574,13 +6809,6 @@ export declare class WindowLevel {
6574
6809
  * @type {number}
6575
6810
  */
6576
6811
  width: number;
6577
- /**
6578
- * Check for equality.
6579
- *
6580
- * @param {WindowLevel} rhs The other object to compare to.
6581
- * @returns {boolean} True if both objects are equal.
6582
- */
6583
- equals(rhs: WindowLevel): boolean;
6584
6812
  }
6585
6813
 
6586
6814
  /**