如何在OpenCV js中计算拉普拉斯方差?

drnojrws  于 2022-12-04  发布在  其他
关注(0)|答案(2)|浏览(183)

我尝试使用OpenCV实现模糊检测,但在OpenCV js中找不到以下语句的任何等效语句:cv2.Laplacian(image, cv2.CV_64F).var()
有没有其他方法来计算方差?

k4emjkb1

k4emjkb11#

您可以通过获取Laplacian Mat的 Standard Deviation,然后将其平方来计算方差。OpenCV具有计算标准差的函数。

cv.meanStdDev(srcMat, mean, standardDeviationMat)

在下面的代码中,你可以查看它是如何完成的。我从一个ImageData对象中阅读图像,然后将其更改为灰度,最后计算 * 拉普拉斯方差 *:

const cvImage = cv.matFromImageData(imageData);
const grayImage = new cv.Mat();
const laplacianMat = new cv.Mat();

cv.cvtColor(cvImage, grayImage, cv.COLOR_RGBA2GRAY, 0);
cv.Laplacian(grayImage, laplacianMat, cv.CV_64F);

const mean = new cv.Mat(1, 4, cv.CV_64F);
const standardDeviationMat = new cv.Mat(1, 4, cv.CV_64F);

cv.meanStdDev(laplacianMat, mean, standardDeviationMat);

const standardDeviation = standardDeviationMat.doubleAt(0, 0);
const laplacianVar = standardDeviation * standardDeviation;

在这个post中也有类似的答案,但是使用的是opencv4nodejs而不是opencv.js

pbpqsu0x

pbpqsu0x2#

我也很难理解这个问题。Here是一个代码沙箱的链接,如果你想玩一个工作示例的话。我已经在opencv.js4.x中使用了这个链接。
下面是用于快速复制和粘贴的代码片段:

const mean = (array = []) =>
  array.reduce((acc, x) => acc + x, 0) / array.length;

const variance = (array = []) => {
  const m = mean(array);
  return array.reduce((acc, el) => acc + Math.pow(el - m, 2), 0) / array.length;
}

const processVideo = () => {
  let src = new cv.Mat(video.height, video.width, cv.CV_8UC4);
  let gray_src = new cv.Mat(video.height, video.width, cv.CV_8UC1);
  let lap_gray = new cv.Mat(video.height, video.width, cv.CV_8UC1);
  let cap = new cv.VideoCapture(video);
  const FPS = 15;

  let begin = Date.now();

  // start processing cap -> src
  cap.read(src); 

  // process src -> dst
  cv.cvtColor(src, gray_src, cv.COLOR_RGBA2GRAY);
  cv.Laplacian(gray_src, lap_gray, -1);

  // this is the fm value in the original post
  const focusMeasure = Math.floor(variance(lap_gray.data));
  // console.log(fm); // uncomment to see; it will spam the console
  
  // write dst to canvas
  cv.imshow("canvasOutput", lap_gray);

  // schedule the next one.
  let delay = 1000 / FPS - (Date.now() - begin);
  setTimeout(processVideo, delay);
}

相关问题