Skip to content

Commit a364e0e

Browse files
committed
(#57) Added method to assure a ROI does not exceed image boundaries
1 parent 686a5a0 commit a364e0e

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

lib/provider/opencv/image-processor.class.ts

+10-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,14 @@ import * as cv from "opencv4nodejs-prebuilt";
22
import { Image } from "../../image.class";
33
import { Region } from "../../region.class";
44

5+
const determineROI = (img: Image, roi: Region): cv.Rect => {
6+
return new cv.Rect(
7+
Math.min(Math.max(roi.left, 0), img.width),
8+
Math.min(Math.max(roi.top, 0), img.height),
9+
Math.min(roi.width, img.width - roi.left),
10+
Math.min(roi.height, img.height - roi.top));
11+
};
12+
513
export class ImageProcessor {
614
/**
715
* fromImageWithAlphaChannel should provide a way to create a library specific
@@ -18,7 +26,7 @@ export class ImageProcessor {
1826
): Promise<cv.Mat> {
1927
const mat = await new cv.Mat(img.data, img.height, img.width, cv.CV_8UC4).cvtColorAsync(cv.COLOR_BGRA2BGR);
2028
if (roi) {
21-
return mat.getRegion(new cv.Rect(roi.left, roi.top, roi.width, roi.height));
29+
return mat.getRegion(determineROI(img, roi));
2230
} else {
2331
return mat;
2432
}
@@ -39,7 +47,7 @@ export class ImageProcessor {
3947
): Promise<cv.Mat> {
4048
const mat = new cv.Mat(img.data, img.height, img.width, cv.CV_8UC3);
4149
if (roi) {
42-
return mat.getRegion(new cv.Rect(roi.left, roi.top, roi.width, roi.height));
50+
return mat.getRegion(determineROI(img, roi));
4351
} else {
4452
return mat;
4553
}

0 commit comments

Comments
 (0)