You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OpenCV.js中创建掩码?已掌握C++中cv::Mat::zeros和Rect用法

Got it, I totally get where you're coming from—OpenCV.js does have some slight API differences compared to the C++ version, but creating a mask similar to using cv::Mat::zeros and Rect is totally doable with a few equivalent steps. Let me break it down for you:

Step 1: Create a blank all-zero mask

In C++ you'd use cv::Mat::zeros to get a black (all-zero) mask. In OpenCV.js, you have two straightforward options:

Either initialize a new cv.Mat directly with a zero scalar:

// Assuming you have an input image `img` to match dimensions
const mask = new cv.Mat(img.rows, img.cols, cv.CV_8UC1, new cv.Scalar(0));

Or use the cv.Mat.zeros function (which works similarly to the C++ static method):

const mask = cv.Mat.zeros(img.rows, img.cols, cv.CV_8UC1);

(Note: Use cv.CV_8UC1 for 8-bit single-channel masks, which is the most common type. Adjust the type if you need a float mask, like cv.CV_32FC1.)

Step 2: Define your rectangular region

Just like C++'s cv::Rect, OpenCV.js has cv.Rect. You create it with the same parameters: x-coordinate, y-coordinate, width, height:

// Example: A rectangle starting at (100,100) with width 200, height 150
const roiRect = new cv.Rect(100, 100, 200, 150);

Step 3: Fill the rectangle to create the mask's active region

To turn that rectangular area into the "active" part of the mask (white, non-zero), use cv.rectangle with a fill thickness. In OpenCV.js, you can use -1 or the constant cv.FILLED to fill the rectangle completely:

// Fill the rectangle with white (255 for 8-bit masks)
cv.rectangle(mask, roiRect, new cv.Scalar(255), cv.FILLED);

Alternatively, you can use the ROI (Region of Interest) approach to set the area directly:

const roi = mask.roi(roiRect);
roi.setTo(new cv.Scalar(255));
roi.delete(); // Important: Release the ROI reference to avoid memory leaks

Full Example

Here's a complete snippet tying it all together, including cleanup (critical for OpenCV.js to prevent memory leaks):

// Assume we have an input image loaded as `inputImg`
const mask = cv.Mat.zeros(inputImg.rows, inputImg.cols, cv.CV_8UC1);
const targetRect = new cv.Rect(50, 50, 300, 200);

// Fill the rectangle to make the mask
cv.rectangle(mask, targetRect, new cv.Scalar(255), cv.FILLED);

// Use the mask for an operation, e.g., copy the masked region
const maskedResult = new cv.Mat();
inputImg.copyTo(maskedResult, mask);

// Don't forget to clean up all OpenCV objects!
mask.delete();
targetRect.delete();
maskedResult.delete();

A quick reminder: Always call .delete() on any cv.Mat, cv.Rect, or other OpenCV.js objects you create—JavaScript doesn't handle automatic memory management for these like C++ does with destructors.

内容的提问来源于stack exchange,提问作者my-lord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:52:12