Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
function debugImage(image: cv.Mat, filename: string, suffix?: string) {
const parsedPath = path.parse(filename);
let fullFilename = parsedPath.name;
if (suffix) {
fullFilename = fullFilename + "_" + suffix;
}
fullFilename += parsedPath.ext;
const fullPath = path.join(parsedPath.dir, fullFilename);
cv.imwriteAsync(fullPath, image);
}
public async store(data: Image, path: string): Promise {
let outputMat: cv.Mat;
if (data.hasAlphaChannel) {
outputMat = await ImageProcessor.fromImageWithAlphaChannel(data);
} else {
outputMat = await ImageProcessor.fromImageWithoutAlphaChannel(data);
}
return cv.imwriteAsync(path, outputMat);
}
}
function determineROI(img: Image, roi: Region): cv.Rect {
return new cv.Rect(
Math.min(Math.max(roi.left, 0), img.width),
Math.min(Math.max(roi.top, 0), img.height),
Math.min(roi.width, img.width - roi.left),
Math.min(roi.height, img.height - roi.top));
}
public static async fromImageWithoutAlphaChannel(
img: Image,
roi?: Region,
): Promise {
const mat = new cv.Mat(img.data, img.height, img.width, cv.CV_8UC3);
if (roi) {
return mat.getRegion(determineROI(img, roi));
} else {
return mat;
}
}
}
public static async fromImageWithAlphaChannel(
img: Image,
roi?: Region,
): Promise {
const mat = await new cv.Mat(img.data, img.height, img.width, cv.CV_8UC4).cvtColorAsync(cv.COLOR_BGRA2BGR);
if (roi) {
return mat.getRegion(determineROI(img, roi));
} else {
return mat;
}
}
export async function findEdges(image: cv.Mat): Promise {
const gray = await image.cvtColorAsync(cv.COLOR_BGR2GRAY);
return gray.cannyAsync(50, 200);
}
return new Promise<img>(async (resolve, reject) => {
try {
const image = await cv.imreadAsync(path, cv.IMREAD_UNCHANGED);
resolve(new Image(image.cols, image.rows, image.getData(), image.channels));
} catch (e) {
reject(`Failed to load image from '${path}'`);
}
});
}
export async function scaleImage(image: cv.Mat, scaleFactor: number): Promise {
const boundScaleFactor = lowerBound(scaleFactor, 0.0, 1.0);
const scaledRows = Math.floor(image.rows * boundScaleFactor);
const scaledCols = Math.floor(image.cols * boundScaleFactor);
return image.resizeAsync(scaledRows, scaledCols, 0, 0, cv.INTER_AREA);
}
export async function matchImages(haystack: cv.Mat, needle: cv.Mat): Promise {
const match = await haystack.matchTemplateAsync(
needle,
cv.TM_SQDIFF_NORMED,
);
const minMax = await match.minMaxLocAsync();
return new MatchResult(
1.0 - minMax.minVal,
new Region(
minMax.minLoc.x,
minMax.minLoc.y,
needle.cols,
needle.rows,
),
);
}