ppu-ocv 1.5.3 → 1.7.0
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.
- package/README.md +0 -36
- package/canvas-toolkit.d.ts +2 -2
- package/canvas-toolkit.js +1 -1
- package/contours.d.ts +2 -2
- package/contours.js +1 -1
- package/image-analysis.d.ts +1 -1
- package/image-analysis.js +1 -1
- package/image-processor.d.ts +3 -3
- package/image-processor.js +1 -1
- package/index.d.ts +7 -8
- package/index.interface.d.ts +0 -9
- package/index.js +1 -1
- package/operations/adaptive-threshold.d.ts +2 -2
- package/operations/adaptive-threshold.js +1 -1
- package/operations/blur.d.ts +2 -2
- package/operations/blur.js +1 -1
- package/operations/border.d.ts +2 -2
- package/operations/border.js +1 -1
- package/operations/canny.d.ts +2 -2
- package/operations/canny.js +1 -1
- package/operations/convert.d.ts +2 -2
- package/operations/convert.js +1 -1
- package/operations/dilate.d.ts +2 -2
- package/operations/dilate.js +1 -1
- package/operations/erode.d.ts +2 -2
- package/operations/erode.js +1 -1
- package/operations/grayscale.d.ts +2 -2
- package/operations/grayscale.js +1 -1
- package/operations/invert.d.ts +2 -2
- package/operations/invert.js +1 -1
- package/operations/morphological-gradient.d.ts +2 -2
- package/operations/morphological-gradient.js +1 -1
- package/operations/resize.d.ts +2 -2
- package/operations/resize.js +1 -1
- package/operations/rotate.d.ts +2 -2
- package/operations/rotate.js +1 -1
- package/operations/threshold.d.ts +2 -2
- package/operations/threshold.js +1 -1
- package/operations/warp.d.ts +2 -2
- package/operations/warp.js +1 -1
- package/package.json +1 -1
- package/pipeline/index.d.ts +30 -30
- package/pipeline/index.js +1 -1
- package/pipeline/registry.d.ts +2 -2
- package/face-detector.d.ts +0 -70
- package/face-detector.js +0 -1
- package/haarcascade_eye.xml +0 -12213
- package/haarcascade_eye_tree_eyeglasses.xml +0 -22619
- package/haarcascade_frontalface_default.xml +0 -33314
package/README.md
CHANGED
|
@@ -165,42 +165,6 @@ See: [How to extend ppu-ocv operations](./docs/how-to-extend-ppu-ocv-operations.
|
|
|
165
165
|
| `getCornerPoints` | Canvas, contour | Get four corner points for a given contour. Useful for perspective transformation (warp). |
|
|
166
166
|
| `destroy` | | Destroy & clean-up the memory from the contours |
|
|
167
167
|
|
|
168
|
-
#### `FaceDetector`
|
|
169
|
-
|
|
170
|
-
Singleton class for face and eye detection using Haar Cascade classifiers.
|
|
171
|
-
|
|
172
|
-
| Method | Args | Description |
|
|
173
|
-
| ------------- | --------------------------- | ---------------------------------------------------------------------- |
|
|
174
|
-
| `getInstance` | | Get the singleton instance of FaceDetector |
|
|
175
|
-
| `detectFace` | Canvas, options | Detect faces in the given canvas, returns `{ faces: BoundingBox[] }` |
|
|
176
|
-
| `detectEye` | Canvas, options | Detect eyes in the given canvas, returns `{ eyes: { left, right }[] }` |
|
|
177
|
-
| `alignFace` | Canvas, [leftEye, rightEye] | Align face based on eye positions, returns aligned Canvas |
|
|
178
|
-
|
|
179
|
-
**Usage Example:**
|
|
180
|
-
|
|
181
|
-
```ts
|
|
182
|
-
import { FaceDetector, ImageProcessor } from "ppu-ocv";
|
|
183
|
-
|
|
184
|
-
await ImageProcessor.initRuntime();
|
|
185
|
-
const file = Bun.file("./image.jpg");
|
|
186
|
-
const canvas = await ImageProcessor.prepareCanvas(await file.arrayBuffer());
|
|
187
|
-
|
|
188
|
-
const faceDetector = await FaceDetector.getInstance();
|
|
189
|
-
|
|
190
|
-
// Detect faces
|
|
191
|
-
const faceResult = await faceDetector.detectFace(canvas);
|
|
192
|
-
console.log(`Found ${faceResult.faces.length} faces`);
|
|
193
|
-
|
|
194
|
-
// Detect eyes
|
|
195
|
-
const eyeResult = await faceDetector.detectEye(canvas);
|
|
196
|
-
|
|
197
|
-
// Align face if eyes detected
|
|
198
|
-
if (eyeResult.eyes.length > 0) {
|
|
199
|
-
const { left, right } = eyeResult.eyes[0];
|
|
200
|
-
const alignedCanvas = await faceDetector.alignFace(canvas, [left, right]);
|
|
201
|
-
}
|
|
202
|
-
```
|
|
203
|
-
|
|
204
168
|
#### `ImageAnalysis`
|
|
205
169
|
|
|
206
170
|
Just a collection of utility functions for analyzing image properties.
|
package/canvas-toolkit.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { BoundingBox, SKRSContext2D } from "./index";
|
|
2
|
-
import { Canvas, cv } from "./index";
|
|
1
|
+
import type { BoundingBox, SKRSContext2D } from "./index.js";
|
|
2
|
+
import { Canvas, cv } from "./index.js";
|
|
3
3
|
/**
|
|
4
4
|
* Singleton class for canvas manipulation utilities
|
|
5
5
|
*/
|
package/canvas-toolkit.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export class CanvasToolkit{static instance=null;step=0;constructor(){}static getInstance(){if(!CanvasToolkit.instance){CanvasToolkit.instance=new CanvasToolkit}return CanvasToolkit.instance}crop(options){const{bbox,canvas}=options;let croppedCanvas=createCanvas(bbox.x1-bbox.x0,bbox.y1-bbox.y0);let croppedCtx=croppedCanvas.getContext("2d");croppedCtx.drawImage(canvas,bbox.x0,bbox.y0,bbox.x1-bbox.x0,bbox.y1-bbox.y0,0,0,croppedCanvas.width,croppedCanvas.height);return croppedCanvas}isDirty(options){const{canvas,threshold=127.5,majorColorThreshold=0.97}=options;let whiteCount=0;let blackCount=0;let borderlessCanvas=this.crop({bbox:{x0:canvas.width*0.1,y0:canvas.height*0.1,x1:canvas.width*0.9,y1:canvas.height*0.9},canvas});let ctx=borderlessCanvas.getContext("2d");let colorData=ctx.getImageData(0,0,borderlessCanvas.width,borderlessCanvas.height).data;for(let i=0;i<colorData.length;i+=4){let red=colorData[i];let green=colorData[i+1];let blue=colorData[i+2];if(red>=threshold&&green>=threshold&&blue>=threshold){whiteCount++}else{blackCount++}}let majorColorRatio=Math.max(whiteCount,blackCount)/(blackCount+whiteCount);return majorColorRatio<majorColorThreshold}saveImage(options){const{canvas,filename,path="out"}=options;let folderPath=join(process.cwd(),path);if(!existsSync(folderPath)){mkdirSync(folderPath,{recursive:true})}let filePath=join(folderPath,`${this.step++}. ${filename}.png`);let out=createWriteStream(filePath);let buffer=canvas.toBuffer("image/png");return new Promise((res,rej)=>{out.write(buffer,(err)=>{if(err){rej(err)}else{res()}})})}clearOutput(path="out"){let folderPath=join(process.cwd(),path);if(existsSync(folderPath)){let files=readdirSync(folderPath);for(let file of files){if(file===".gitignore")continue;let filePath=join(folderPath,file);unlinkSync(filePath)}}}drawLine(options){const{ctx,x,y,width,height,lineWidth=2,color="blue"}=options;ctx.beginPath();ctx.strokeStyle=color;ctx.lineWidth=lineWidth;ctx.strokeRect(x,y,width,height);ctx.closePath()}drawContour(options){const{ctx,contour,strokeStyle="red",lineWidth=2}=options;let pts=contour.data32S;if(pts.length<4)return;ctx.strokeStyle=strokeStyle;ctx.lineWidth=lineWidth;ctx.beginPath();ctx.moveTo(pts[0],pts[1]);for(let i=2;i<pts.length;i+=2){ctx.lineTo(pts[i],pts[i+1])}ctx.closePath();ctx.stroke()}}import{createCanvas}from"./index";import{createWriteStream,existsSync,mkdirSync,readdirSync,unlinkSync}from"fs";import{join}from"path";
|
|
1
|
+
export class CanvasToolkit{static instance=null;step=0;constructor(){}static getInstance(){if(!CanvasToolkit.instance){CanvasToolkit.instance=new CanvasToolkit}return CanvasToolkit.instance}crop(options){const{bbox,canvas}=options;let croppedCanvas=createCanvas(bbox.x1-bbox.x0,bbox.y1-bbox.y0);let croppedCtx=croppedCanvas.getContext("2d");croppedCtx.drawImage(canvas,bbox.x0,bbox.y0,bbox.x1-bbox.x0,bbox.y1-bbox.y0,0,0,croppedCanvas.width,croppedCanvas.height);return croppedCanvas}isDirty(options){const{canvas,threshold=127.5,majorColorThreshold=0.97}=options;let whiteCount=0;let blackCount=0;let borderlessCanvas=this.crop({bbox:{x0:canvas.width*0.1,y0:canvas.height*0.1,x1:canvas.width*0.9,y1:canvas.height*0.9},canvas});let ctx=borderlessCanvas.getContext("2d");let colorData=ctx.getImageData(0,0,borderlessCanvas.width,borderlessCanvas.height).data;for(let i=0;i<colorData.length;i+=4){let red=colorData[i];let green=colorData[i+1];let blue=colorData[i+2];if(red>=threshold&&green>=threshold&&blue>=threshold){whiteCount++}else{blackCount++}}let majorColorRatio=Math.max(whiteCount,blackCount)/(blackCount+whiteCount);return majorColorRatio<majorColorThreshold}saveImage(options){const{canvas,filename,path="out"}=options;let folderPath=join(process.cwd(),path);if(!existsSync(folderPath)){mkdirSync(folderPath,{recursive:true})}let filePath=join(folderPath,`${this.step++}. ${filename}.png`);let out=createWriteStream(filePath);let buffer=canvas.toBuffer("image/png");return new Promise((res,rej)=>{out.write(buffer,(err)=>{if(err){rej(err)}else{res()}})})}clearOutput(path="out"){let folderPath=join(process.cwd(),path);if(existsSync(folderPath)){let files=readdirSync(folderPath);for(let file of files){if(file===".gitignore")continue;let filePath=join(folderPath,file);unlinkSync(filePath)}}}drawLine(options){const{ctx,x,y,width,height,lineWidth=2,color="blue"}=options;ctx.beginPath();ctx.strokeStyle=color;ctx.lineWidth=lineWidth;ctx.strokeRect(x,y,width,height);ctx.closePath()}drawContour(options){const{ctx,contour,strokeStyle="red",lineWidth=2}=options;let pts=contour.data32S;if(pts.length<4)return;ctx.strokeStyle=strokeStyle;ctx.lineWidth=lineWidth;ctx.beginPath();ctx.moveTo(pts[0],pts[1]);for(let i=2;i<pts.length;i+=2){ctx.lineTo(pts[i],pts[i+1])}ctx.closePath();ctx.stroke()}}import{createCanvas}from"./index.js";import{createWriteStream,existsSync,mkdirSync,readdirSync,unlinkSync}from"fs";import{join}from"path";
|
package/contours.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { BoundingBox, Canvas, Points } from "./index";
|
|
2
|
-
import { cv } from "./index";
|
|
1
|
+
import type { BoundingBox, Canvas, Points } from "./index.js";
|
|
2
|
+
import { cv } from "./index.js";
|
|
3
3
|
export interface ContoursOptions {
|
|
4
4
|
/** The contour retrieval mode. (cv.RETR_...) */
|
|
5
5
|
mode: cv.RetrievalModes;
|
package/contours.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export class Contours{contours;constructor(img,options={}){let opts={...defaultOptions(),...options};if(img instanceof cv.Mat){let contours=new cv.MatVector;let hierarchy=new cv.Mat;try{cv.findContours(img,contours,hierarchy,opts.mode,opts.method)}catch(error){throw error}hierarchy.delete();this.contours=contours}else{throw new Error("Invalid img type. Must be cv.Mat.")}}getAll(){return this.contours}getSize(){return this.contours.size()}getFromIndex(index){if(index<this.contours.size()){return this.contours.get(index)}return new cv.Mat}getRect(contour){return cv.boundingRect(contour)}iterate(callback){for(let i=0,len=this.contours.size();i<len;i++){let contour=this.contours.get(i);callback(contour)}return this}getLargestContourArea(){let maxArea=0;let largestContour=null;this.iterate((contour)=>{let area=cv.contourArea(contour);if(area>maxArea){maxArea=area;largestContour=contour}});return largestContour}getCornerPoints(options){const{canvas,contour=this.getLargestContourArea()}=options;let bbox={x0:0,y0:0,x1:canvas.width,y1:canvas.height};if(!contour){return{points:{topLeft:{x:bbox.x0,y:bbox.y0},topRight:{x:bbox.x1,y:bbox.y0},bottomLeft:{x:bbox.x0,y:bbox.y1},bottomRight:{x:bbox.x1,y:bbox.y1}},bbox}}let rect=cv.minAreaRect(contour);let vertices=cv.RotatedRect.points(rect);let points={topLeft:{x:0,y:0},topRight:{x:0,y:0},bottomRight:{x:0,y:0},bottomLeft:{x:0,y:0}};let sums=vertices.map((pt)=>pt.x+pt.y);let diffs=vertices.map((pt)=>pt.y-pt.x);let topLeftIdx=sums.indexOf(Math.min(...sums));let topRightIdx=diffs.indexOf(Math.min(...diffs));let bottomRightIdx=sums.indexOf(Math.max(...sums));let bottomLeftIdx=diffs.indexOf(Math.max(...diffs));if(!vertices[topLeftIdx]||!vertices[topRightIdx]||!vertices[bottomRightIdx]||!vertices[bottomLeftIdx]){return{points:{topLeft:{x:bbox.x0,y:bbox.y0},topRight:{x:bbox.x1,y:bbox.y0},bottomLeft:{x:bbox.x0,y:bbox.y1},bottomRight:{x:bbox.x1,y:bbox.y1}},bbox}}points.topLeft={x:vertices[topLeftIdx].x,y:vertices[topLeftIdx].y};points.topRight={x:vertices[topRightIdx].x,y:vertices[topRightIdx].y};points.bottomRight={x:vertices[bottomRightIdx].x,y:vertices[bottomRightIdx].y};points.bottomLeft={x:vertices[bottomLeftIdx].x,y:vertices[bottomLeftIdx].y};contour.delete();let ensureInBounds=(p)=>{p.x=Math.max(0,Math.min(canvas.width,p.x));p.y=Math.max(0,Math.min(canvas.height,p.y));return p};points.topLeft=ensureInBounds(points.topLeft);points.topRight=ensureInBounds(points.topRight);points.bottomLeft=ensureInBounds(points.bottomLeft);points.bottomRight=ensureInBounds(points.bottomRight);return{points,bbox}}getApproximateRectangleContour(options){const{threshold=0.02,contour=this.getLargestContourArea()}=options??{};if(!contour)return;let epsilon=threshold*cv.arcLength(contour,true);let approxContour=new cv.Mat;cv.approxPolyDP(contour,approxContour,epsilon,true);contour.delete();return approxContour}destroy(){try{this.contours.delete()}catch(error){}}}import{cv}from"./index";function defaultOptions(){return{mode:cv.RETR_EXTERNAL,method:cv.CHAIN_APPROX_SIMPLE}}
|
|
1
|
+
export class Contours{contours;constructor(img,options={}){let opts={...defaultOptions(),...options};if(img instanceof cv.Mat){let contours=new cv.MatVector;let hierarchy=new cv.Mat;try{cv.findContours(img,contours,hierarchy,opts.mode,opts.method)}catch(error){throw error}hierarchy.delete();this.contours=contours}else{throw new Error("Invalid img type. Must be cv.Mat.")}}getAll(){return this.contours}getSize(){return this.contours.size()}getFromIndex(index){if(index<this.contours.size()){return this.contours.get(index)}return new cv.Mat}getRect(contour){return cv.boundingRect(contour)}iterate(callback){for(let i=0,len=this.contours.size();i<len;i++){let contour=this.contours.get(i);callback(contour)}return this}getLargestContourArea(){let maxArea=0;let largestContour=null;this.iterate((contour)=>{let area=cv.contourArea(contour);if(area>maxArea){maxArea=area;largestContour=contour}});return largestContour}getCornerPoints(options){const{canvas,contour=this.getLargestContourArea()}=options;let bbox={x0:0,y0:0,x1:canvas.width,y1:canvas.height};if(!contour){return{points:{topLeft:{x:bbox.x0,y:bbox.y0},topRight:{x:bbox.x1,y:bbox.y0},bottomLeft:{x:bbox.x0,y:bbox.y1},bottomRight:{x:bbox.x1,y:bbox.y1}},bbox}}let rect=cv.minAreaRect(contour);let vertices=cv.RotatedRect.points(rect);let points={topLeft:{x:0,y:0},topRight:{x:0,y:0},bottomRight:{x:0,y:0},bottomLeft:{x:0,y:0}};let sums=vertices.map((pt)=>pt.x+pt.y);let diffs=vertices.map((pt)=>pt.y-pt.x);let topLeftIdx=sums.indexOf(Math.min(...sums));let topRightIdx=diffs.indexOf(Math.min(...diffs));let bottomRightIdx=sums.indexOf(Math.max(...sums));let bottomLeftIdx=diffs.indexOf(Math.max(...diffs));if(!vertices[topLeftIdx]||!vertices[topRightIdx]||!vertices[bottomRightIdx]||!vertices[bottomLeftIdx]){return{points:{topLeft:{x:bbox.x0,y:bbox.y0},topRight:{x:bbox.x1,y:bbox.y0},bottomLeft:{x:bbox.x0,y:bbox.y1},bottomRight:{x:bbox.x1,y:bbox.y1}},bbox}}points.topLeft={x:vertices[topLeftIdx].x,y:vertices[topLeftIdx].y};points.topRight={x:vertices[topRightIdx].x,y:vertices[topRightIdx].y};points.bottomRight={x:vertices[bottomRightIdx].x,y:vertices[bottomRightIdx].y};points.bottomLeft={x:vertices[bottomLeftIdx].x,y:vertices[bottomLeftIdx].y};contour.delete();let ensureInBounds=(p)=>{p.x=Math.max(0,Math.min(canvas.width,p.x));p.y=Math.max(0,Math.min(canvas.height,p.y));return p};points.topLeft=ensureInBounds(points.topLeft);points.topRight=ensureInBounds(points.topRight);points.bottomLeft=ensureInBounds(points.bottomLeft);points.bottomRight=ensureInBounds(points.bottomRight);return{points,bbox}}getApproximateRectangleContour(options){const{threshold=0.02,contour=this.getLargestContourArea()}=options??{};if(!contour)return;let epsilon=threshold*cv.arcLength(contour,true);let approxContour=new cv.Mat;cv.approxPolyDP(contour,approxContour,epsilon,true);contour.delete();return approxContour}destroy(){try{this.contours.delete()}catch(error){}}}import{cv}from"./index.js";function defaultOptions(){return{mode:cv.RETR_EXTERNAL,method:cv.CHAIN_APPROX_SIMPLE}}
|
package/image-analysis.d.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* !IMPORTANT: Ensure ImageProcessor.initRuntime() has been called successfully
|
|
4
4
|
* once before using any functions from this module.
|
|
5
5
|
*/
|
|
6
|
-
import type { Canvas } from "./index";
|
|
6
|
+
import type { Canvas } from "./index.js";
|
|
7
7
|
/**
|
|
8
8
|
* Options for calculating mean Lab lightness.
|
|
9
9
|
*/
|
package/image-analysis.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ImageProcessor,cv}from"./index";export function calculateMeanNormalizedLabLightness(options){const{canvas,dimension}=options;let processor=null;let resized=null;let labImg=null;let channels=null;let L=null;let mask=null;let scalarMat=null;try{processor=new ImageProcessor(canvas);resized=processor.execute("resize",{width:dimension.width,height:dimension.height}).toMat();labImg=new cv.Mat;cv.cvtColor(resized,labImg,cv.COLOR_BGR2Lab);channels=new cv.MatVector;cv.split(labImg,channels);L=channels.get(0);mask=new cv.Mat;let maxLocResult=cv.minMaxLoc(L,mask);let maxPixelValue=maxLocResult.maxVal;if(maxPixelValue===0){return 0}scalarMat=new cv.Mat(L.rows,L.cols,L.type(),new cv.Scalar(maxPixelValue));cv.divide(L,scalarMat,L,1,-1);let meanL=cv.mean(L)[0];return meanL??0}finally{processor?.destroy();labImg?.delete();channels?.delete();L?.delete();mask?.delete();scalarMat?.delete()}}export function calculateMeanGrayscaleValue(canvas){let processor=null;let grayscaleImg=null;try{processor=new ImageProcessor(canvas);grayscaleImg=processor.blur().grayscale().toMat();let mean=cv.mean(grayscaleImg)[0];return mean??0}finally{processor?.destroy()}}
|
|
1
|
+
import{ImageProcessor,cv}from"./index.js";export function calculateMeanNormalizedLabLightness(options){const{canvas,dimension}=options;let processor=null;let resized=null;let labImg=null;let channels=null;let L=null;let mask=null;let scalarMat=null;try{processor=new ImageProcessor(canvas);resized=processor.execute("resize",{width:dimension.width,height:dimension.height}).toMat();labImg=new cv.Mat;cv.cvtColor(resized,labImg,cv.COLOR_BGR2Lab);channels=new cv.MatVector;cv.split(labImg,channels);L=channels.get(0);mask=new cv.Mat;let maxLocResult=cv.minMaxLoc(L,mask);let maxPixelValue=maxLocResult.maxVal;if(maxPixelValue===0){return 0}scalarMat=new cv.Mat(L.rows,L.cols,L.type(),new cv.Scalar(maxPixelValue));cv.divide(L,scalarMat,L,1,-1);let meanL=cv.mean(L)[0];return meanL??0}finally{processor?.destroy();labImg?.delete();channels?.delete();L?.delete();mask?.delete();scalarMat?.delete()}}export function calculateMeanGrayscaleValue(canvas){let processor=null;let grayscaleImg=null;try{processor=new ImageProcessor(canvas);grayscaleImg=processor.blur().grayscale().toMat();let mean=cv.mean(grayscaleImg)[0];return mean??0}finally{processor?.destroy()}}
|
package/image-processor.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Canvas, cv } from "./index";
|
|
2
|
-
import type { AdaptiveThresholdOptions, BlurOptions, BorderOptions, CannyOptions, DilateOptions, ErodeOptions, GrayscaleOptions, InvertOptions, MorphologicalGradientOptions, OperationName, OperationOptions, RequiredOptions, ResizeOptions, RotateOptions, ThresholdOptions, WarpOptions } from "./index";
|
|
3
|
-
import type { ConvertOptions } from "./pipeline";
|
|
1
|
+
import { Canvas, cv } from "./index.js";
|
|
2
|
+
import type { AdaptiveThresholdOptions, BlurOptions, BorderOptions, CannyOptions, DilateOptions, ErodeOptions, GrayscaleOptions, InvertOptions, MorphologicalGradientOptions, OperationName, OperationOptions, RequiredOptions, ResizeOptions, RotateOptions, ThresholdOptions, WarpOptions } from "./index.js";
|
|
3
|
+
import type { ConvertOptions } from "./pipeline/index.js";
|
|
4
4
|
type NameWithRequiredOptions = {
|
|
5
5
|
[N in OperationName]: OperationOptions<N> extends RequiredOptions ? N : never;
|
|
6
6
|
}[OperationName];
|
package/image-processor.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export class ImageProcessor{img;width;height;constructor(source){if(source instanceof Canvas){let ctx=source.getContext("2d");let imageData=ctx.getImageData(0,0,source.width,source.height);this.img=cv.matFromImageData(imageData);this.width=source.width;this.height=source.height}else if(source instanceof cv.Mat){this.img=source;this.width=source.cols;this.height=source.rows}else{throw new Error("Invalid source type. Must be either Canvas or cv.Mat.")}}static async prepareCanvas(file){if(file instanceof Canvas)return file;let img=await loadImage(file);let canvas=createCanvas(img.width,img.height);let ctx=canvas.getContext("2d");ctx.drawImage(img,0,0);return canvas}static async prepareBuffer(canvas){if(canvas instanceof ArrayBuffer)return canvas;if(typeof canvas.toBuffer==="function"){let buffer=canvas.toBuffer("image/png");let arrayBuffer=new ArrayBuffer(buffer.byteLength);new Uint8Array(arrayBuffer).set(new Uint8Array(buffer));return arrayBuffer}if(typeof canvas.toDataURL==="function"){let dataURL=canvas.toDataURL("image/png");let base64Data=dataURL.replace(/^data:image\/png;base64,/,"");let buffer=Buffer.from(base64Data,"base64");let arrayBuffer=new ArrayBuffer(buffer.byteLength);new Uint8Array(arrayBuffer).set(new Uint8Array(buffer));return arrayBuffer}let ctx=canvas.getContext("2d");let imageData=ctx.getImageData(0,0,canvas.width,canvas.height);let canvasBuffer=new ArrayBuffer(imageData.data.byteLength);new Uint8Array(canvasBuffer).set(new Uint8Array(imageData.data.buffer,imageData.data.byteOffset,imageData.data.byteLength));return canvasBuffer}static async initRuntime(){return new Promise((res)=>{if(cv&&cv.Mat){res()}else{cv["onRuntimeInitialized"]=()=>{res()}}})}execute(operationName,options){if(!registry.hasOperation(operationName)){throw new Error(`Operation "${operationName}" not found`)}try{let result=executeOperation(operationName,this.img,options);this.img=result.img;this.width=result.width;this.height=result.height}catch(error){console.error(`Error executing operation "${operationName}":`,error);throw error}return this}grayscale(options={}){return this.execute("grayscale",options)}invert(options={}){return this.execute("invert",options)}border(options={}){return this.execute("border",options)}blur(options={}){return this.execute("blur",options)}threshold(options={}){return this.execute("threshold",options)}adaptiveThreshold(options={}){return this.execute("adaptiveThreshold",options)}canny(options={}){return this.execute("canny",options)}morphologicalGradient(options={}){return this.execute("morphologicalGradient",options)}erode(options={}){return this.execute("erode",options)}dilate(options={}){return this.execute("dilate",options)}resize(options){return this.execute("resize",options)}warp(options){return this.execute("warp",options)}rotate(options){return this.execute("rotate",options)}convert(options){return this.execute("convert",options)}destroy(){this.img.delete()}toMat(){return this.img}toCanvas(){let canvas=createCanvas(this.width,this.height);let ctx=canvas.getContext("2d");let imgData=ctx.createImageData(this.width,this.height);if(this.img.channels()===1){let data=imgData.data;let gray=new Uint8Array(this.img.data);for(let i=0;i<gray.length;i++){data[i*4]=gray[i];data[i*4+1]=gray[i];data[i*4+2]=gray[i];data[i*4+3]=255}}else{imgData.data.set(new Uint8ClampedArray(this.img.data))}ctx.putImageData(imgData,0,0);return canvas}}import{Canvas,createCanvas,cv,loadImage}from"./index";import{executeOperation,registry}from"./index";
|
|
1
|
+
export class ImageProcessor{img;width;height;constructor(source){if(source instanceof Canvas){let ctx=source.getContext("2d");let imageData=ctx.getImageData(0,0,source.width,source.height);this.img=cv.matFromImageData(imageData);this.width=source.width;this.height=source.height}else if(source instanceof cv.Mat){this.img=source;this.width=source.cols;this.height=source.rows}else{throw new Error("Invalid source type. Must be either Canvas or cv.Mat.")}}static async prepareCanvas(file){if(file instanceof Canvas)return file;let img=await loadImage(file);let canvas=createCanvas(img.width,img.height);let ctx=canvas.getContext("2d");ctx.drawImage(img,0,0);return canvas}static async prepareBuffer(canvas){if(canvas instanceof ArrayBuffer)return canvas;if(typeof canvas.toBuffer==="function"){let buffer=canvas.toBuffer("image/png");let arrayBuffer=new ArrayBuffer(buffer.byteLength);new Uint8Array(arrayBuffer).set(new Uint8Array(buffer));return arrayBuffer}if(typeof canvas.toDataURL==="function"){let dataURL=canvas.toDataURL("image/png");let base64Data=dataURL.replace(/^data:image\/png;base64,/,"");let buffer=Buffer.from(base64Data,"base64");let arrayBuffer=new ArrayBuffer(buffer.byteLength);new Uint8Array(arrayBuffer).set(new Uint8Array(buffer));return arrayBuffer}let ctx=canvas.getContext("2d");let imageData=ctx.getImageData(0,0,canvas.width,canvas.height);let canvasBuffer=new ArrayBuffer(imageData.data.byteLength);new Uint8Array(canvasBuffer).set(new Uint8Array(imageData.data.buffer,imageData.data.byteOffset,imageData.data.byteLength));return canvasBuffer}static async initRuntime(){return new Promise((res)=>{if(cv&&cv.Mat){res()}else{cv["onRuntimeInitialized"]=()=>{res()}}})}execute(operationName,options){if(!registry.hasOperation(operationName)){throw new Error(`Operation "${operationName}" not found`)}try{let result=executeOperation(operationName,this.img,options);this.img=result.img;this.width=result.width;this.height=result.height}catch(error){console.error(`Error executing operation "${operationName}":`,error);throw error}return this}grayscale(options={}){return this.execute("grayscale",options)}invert(options={}){return this.execute("invert",options)}border(options={}){return this.execute("border",options)}blur(options={}){return this.execute("blur",options)}threshold(options={}){return this.execute("threshold",options)}adaptiveThreshold(options={}){return this.execute("adaptiveThreshold",options)}canny(options={}){return this.execute("canny",options)}morphologicalGradient(options={}){return this.execute("morphologicalGradient",options)}erode(options={}){return this.execute("erode",options)}dilate(options={}){return this.execute("dilate",options)}resize(options){return this.execute("resize",options)}warp(options){return this.execute("warp",options)}rotate(options){return this.execute("rotate",options)}convert(options){return this.execute("convert",options)}destroy(){this.img.delete()}toMat(){return this.img}toCanvas(){let canvas=createCanvas(this.width,this.height);let ctx=canvas.getContext("2d");let imgData=ctx.createImageData(this.width,this.height);if(this.img.channels()===1){let data=imgData.data;let gray=new Uint8Array(this.img.data);for(let i=0;i<gray.length;i++){data[i*4]=gray[i];data[i*4+1]=gray[i];data[i*4+2]=gray[i];data[i*4+3]=255}}else{imgData.data.set(new Uint8ClampedArray(this.img.data))}ctx.putImageData(imgData,0,0);return canvas}}import{Canvas,createCanvas,cv,loadImage}from"./index.js";import{executeOperation,registry}from"./index.js";
|
package/index.d.ts
CHANGED
|
@@ -2,11 +2,10 @@ import cv from "@techstark/opencv-js";
|
|
|
2
2
|
export { cv };
|
|
3
3
|
export { Canvas, createCanvas, ImageData, loadImage } from "@napi-rs/canvas";
|
|
4
4
|
export type { SKRSContext2D } from "@napi-rs/canvas";
|
|
5
|
-
export type { BoundingBox, Coordinate, Points
|
|
6
|
-
export { executeOperation, OperationRegistry, registry } from "./pipeline";
|
|
7
|
-
export { CanvasToolkit } from "./canvas-toolkit";
|
|
8
|
-
export { Contours } from "./contours";
|
|
9
|
-
export { calculateMeanGrayscaleValue, calculateMeanNormalizedLabLightness, type CalculateMeanLightnessOptions, } from "./image-analysis";
|
|
10
|
-
export { ImageProcessor } from "./image-processor";
|
|
11
|
-
export {
|
|
12
|
-
export type { AdaptiveThresholdOptions, BlurOptions, BorderOptions, CannyOptions, DilateOptions, ErodeOptions, GrayscaleOptions, InvertOptions, MorphologicalGradientOptions, OperationFunction, OperationName, OperationOptions, OperationResult, PartialOptions, RegisteredOperations, RequiredOptions, ResizeOptions, RotateOptions, ThresholdOptions, WarpOptions, } from "./pipeline";
|
|
5
|
+
export type { BoundingBox, Coordinate, Points } from "./index.interface.js";
|
|
6
|
+
export { executeOperation, OperationRegistry, registry, } from "./pipeline/index.js";
|
|
7
|
+
export { CanvasToolkit } from "./canvas-toolkit.js";
|
|
8
|
+
export { Contours } from "./contours.js";
|
|
9
|
+
export { calculateMeanGrayscaleValue, calculateMeanNormalizedLabLightness, type CalculateMeanLightnessOptions, } from "./image-analysis.js";
|
|
10
|
+
export { ImageProcessor } from "./image-processor.js";
|
|
11
|
+
export type { AdaptiveThresholdOptions, BlurOptions, BorderOptions, CannyOptions, DilateOptions, ErodeOptions, GrayscaleOptions, InvertOptions, MorphologicalGradientOptions, OperationFunction, OperationName, OperationOptions, OperationResult, PartialOptions, RegisteredOperations, RequiredOptions, ResizeOptions, RotateOptions, ThresholdOptions, WarpOptions, } from "./pipeline/index.js";
|
package/index.interface.d.ts
CHANGED
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import cv from"@techstark/opencv-js";export{cv};export{Canvas,createCanvas,ImageData,loadImage}from"@napi-rs/canvas";export{executeOperation,OperationRegistry,registry}from"./pipeline";export{CanvasToolkit}from"./canvas-toolkit";export{Contours}from"./contours";export{calculateMeanGrayscaleValue,calculateMeanNormalizedLabLightness}from"./image-analysis";export{ImageProcessor}from"./image-processor";
|
|
1
|
+
import cv from"@techstark/opencv-js";export{cv};export{Canvas,createCanvas,ImageData,loadImage}from"@napi-rs/canvas";export{executeOperation,OperationRegistry,registry}from"./pipeline/index.js";export{CanvasToolkit}from"./canvas-toolkit.js";export{Contours}from"./contours.js";export{calculateMeanGrayscaleValue,calculateMeanNormalizedLabLightness}from"./image-analysis.js";export{ImageProcessor}from"./image-processor.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { OperationResult, PartialOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { OperationResult, PartialOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
adaptiveThreshold: AdaptiveThresholdOptions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";function defaultOptions(){return{upper:255,method:cv.ADAPTIVE_THRESH_GAUSSIAN_C,type:cv.THRESH_BINARY_INV,size:7,constant:2}}export function adaptiveThreshold(img,options){let imgAdaptiveThreshold=new cv.Mat;cv.adaptiveThreshold(img,imgAdaptiveThreshold,options.upper,options.method,options.type,options.size,options.constant);img.delete();return{img:imgAdaptiveThreshold,width:imgAdaptiveThreshold.cols,height:imgAdaptiveThreshold.rows}}registry.register("adaptiveThreshold",adaptiveThreshold,defaultOptions);
|
|
1
|
+
import{cv,registry}from"../index.js";function defaultOptions(){return{upper:255,method:cv.ADAPTIVE_THRESH_GAUSSIAN_C,type:cv.THRESH_BINARY_INV,size:7,constant:2}}export function adaptiveThreshold(img,options){let imgAdaptiveThreshold=new cv.Mat;cv.adaptiveThreshold(img,imgAdaptiveThreshold,options.upper,options.method,options.type,options.size,options.constant);img.delete();return{img:imgAdaptiveThreshold,width:imgAdaptiveThreshold.cols,height:imgAdaptiveThreshold.rows}}registry.register("adaptiveThreshold",adaptiveThreshold,defaultOptions);
|
package/operations/blur.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { OperationResult, PartialOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { OperationResult, PartialOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
blur: BlurOptions;
|
package/operations/blur.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";function defaultOptions(){return{size:[5,5],sigma:0}}export function blur(img,options){let imgBlur=new cv.Mat;cv.GaussianBlur(img,imgBlur,new cv.Size(options.size[0],options.size[1]),options.sigma);img.delete();return{img:imgBlur,width:imgBlur.cols,height:imgBlur.rows}}registry.register("blur",blur,defaultOptions);
|
|
1
|
+
import{cv,registry}from"../index.js";function defaultOptions(){return{size:[5,5],sigma:0}}export function blur(img,options){let imgBlur=new cv.Mat;cv.GaussianBlur(img,imgBlur,new cv.Size(options.size[0],options.size[1]),options.sigma);img.delete();return{img:imgBlur,width:imgBlur.cols,height:imgBlur.rows}}registry.register("blur",blur,defaultOptions);
|
package/operations/border.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { OperationResult, PartialOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { OperationResult, PartialOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
border: BorderOptions;
|
package/operations/border.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";function defaultOptions(){return{size:10,borderType:cv.BORDER_CONSTANT,borderColor:[255,255,255,255]}}export function border(img,options){let imgBorder=new cv.Mat;cv.copyMakeBorder(img,imgBorder,options.size,options.size,options.size,options.size,options.borderType,options.borderColor);img.delete();return{img:imgBorder,width:imgBorder.cols,height:imgBorder.rows}}registry.register("border",border,defaultOptions);
|
|
1
|
+
import{cv,registry}from"../index.js";function defaultOptions(){return{size:10,borderType:cv.BORDER_CONSTANT,borderColor:[255,255,255,255]}}export function border(img,options){let imgBorder=new cv.Mat;cv.copyMakeBorder(img,imgBorder,options.size,options.size,options.size,options.size,options.borderType,options.borderColor);img.delete();return{img:imgBorder,width:imgBorder.cols,height:imgBorder.rows}}registry.register("border",border,defaultOptions);
|
package/operations/canny.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { OperationResult, PartialOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { OperationResult, PartialOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
canny: CannyOptions;
|
package/operations/canny.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";function defaultOptions(){return{lower:50,upper:150}}export function canny(img,options){let imgCanny=new cv.Mat;cv.Canny(img,imgCanny,options.lower,options.upper);img.delete();return{img:imgCanny,width:imgCanny.cols,height:imgCanny.rows}}registry.register("canny",canny,defaultOptions);
|
|
1
|
+
import{cv,registry}from"../index.js";function defaultOptions(){return{lower:50,upper:150}}export function canny(img,options){let imgCanny=new cv.Mat;cv.Canny(img,imgCanny,options.lower,options.upper);img.delete();return{img:imgCanny,width:imgCanny.cols,height:imgCanny.rows}}registry.register("canny",canny,defaultOptions);
|
package/operations/convert.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { OperationResult, RequiredOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { OperationResult, RequiredOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
convert: ConvertOptions;
|
package/operations/convert.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";export function convert(img,options){if(options.rtype===undefined){throw new Error("Invalid options: rtype is required")}let imgConvert=new cv.Mat;img.convertTo(imgConvert,options.rtype);img.delete();return{img:imgConvert,width:imgConvert.cols,height:imgConvert.rows}}registry.register("convert",convert);
|
|
1
|
+
import{cv,registry}from"../index.js";export function convert(img,options){if(options.rtype===undefined){throw new Error("Invalid options: rtype is required")}let imgConvert=new cv.Mat;img.convertTo(imgConvert,options.rtype);img.delete();return{img:imgConvert,width:imgConvert.cols,height:imgConvert.rows}}registry.register("convert",convert);
|
package/operations/dilate.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { OperationResult, PartialOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { OperationResult, PartialOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
dilate: DilateOptions;
|
package/operations/dilate.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";function defaultOptions(){return{size:[5,5],iter:1}}export function dilate(img,options){let imgDilate=new cv.Mat;let kernel=cv.getStructuringElement(cv.MORPH_RECT,new cv.Size(options.size[0],options.size[1]));cv.dilate(img,imgDilate,kernel,new cv.Point(-1,-1),options.iter);img.delete();return{img:imgDilate,width:imgDilate.cols,height:imgDilate.rows}}registry.register("dilate",dilate,defaultOptions);
|
|
1
|
+
import{cv,registry}from"../index.js";function defaultOptions(){return{size:[5,5],iter:1}}export function dilate(img,options){let imgDilate=new cv.Mat;let kernel=cv.getStructuringElement(cv.MORPH_RECT,new cv.Size(options.size[0],options.size[1]));cv.dilate(img,imgDilate,kernel,new cv.Point(-1,-1),options.iter);img.delete();return{img:imgDilate,width:imgDilate.cols,height:imgDilate.rows}}registry.register("dilate",dilate,defaultOptions);
|
package/operations/erode.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { OperationResult, PartialOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { OperationResult, PartialOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
erode: ErodeOptions;
|
package/operations/erode.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";function defaultOptions(){return{size:[5,5],iter:1}}export function erode(img,options){let imgErode=new cv.Mat;let kernel=cv.getStructuringElement(cv.MORPH_RECT,new cv.Size(options.size[0],options.size[1]));cv.erode(img,imgErode,kernel,new cv.Point(-1,-1),options.iter);img.delete();return{img:imgErode,width:imgErode.cols,height:imgErode.rows}}registry.register("erode",erode,defaultOptions);
|
|
1
|
+
import{cv,registry}from"../index.js";function defaultOptions(){return{size:[5,5],iter:1}}export function erode(img,options){let imgErode=new cv.Mat;let kernel=cv.getStructuringElement(cv.MORPH_RECT,new cv.Size(options.size[0],options.size[1]));cv.erode(img,imgErode,kernel,new cv.Point(-1,-1),options.iter);img.delete();return{img:imgErode,width:imgErode.cols,height:imgErode.rows}}registry.register("erode",erode,defaultOptions);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { OperationResult, PartialOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { OperationResult, PartialOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
grayscale: GrayscaleOptions;
|
package/operations/grayscale.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";function defaultOptions(){return{}}export function grayscale(img,options){let imgGrayscale=new cv.Mat;cv.cvtColor(img,imgGrayscale,cv.COLOR_RGBA2GRAY);img.delete();return{img:imgGrayscale,width:imgGrayscale.cols,height:imgGrayscale.rows}}registry.register("grayscale",grayscale,defaultOptions);
|
|
1
|
+
import{cv,registry}from"../index.js";function defaultOptions(){return{}}export function grayscale(img,options){let imgGrayscale=new cv.Mat;cv.cvtColor(img,imgGrayscale,cv.COLOR_RGBA2GRAY);img.delete();return{img:imgGrayscale,width:imgGrayscale.cols,height:imgGrayscale.rows}}registry.register("grayscale",grayscale,defaultOptions);
|
package/operations/invert.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { OperationResult, PartialOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { OperationResult, PartialOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
invert: InvertOptions;
|
package/operations/invert.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";function defaultOptions(){return{}}export function invert(img,options){let imgInvert=new cv.Mat;cv.bitwise_not(img,imgInvert);img.delete();return{img:imgInvert,width:imgInvert.cols,height:imgInvert.rows}}registry.register("invert",invert,defaultOptions);
|
|
1
|
+
import{cv,registry}from"../index.js";function defaultOptions(){return{}}export function invert(img,options){let imgInvert=new cv.Mat;cv.bitwise_not(img,imgInvert);img.delete();return{img:imgInvert,width:imgInvert.cols,height:imgInvert.rows}}registry.register("invert",invert,defaultOptions);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { OperationResult, PartialOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { OperationResult, PartialOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
morphologicalGradient: MorphologicalGradientOptions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";function defaultOptions(){return{size:[3,3]}}export function morphologicalGradient(img,options){let imgMorphologicalGradient=new cv.Mat;let kernel=cv.getStructuringElement(cv.MORPH_RECT,new cv.Size(options.size[0],options.size[1]));cv.morphologyEx(img,imgMorphologicalGradient,cv.MORPH_GRADIENT,kernel);img.delete();return{img:imgMorphologicalGradient,width:imgMorphologicalGradient.cols,height:imgMorphologicalGradient.rows}}registry.register("morphologicalGradient",morphologicalGradient,defaultOptions);
|
|
1
|
+
import{cv,registry}from"../index.js";function defaultOptions(){return{size:[3,3]}}export function morphologicalGradient(img,options){let imgMorphologicalGradient=new cv.Mat;let kernel=cv.getStructuringElement(cv.MORPH_RECT,new cv.Size(options.size[0],options.size[1]));cv.morphologyEx(img,imgMorphologicalGradient,cv.MORPH_GRADIENT,kernel);img.delete();return{img:imgMorphologicalGradient,width:imgMorphologicalGradient.cols,height:imgMorphologicalGradient.rows}}registry.register("morphologicalGradient",morphologicalGradient,defaultOptions);
|
package/operations/resize.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { OperationResult, RequiredOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { OperationResult, RequiredOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
resize: ResizeOptions;
|
package/operations/resize.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";export function resize(img,options){if(!options.width||!options.height){throw new Error("Invalid options: width and height are required")}let imgResize=new cv.Mat;cv.resize(img,imgResize,new cv.Size(options.width,options.height));img.delete();return{img:imgResize,width:imgResize.cols,height:imgResize.rows}}registry.register("resize",resize);
|
|
1
|
+
import{cv,registry}from"../index.js";export function resize(img,options){if(!options.width||!options.height){throw new Error("Invalid options: width and height are required")}let imgResize=new cv.Mat;cv.resize(img,imgResize,new cv.Size(options.width,options.height));img.delete();return{img:imgResize,width:imgResize.cols,height:imgResize.rows}}registry.register("resize",resize);
|
package/operations/rotate.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { OperationResult, RequiredOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { OperationResult, RequiredOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
rotate: RotateOptions;
|
package/operations/rotate.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";export function rotate(img,options){let center=options.center||new cv.Point(img.cols/2,img.rows/2);let M=cv.getRotationMatrix2D(center,options.angle,1);let dsize=new cv.Size(img.cols,img.rows);let rotatedImg=new cv.Mat;cv.warpAffine(img,rotatedImg,M,dsize,cv.INTER_LINEAR,cv.BORDER_CONSTANT,new cv.Scalar);img.delete();M.delete();return{img:rotatedImg,width:rotatedImg.cols,height:rotatedImg.rows}}registry.register("rotate",rotate);
|
|
1
|
+
import{cv,registry}from"../index.js";export function rotate(img,options){let center=options.center||new cv.Point(img.cols/2,img.rows/2);let M=cv.getRotationMatrix2D(center,options.angle,1);let dsize=new cv.Size(img.cols,img.rows);let rotatedImg=new cv.Mat;cv.warpAffine(img,rotatedImg,M,dsize,cv.INTER_LINEAR,cv.BORDER_CONSTANT,new cv.Scalar);img.delete();M.delete();return{img:rotatedImg,width:rotatedImg.cols,height:rotatedImg.rows}}registry.register("rotate",rotate);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { OperationResult, PartialOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { OperationResult, PartialOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
threshold: ThresholdOptions;
|
package/operations/threshold.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";function defaultOptions(){return{lower:0,upper:255,type:cv.THRESH_BINARY_INV+cv.THRESH_OTSU}}export function threshold(img,options){let imgThreshold=new cv.Mat;cv.threshold(img,imgThreshold,options.lower,options.upper,options.type);img.delete();return{img:imgThreshold,width:imgThreshold.cols,height:imgThreshold.rows}}registry.register("threshold",threshold,defaultOptions);
|
|
1
|
+
import{cv,registry}from"../index.js";function defaultOptions(){return{lower:0,upper:255,type:cv.THRESH_BINARY_INV+cv.THRESH_OTSU}}export function threshold(img,options){let imgThreshold=new cv.Mat;cv.threshold(img,imgThreshold,options.lower,options.upper,options.type);img.delete();return{img:imgThreshold,width:imgThreshold.cols,height:imgThreshold.rows}}registry.register("threshold",threshold,defaultOptions);
|
package/operations/warp.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { BoundingBox, OperationResult, Points, RequiredOptions } from "../index";
|
|
2
|
-
import { cv } from "../index";
|
|
1
|
+
import type { BoundingBox, OperationResult, Points, RequiredOptions } from "../index.js";
|
|
2
|
+
import { cv } from "../index.js";
|
|
3
3
|
declare module "../index" {
|
|
4
4
|
interface RegisteredOperations {
|
|
5
5
|
warp: WarpOptions;
|
package/operations/warp.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cv,registry}from"../index";export function warp(img,options){if(!options.points||!options.bbox){throw new Error("Invalid options: points and bbox are required")}const{points,bbox}=options;let imgWarp=new cv.Mat;let targetWidth=bbox.x1-bbox.x0;let targetHeight=bbox.y1-bbox.y0;let destArray=[0,0,targetWidth-1,0,targetWidth-1,targetHeight-1,0,targetHeight-1];let srcArray=[points.topLeft.x,points.topLeft.y,points.topRight.x,points.topRight.y,points.bottomRight.x,points.bottomRight.y,points.bottomLeft.x,points.bottomLeft.y];let dest=cv.matFromArray(4,1,cv.CV_32FC2,destArray);let src=cv.matFromArray(4,1,cv.CV_32FC2,srcArray);let M=cv.getPerspectiveTransform(src,dest);let dsize=new cv.Size(targetWidth,targetHeight);cv.warpPerspective(img,imgWarp,M,dsize);M.delete();src.delete();dest.delete();img.delete();return{img:imgWarp,width:imgWarp.cols,height:imgWarp.rows}}registry.register("warp",warp);
|
|
1
|
+
import{cv,registry}from"../index.js";export function warp(img,options){if(!options.points||!options.bbox){throw new Error("Invalid options: points and bbox are required")}const{points,bbox}=options;let imgWarp=new cv.Mat;let targetWidth=bbox.x1-bbox.x0;let targetHeight=bbox.y1-bbox.y0;let destArray=[0,0,targetWidth-1,0,targetWidth-1,targetHeight-1,0,targetHeight-1];let srcArray=[points.topLeft.x,points.topLeft.y,points.topRight.x,points.topRight.y,points.bottomRight.x,points.bottomRight.y,points.bottomLeft.x,points.bottomLeft.y];let dest=cv.matFromArray(4,1,cv.CV_32FC2,destArray);let src=cv.matFromArray(4,1,cv.CV_32FC2,srcArray);let M=cv.getPerspectiveTransform(src,dest);let dsize=new cv.Size(targetWidth,targetHeight);cv.warpPerspective(img,imgWarp,M,dsize);M.delete();src.delete();dest.delete();img.delete();return{img:imgWarp,width:imgWarp.cols,height:imgWarp.rows}}registry.register("warp",warp);
|
package/package.json
CHANGED
package/pipeline/index.d.ts
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
export { executeOperation, OperationRegistry, registry } from "./registry";
|
|
2
|
-
export type { OperationFunction, OperationName, OperationOptions, OperationResult, PartialOptions, RegisteredOperations, RequiredOptions, } from "./types";
|
|
3
|
-
import "../operations/adaptive-threshold";
|
|
4
|
-
import "../operations/blur";
|
|
5
|
-
import "../operations/border";
|
|
6
|
-
import "../operations/canny";
|
|
7
|
-
import "../operations/convert";
|
|
8
|
-
import "../operations/dilate";
|
|
9
|
-
import "../operations/erode";
|
|
10
|
-
import "../operations/grayscale";
|
|
11
|
-
import "../operations/invert";
|
|
12
|
-
import "../operations/morphological-gradient";
|
|
13
|
-
import "../operations/resize";
|
|
14
|
-
import "../operations/rotate";
|
|
15
|
-
import "../operations/threshold";
|
|
16
|
-
import "../operations/warp";
|
|
17
|
-
export type { AdaptiveThresholdOptions } from "../operations/adaptive-threshold";
|
|
18
|
-
export type { BlurOptions } from "../operations/blur";
|
|
19
|
-
export type { BorderOptions } from "../operations/border";
|
|
20
|
-
export type { CannyOptions } from "../operations/canny";
|
|
21
|
-
export type { ConvertOptions } from "../operations/convert";
|
|
22
|
-
export type { DilateOptions } from "../operations/dilate";
|
|
23
|
-
export type { ErodeOptions } from "../operations/erode";
|
|
24
|
-
export type { GrayscaleOptions } from "../operations/grayscale";
|
|
25
|
-
export type { InvertOptions } from "../operations/invert";
|
|
26
|
-
export type { MorphologicalGradientOptions } from "../operations/morphological-gradient";
|
|
27
|
-
export type { ResizeOptions } from "../operations/resize";
|
|
28
|
-
export type { RotateOptions } from "../operations/rotate";
|
|
29
|
-
export type { ThresholdOptions } from "../operations/threshold";
|
|
30
|
-
export type { WarpOptions } from "../operations/warp";
|
|
1
|
+
export { executeOperation, OperationRegistry, registry } from "./registry.js";
|
|
2
|
+
export type { OperationFunction, OperationName, OperationOptions, OperationResult, PartialOptions, RegisteredOperations, RequiredOptions, } from "./types.js";
|
|
3
|
+
import "../operations/adaptive-threshold.js";
|
|
4
|
+
import "../operations/blur.js";
|
|
5
|
+
import "../operations/border.js";
|
|
6
|
+
import "../operations/canny.js";
|
|
7
|
+
import "../operations/convert.js";
|
|
8
|
+
import "../operations/dilate.js";
|
|
9
|
+
import "../operations/erode.js";
|
|
10
|
+
import "../operations/grayscale.js";
|
|
11
|
+
import "../operations/invert.js";
|
|
12
|
+
import "../operations/morphological-gradient.js";
|
|
13
|
+
import "../operations/resize.js";
|
|
14
|
+
import "../operations/rotate.js";
|
|
15
|
+
import "../operations/threshold.js";
|
|
16
|
+
import "../operations/warp.js";
|
|
17
|
+
export type { AdaptiveThresholdOptions } from "../operations/adaptive-threshold.js";
|
|
18
|
+
export type { BlurOptions } from "../operations/blur.js";
|
|
19
|
+
export type { BorderOptions } from "../operations/border.js";
|
|
20
|
+
export type { CannyOptions } from "../operations/canny.js";
|
|
21
|
+
export type { ConvertOptions } from "../operations/convert.js";
|
|
22
|
+
export type { DilateOptions } from "../operations/dilate.js";
|
|
23
|
+
export type { ErodeOptions } from "../operations/erode.js";
|
|
24
|
+
export type { GrayscaleOptions } from "../operations/grayscale.js";
|
|
25
|
+
export type { InvertOptions } from "../operations/invert.js";
|
|
26
|
+
export type { MorphologicalGradientOptions } from "../operations/morphological-gradient.js";
|
|
27
|
+
export type { ResizeOptions } from "../operations/resize.js";
|
|
28
|
+
export type { RotateOptions } from "../operations/rotate.js";
|
|
29
|
+
export type { ThresholdOptions } from "../operations/threshold.js";
|
|
30
|
+
export type { WarpOptions } from "../operations/warp.js";
|
package/pipeline/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{executeOperation,OperationRegistry,registry}from"./registry";import"../operations/adaptive-threshold";import"../operations/blur";import"../operations/border";import"../operations/canny";import"../operations/convert";import"../operations/dilate";import"../operations/erode";import"../operations/grayscale";import"../operations/invert";import"../operations/morphological-gradient";import"../operations/resize";import"../operations/rotate";import"../operations/threshold";import"../operations/warp";
|
|
1
|
+
export{executeOperation,OperationRegistry,registry}from"./registry.js";import"../operations/adaptive-threshold.js";import"../operations/blur.js";import"../operations/border.js";import"../operations/canny.js";import"../operations/convert.js";import"../operations/dilate.js";import"../operations/erode.js";import"../operations/grayscale.js";import"../operations/invert.js";import"../operations/morphological-gradient.js";import"../operations/resize.js";import"../operations/rotate.js";import"../operations/threshold.js";import"../operations/warp.js";
|
package/pipeline/registry.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { cv } from "../index";
|
|
2
|
-
import type { OperationFunction, OperationName, OperationOptions, OperationResult } from "./index";
|
|
1
|
+
import { cv } from "../index.js";
|
|
2
|
+
import type { OperationFunction, OperationName, OperationOptions, OperationResult } from "./index.js";
|
|
3
3
|
export declare class OperationRegistry {
|
|
4
4
|
private operations;
|
|
5
5
|
private defaultOptions;
|
package/face-detector.d.ts
DELETED
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import { Canvas } from "./index";
|
|
2
|
-
import type { BoundingBox, EyesDetectorResult, FaceDetectorResult } from "./index.interface";
|
|
3
|
-
export declare class FaceDetector {
|
|
4
|
-
private static instance;
|
|
5
|
-
private frontalFaceCascade;
|
|
6
|
-
private eyeCascade;
|
|
7
|
-
private eyeGlassCascade;
|
|
8
|
-
/**
|
|
9
|
-
* Private constructor to prevent direct instantiation
|
|
10
|
-
*/
|
|
11
|
-
private constructor();
|
|
12
|
-
/**
|
|
13
|
-
* Get the singleton instance of FaceDetector
|
|
14
|
-
* @returns The singleton instance
|
|
15
|
-
* @example
|
|
16
|
-
* const faceDetector = await FaceDetector.getInstance();
|
|
17
|
-
*/
|
|
18
|
-
static getInstance(): Promise<FaceDetector>;
|
|
19
|
-
/**
|
|
20
|
-
* Detect faces in the given canvas
|
|
21
|
-
* @param canvas Source canvas containing the image
|
|
22
|
-
* @param options Detection options
|
|
23
|
-
* @returns Promise resolving to detected faces
|
|
24
|
-
* @example
|
|
25
|
-
* const result = await faceDetector.detectFace(canvas);
|
|
26
|
-
* console.log(`Found ${result.faces.length} faces`);
|
|
27
|
-
*/
|
|
28
|
-
detectFace(canvas: Canvas, options?: {
|
|
29
|
-
scaleFactor?: number;
|
|
30
|
-
minNeighbors?: number;
|
|
31
|
-
minSize?: {
|
|
32
|
-
width: number;
|
|
33
|
-
height: number;
|
|
34
|
-
};
|
|
35
|
-
}): Promise<FaceDetectorResult>;
|
|
36
|
-
/**
|
|
37
|
-
* Detect eyes in the given canvas
|
|
38
|
-
* @param canvas Source canvas containing the image
|
|
39
|
-
* @param options Detection options
|
|
40
|
-
* @returns Promise resolving to detected eyes
|
|
41
|
-
* @example
|
|
42
|
-
* const result = await faceDetector.detectEye(canvas);
|
|
43
|
-
* console.log(`Found ${result.eyes.length} eye pairs`);
|
|
44
|
-
*/
|
|
45
|
-
detectEye(canvas: Canvas, options?: {
|
|
46
|
-
scaleFactor?: number;
|
|
47
|
-
minNeighbors?: number;
|
|
48
|
-
minSize?: {
|
|
49
|
-
width: number;
|
|
50
|
-
height: number;
|
|
51
|
-
};
|
|
52
|
-
useFallback?: boolean;
|
|
53
|
-
}): Promise<EyesDetectorResult>;
|
|
54
|
-
/**
|
|
55
|
-
* Detect eyes with glasses/sunglasses
|
|
56
|
-
* @param gray Grayscale cv.Mat image
|
|
57
|
-
* @param options Detection options
|
|
58
|
-
* @returns Detected eyes result
|
|
59
|
-
*/
|
|
60
|
-
private detectEyeSunglass;
|
|
61
|
-
/**
|
|
62
|
-
* Align face based on eye positions
|
|
63
|
-
* @param canvas Source canvas containing the face
|
|
64
|
-
* @param eyes Tuple of left and right eye bounding boxes
|
|
65
|
-
* @returns Promise resolving to aligned face canvas
|
|
66
|
-
* @example
|
|
67
|
-
* const aligned = await faceDetector.alignFace(canvas, [leftEye, rightEye]);
|
|
68
|
-
*/
|
|
69
|
-
alignFace(canvas: Canvas, eyes: [BoundingBox, BoundingBox]): Promise<Canvas>;
|
|
70
|
-
}
|
package/face-detector.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export class FaceDetector{static instance=null;frontalFaceCascade;eyeCascade;eyeGlassCascade;constructor(){let __dirname=dirname(fileURLToPath(import.meta.url));let frontalFaceData=readFileSync(join(__dirname,"haarcascade_frontalface_default.xml"));let eyeData=readFileSync(join(__dirname,"haarcascade_eye.xml"));let eyeGlassData=readFileSync(join(__dirname,"haarcascade_eye_tree_eyeglasses.xml"));cv.FS.writeFile("haarcascade_frontalface_default.xml",frontalFaceData);cv.FS.writeFile("haarcascade_eye.xml",eyeData);cv.FS.writeFile("haarcascade_eye_tree_eyeglasses.xml",eyeGlassData);this.frontalFaceCascade=new cv.CascadeClassifier;this.eyeCascade=new cv.CascadeClassifier;this.eyeGlassCascade=new cv.CascadeClassifier;this.frontalFaceCascade.load("haarcascade_frontalface_default.xml");this.eyeCascade.load("haarcascade_eye.xml");this.eyeGlassCascade.load("haarcascade_eye_tree_eyeglasses.xml")}static async getInstance(){await ImageProcessor.initRuntime();if(!FaceDetector.instance){FaceDetector.instance=new FaceDetector}return FaceDetector.instance}async detectFace(canvas,options={}){const{scaleFactor=1.1,minNeighbors=3,minSize={width:30,height:30}}=options;let processor=new ImageProcessor(canvas);let faces=new cv.RectVector;let minSizeMat=new cv.Size(minSize.width,minSize.height);let detectedFaces=[];try{let grayScaled=processor.grayscale().toMat();this.frontalFaceCascade.detectMultiScale(grayScaled,faces,scaleFactor,minNeighbors,0,minSizeMat);for(let i=0;i<faces.size();i++){let face=faces.get(i);detectedFaces.push({x0:face.x,y0:face.y,x1:face.x+face.width,y1:face.y+face.height})}}catch(error){}finally{faces.delete();processor.destroy()}return{faces:detectedFaces}}async detectEye(canvas,options={}){const{scaleFactor=1.05,minNeighbors=3,minSize={width:10,height:10},useFallback=true}=options;let processor=new ImageProcessor(canvas);let grayscaled=processor.grayscale().toMat();let eyes=new cv.RectVector;let minSizeMat=new cv.Size(minSize.width,minSize.height);let result;try{this.eyeCascade.detectMultiScale(grayscaled,eyes,scaleFactor,minNeighbors,0,minSizeMat);if(eyes.size()===0&&useFallback){let eyesWithGlasses=this.detectEyeSunglass(grayscaled,{scaleFactor,minNeighbors,minSize});result=eyesWithGlasses}else{let detectedEyes=[];let eyeArray=[];for(let i=0;i<eyes.size();i++){let eye=eyes.get(i);eyeArray.push({x0:eye.x,y0:eye.y,x1:eye.x+eye.width,y1:eye.y+eye.height})}eyeArray.sort((a,b)=>a.x0-b.x0);for(let i=0;i<eyeArray.length-1;i+=2){detectedEyes.push({left:eyeArray[i],right:eyeArray[i+1]})}result={eyes:detectedEyes}}}catch(error){console.error(`[detectEyes error]: `,error);result={eyes:[]}}finally{eyes.delete();processor.destroy()}return result}detectEyeSunglass(grayscale,options){const{scaleFactor,minNeighbors,minSize}=options;let eyes=new cv.RectVector;let minSizeMat=new cv.Size(minSize.width,minSize.height);this.eyeGlassCascade.detectMultiScale(grayscale,eyes,scaleFactor,minNeighbors,0,minSizeMat);let detectedEyes=[];let eyeArray=[];for(let i=0;i<eyes.size();i++){let eye=eyes.get(i);eyeArray.push({x0:eye.x,y0:eye.y,x1:eye.x+eye.width,y1:eye.y+eye.height})}eyeArray.sort((a,b)=>a.x0-b.x0);for(let i=0;i<eyeArray.length-1;i+=2){detectedEyes.push({left:eyeArray[i],right:eyeArray[i+1]})}return{eyes:detectedEyes}}async alignFace(canvas,eyes){const[leftEye,rightEye]=eyes;let leftEyeCenter={x:(leftEye.x0+leftEye.x1)/2,y:(leftEye.y0+leftEye.y1)/2};let rightEyeCenter={x:(rightEye.x0+rightEye.x1)/2,y:(rightEye.y0+rightEye.y1)/2};let deltaX=rightEyeCenter.x-leftEyeCenter.x;let deltaY=rightEyeCenter.y-leftEyeCenter.y;let angle=Math.atan2(deltaY,deltaX)*(180/Math.PI);let centerX=(leftEyeCenter.x+rightEyeCenter.x)/2;let centerY=(leftEyeCenter.y+rightEyeCenter.y)/2;let center=new cv.Point(centerX,centerY);let processor=new ImageProcessor(canvas);let rotated=processor.rotate({angle,center}).toCanvas();return rotated}}import{readFileSync}from"fs";import{dirname,join}from"path";import{fileURLToPath}from"url";import{cv,ImageProcessor}from"./index";
|