如何在 OpenCV 中对图像应用遮罩?
我想对彩色图像应用二元蒙版。 请提供一个基本的代码示例,并正确解释代码的工作原理。
另外,是否有一些选项可以永久应用蒙版,以便所有功能仅在蒙版内运行?
I want to apply a binary mask to a color image.
Please provide a basic code example with proper explanation of how the code works.
Also, is there some option to apply a mask permanently so all functions operate only within the mask?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
虽然 @perrejba 的答案是正确的,但它使用了遗留的 C 风格函数。由于问题被标记为 C++,您可能希望改用一个方法:
inputMat.copyTo(outputMat, maskMat);
所有对象都是
cv::Mat
类型。请注意,掩码是二进制的。掩码中的任何非零值都被解释为“执行复制”。即使蒙版是灰度图像。
另请注意,.copyTo() 函数在复制之前不会清除输出。
如果您想永久更改原始图像,则必须进行额外的复制/克隆/分配。没有为重叠输入/输出图像定义 copyTo() 函数。因此,您不能使用相同的图像作为输入和输出。
While @perrejba s answer is correct, it uses the legacy C-style functions. As the question is tagged C++, you may want to use a method instead:
inputMat.copyTo(outputMat, maskMat);
All objects are of type
cv::Mat
.Please be aware that the masking is binary. Any non-zero value in the mask is interpreted as 'do copy'. Even if the mask is a greyscale image.
Also be aware that the .copyTo() function does not clear the output before copying.
If you want to permanently alter the original Image, you have to do an additional copy/clone/assignment. The copyTo() function is not defined for overlapping input/output images. So you can't use the same image as both input and output.
您不对图像应用二元蒙版。您(可选)在处理函数调用中使用二进制掩码来告诉函数您要处理图像的哪些像素。如果我完全误解了你的问题,你应该添加更多细节来澄清。
You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.
好吧,这个问题出现在搜索结果的顶部,所以我相信我们在这里需要代码示例。 Python 代码如下:
蒙版和框架必须具有相同的大小,因此蒙版为
1
时像素保持原样,蒙版像素为0
时像素设置为零。对于
C++
来说有点不同:Well, this question appears on top of search results, so I believe we need code example here. Here's the Python code:
Mask and frame must be the same size, so pixels remain as-is where mask is
1
and are set to zero where mask pixel is0
.And for
C++
it's a little bit different:您可以使用掩码仅将原始图像的感兴趣区域复制到目标图像:
其中掩码应为 8 位单通道数组。
查看更多信息 OpenCV 文档
You can use the mask to copy only the region of interest of an original image to a destination one:
where
mask
should be an 8-bit single channel array.See more at the OpenCV docs
以下是一些代码,用于对从网络摄像头获取的视频帧序列应用二进制掩码。
注释并取消注释“bitwise_not(Mon_mask,Mon_mask);”行并查看效果。
最好的,
艾哈迈德。
Here is some code to apply binary mask on a video frame sequence acquired from a webcam.
comment and uncomment the "bitwise_not(Mon_mask,Mon_mask);"line and see the effect.
bests,
Ahmed.
使用带遮罩的副本。
代码示例:
Use copy with a mask.
Code sample: