如何在OpenCV JS中读取图像

时间:2018-09-21 07:29:13

标签: javascript opencv opencv3.0

如何在opencv js中读取图像。我无法在opencv javascript文档的帮助下完成此操作。有人可以在这里写一些代码来帮助我如何阅读“ opencv js”中的图像

2 个答案:

答案 0 :(得分:1)

OpenCV.js official site上的第一个教程之一完全满足您的要求。

我将在此处发布代码并向您解释其工作方式:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello OpenCV.js</title>
</head>
<body>
<h2>Hello OpenCV.js</h2>
<p id="status">OpenCV.js is loading...</p>
<div>
  <!-- we create 1 image element, 1 canvas element and an image source -->
  <div class="inputoutput">
    <img id="imageSrc" alt="No Image" />
    <div class="caption">imageSrc <input type="file" id="fileInput" name="file"/>
  </div>
</div>
<div class="inputoutput">
  <canvas id="canvasOutput" ></canvas>
  <div class="caption">canvasOutput</div>
</div>
</div>
<script type="text/javascript">
   // Here starts javascript. We save the loaded image in a variable called
   // imgElement 
   let imgElement = document.getElementById('imageSrc');
   let inputElement = document.getElementById('fileInput');
   // We add a listener which starts when an image is loaded 
   inputElement.addEventListener('change', (e) => {
      imgElement.src = URL.createObjectURL(e.target.files[0]);
   }, false);
   imgElement.onload = function() {
   // Image is loaded, we can start working with OpenCV 

   // We read the loaded image from imgElement and save it in a variable
   // we could modify later with OpenCV functions 
   let mat = cv.imread(imgElement);
   // We print the saved or modified image to the canvas element with id
   // 'canvasOutput' 
   cv.imshow('canvasOutput', mat);
   // Free memory 
   mat.delete();
   };

function onOpenCvReady() {
  document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
}
</script>
<script async src="opencv.js" onload="onOpenCvReady();" type="text/javascript">
</script>
</body>
</html>

您可以使用OpenCV函数和OpenCV对象来修改图像。 最常用的是cv.Mat()

您可以尝试通过使用以下代码替换cv.imshow('canvasOutput',mat)来将以前的代码修改为GreyScale:

let dst = new cv.Mat();
cv.cvtColor(mat, dst, cv.COLOR_RGBA2GRAY);
cv.imshow('canvasOutput', dst);

如果您无法在计算机上配置Opencv.js,则可以使用此链接来加载它:https://docs.opencv.org/3.4/opencv.js 只需更改

<script async src="https://docs.opencv.org/3.4/opencv.js"
onload="onOpenCvReady();" type="text/javascript">
</script>

答案 1 :(得分:1)

在html文件中,您必须具有用于OpenCV的图像,如下所示:

<img id="img" src="replace by image URL"/> 

然后,转到您的js文件并通过OpenCV读取它:

let src = cv.imread('img'); //img is the id you have declared from html file

现在,您可以像在OpenCV.js文档中一样使用变量 src 处理图像。