初次提交
This commit is contained in:
37
src/deploy/common/model.ts
Normal file
37
src/deploy/common/model.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import { backend } from "../../backend";
|
||||
import { cv } from "../../cv";
|
||||
|
||||
export type ModelConstructor<T> = new (session: backend.common.CommonSession) => T;
|
||||
|
||||
export type ImageSource = cv.Mat | Uint8Array | string;
|
||||
|
||||
export interface ImageCropOption {
|
||||
/** 图片裁剪区域 */
|
||||
crop?: { sx: number, sy: number, sw: number, sh: number }
|
||||
}
|
||||
|
||||
export abstract class Model {
|
||||
protected session: backend.common.CommonSession;
|
||||
|
||||
protected static async resolveImage<R>(image: ImageSource, resolver: (image: cv.Mat) => R | Promise<R>): Promise<R> {
|
||||
if (typeof image === "string") {
|
||||
if (/^https?:\/\//.test(image)) image = await fetch(image).then(res => res.arrayBuffer()).then(buffer => new Uint8Array(buffer));
|
||||
else image = await import("fs").then(fs => fs.promises.readFile(image as string));
|
||||
}
|
||||
if (image instanceof Uint8Array) image = new cv.Mat(image, { mode: cv.ImreadModes.IMREAD_COLOR_BGR })
|
||||
if (image instanceof cv.Mat) return await resolver(image);
|
||||
else throw new Error("Invalid image");
|
||||
}
|
||||
|
||||
public static fromOnnx<T extends Model>(this: ModelConstructor<T>, modelData: Uint8Array) {
|
||||
return new this(new backend.ort.Session(modelData));
|
||||
}
|
||||
|
||||
public constructor(session: backend.common.CommonSession) { this.session = session; }
|
||||
|
||||
|
||||
public get inputs() { return this.session.inputs; }
|
||||
public get outputs() { return this.session.outputs; }
|
||||
public get input() { return Object.entries(this.inputs)[0][1]; }
|
||||
public get output() { return Object.entries(this.outputs)[0][1]; }
|
||||
}
|
Reference in New Issue
Block a user