參考: https://docs.opencv.org/master/d3/de6/tutorial_js_houghlines.html
將以下內容存成 html 檔案, 先抓取 http://192.168.12.102/snap.jpg 檔案後, 再作影像處理範例:
<html>
<head><meta charset="utf-8"><title>OpenCV demo</title>
<script async src="https://docs.opencv.org/3.4.0/opencv.js" onload="onOpenCvReady( );" type="text/javascript"></script>
</head>
<body>
<div><canvas id="computerVision"></canvas></div>
<script>
async function onOpenCvReady() {
let result = await fetch("http://192.168.12.102/snap.jpg");
let jpgURL = URL.createObjectURL(await result.blob());
let resolv = false;
let future = new Promise((ready, _) => resolv=ready);
let img = new Image();
img.onload = () => {
resolv && resolv(img);
URL.revokeObjectURL(jpgURL);
img.remove();
};
img.src = jpgURL;
let src = cv.imread(await future);// cv: computer vision
let dst = new cv.Mat();// an instance of matrix
cv.cvtColor(src, dst, cv.COLOR_RGBA2GRAY, 0);// color to gray, 轉成灰階
cv.Canny(dst, dst, 50, 200, 3); // gray to edge, 過濾成邊際線
let lines = new cv.Mat();
cv.HoughLinesP(dst, lines, 1, Math.PI / 180, 2, 0, 0)// 從邊際線提取線段
for (let i = 0; i < lines.rows; ++i) {
let startPoint = new cv.Point(lines.data32S[i * 4], lines.data32S[i * 4 + 1]);
let endPoint = new cv.Point(lines.data32S[i * 4 + 2], lines.data32S[i * 4 + 3]);
cv.line(src, startPoint, endPoint, [255, 0, 0, 255]);// 將線段畫在原圖上
}
cv.imshow('computerVision', src);// 秀出合成圖
lines.delete();
dst.delete();
src.delete();
}
</script>
</body>
</html>
使用瀏覽器開啟上述檔案就可, 每次都要上網抓 opencv.js 感覺很麻煩, 可以先抓下來存成 opencv.js, 將它放在與 html 檔案同一目錄下, 稍微修改檔案路徑:
<script async
src="opencv.js" onload="onOpenCvReady();"
type="text/javascript"></script>
沒有留言:
張貼留言