基础语法草稿
# 输入
# 1. 从 canvas 中读取
const src = cv.imread("canvasInput");
1
# 2.
# 输出
# 输出到 canvas 上
cv.imshow("canvasOutput", grayImage);
1
# 预处理
# 灰度
const grayImage = new cv.Mat();
cv.cvtColor(src, grayImage, cv.COLOR_BGR2GRAY, 0);
1
2
2
# 二值化
const binaryImage = new cv.Mat();
// 128 阈值
cv.threshold(grayImage, binaryImage, 128, 255, cv.THRESH_BINARY);
1
2
3
2
3
# 滤波
# 双边滤波
let dst = new cv.Mat();
cv.cvtColor(src, src, cv.COLOR_RGBA2RGB, 0);
cv.bilateralFilter(src, dst, 9, 75, 75, cv.BORDER_DEFAULT);
1
2
3
2
3
# 自定义滤波
const M = cv.matFromArray(3, 3, cv.CV_32FC1, [0, -1, 0, -1, 5, -1, 0, -1, 0]);
cv.filter2D(src, dst, cv.CV_8U, M, new cv.Point(-1, -1), 0, cv.BORDER_DEFAULT);
1
2
2
# 检测
# 轮廓
https://blog.csdn.net/weixin_38346042/article/details/122601245
https://docs.opencv.org/3.4/dc/dcf/tutorial_js_contour_features.html
- 检测
let contours = new cv.MatVector();
let hierarchy = new cv.Mat();
cv.findContours(
binaryImage,
contours,
hierarchy,
cv.RETR_TREE,
cv.CHAIN_APPROX_NONE
);
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
- 绘制
let dst = cv.Mat.zeros(src.rows, src.cols, cv.CV_8UC3);
let poly = new cv.MatVector();
// approximates each contour to polygon
for (let i = 0; i < contours.size(); ++i) {
let tmp = new cv.Mat();
let cnt = contours.get(i);
// You can try more different parameters
cv.approxPolyDP(cnt, tmp, 3, true);
poly.push_back(tmp);
cnt.delete();
tmp.delete();
}
// draw contours with random Scalar
for (let i = 0; i < contours.size(); ++i) {
let color = new cv.Scalar(
Math.round(Math.random() * 255),
Math.round(Math.random() * 255),
Math.round(Math.random() * 255)
);
cv.drawContours(dst, poly, i, color, 1, 8, hierarchy, 0);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
编辑 (opens new window)
上次更新: 2024/09/01, 23:56:56