JavaScript 写法类似于 C++ 写法。
相关内容详细介绍请移步官网:【https://docs.opencv.org/3.3.1/de/d06/tutorial_js_basic_ops.html】
代码示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>subROI</title>
<!-- 将图片设置为左浮动 -->
<style type="text/css">
.InputOutput{
float: left;
margin: 10px;
}
</style>
</head>
<body>
<!-- 若 opencv.js 文件加载成功,显示 opencv.js is ready. -->
<p id="status">opencv.js is loading...</p>
<!-- 上传图片 -->
<div class="InputOutput">
<!-- 文件选择框 -->
<div class="caption">srcImg<input type="file" id="inputFile"/></div>
<!-- 图像展示区 -->
<img id="srcImg" alt="No Image"/>
</div>
<!-- 显示结果 -->
<div class="InputOutput">
<div class="caption">dstImg</div>
<canvas id="dstImg"></canvas>
</div>
<!-- 实现代码 -->
<script type="text/javascript">
<!-- 读入图片 -->
let imgElement=document.getElementById("srcImg");
let fileElement=document.getElementById("inputFile");
fileElement.addEventListener("change",
(e)=>{imgElement.src=URL.createObjectURL(e.target.files[0]);},
false);
<!-- 读入图片的同时执行裁剪操作 -->
imgElement.onload=function(){
let src = cv.imread(imgElement);
let dst = new cv.Mat();
let rect = new cv.Rect(10, 10, 300, 300);
dst = src.roi(rect);
cv.imshow("dstImg", dst);
src.delete();
dst.delete();
}
function onOpenCvReady(){
document.getElementById("status").innerHTML="opencv.js is ready.";
}
</script>
<script async src="opencvjs/opencv.js" onload="onOpenCvReady();" type="text/javascript"></script>
</body>
</html>
效果演示: