81 lines
2.4 KiB
JavaScript
81 lines
2.4 KiB
JavaScript
import cv from 'cv';
|
|
|
|
export default class CvWrapper {
|
|
findBarcode(el) {
|
|
this.initVariables(el);
|
|
|
|
cv.cvtColor(this.src, this.src, cv.COLOR_RGBA2GRAY, 0);
|
|
|
|
cv.Sobel(this.src, this.gradX, cv.CV_32F, 1, 0, -1)
|
|
cv.Sobel(this.src, this.gradY, cv.CV_32F, 0, 1, -1)
|
|
cv.subtract(this.gradX, this.gradY, this.src);
|
|
cv.convertScaleAbs(this.src, this.src);
|
|
|
|
cv.blur(this.src, this.src, this.ksize);
|
|
cv.threshold(this.src, this.src, 210, 255, cv.THRESH_BINARY);
|
|
|
|
this.M = cv.getStructuringElement(cv.MORPH_RECT, this.ksize2);
|
|
cv.morphologyEx(this.src, this.src, cv.MORPH_CLOSE, this.M)
|
|
|
|
cv.erode(this.src, this.src, this.M2, this.anchor, 7);
|
|
cv.dilate(this.src, this.src, this.M2, this.anchor, 2);
|
|
|
|
cv.findContours(this.src, this.contours, this.hierarchy, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE);
|
|
let biggest = 0;
|
|
let index;
|
|
for (let i = 0; i < this.contours.size(); i++) {
|
|
let cnt = this.contours.get(i);
|
|
let area = cv.contourArea(cnt, false);
|
|
if (area > biggest) {
|
|
biggest = area;
|
|
this.contour = cnt;
|
|
index = i
|
|
}
|
|
}
|
|
|
|
let rect = cv.boundingRect(this.contour);
|
|
let rectangleColor = new cv.Scalar(255, 255, 255);
|
|
let point1 = new cv.Point(rect.x, rect.y);
|
|
let point2 = new cv.Point(rect.x + rect.width, rect.y + rect.height);
|
|
|
|
this.dst = this.dst.roi(rect);
|
|
|
|
cv.rectangle(this.preview, point1, point2, rectangleColor, 2, cv.LINE_AA, 0);
|
|
|
|
cv.imshow('canvasOutput', this.dst);
|
|
cv.imshow('canvasPreview', this.preview);
|
|
|
|
this.cleanUpVariable();
|
|
}
|
|
|
|
initVariables(el) {
|
|
this.src = cv.imread(el);
|
|
this.preview = this.src.clone();
|
|
this.dst = this.src.clone();
|
|
this.dsize = new cv.Size(300, 300);
|
|
this.gradX = new cv.Mat();
|
|
this.gradY = new cv.Mat();
|
|
this.M = new cv.Mat();
|
|
this.ksize = new cv.Size(3, 3);
|
|
this.ksize2 = new cv.Size(21, 7);
|
|
this.contours = new cv.MatVector();
|
|
this.contour = new cv.Mat();
|
|
this.hierarchy = new cv.Mat();
|
|
this.M2 = cv.Mat.ones(5, 5, cv.CV_32F);
|
|
this.anchor = new cv.Point(-1, -1);
|
|
}
|
|
|
|
cleanUpVariable() {
|
|
this.src.delete();
|
|
this.dst.delete();
|
|
this.gradX.delete();
|
|
this.gradY.delete();
|
|
this.M.delete();
|
|
this.M2.delete();
|
|
this.contours.delete();
|
|
this.hierarchy.delete();
|
|
this.contour.delete();
|
|
this.preview.delete();
|
|
}
|
|
}
|