C++ 使用 openCV 从另一个图像中减去一个图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2501957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:43:19  来源:igfitidea点击:

subtract one image from another using openCV

c++imageopencvsubtraction

提问by marionmaiden

How can I subtract one image from another using openCV?

如何使用 openCV 从另一个图像中减去一个图像?

Ps.: I coudn't use the python implementation because I'll have to do it in C++

Ps.:我不能使用 python 实现,因为我必须用 C++ 来做

采纳答案by Justin Ethier

Use LoadImageto load your images into memory, then use the Submethod.

用于LoadImage将图像加载到内存中,然后使用Sub方法。

This link contains some example code, if that will help: http://permalink.gmane.org/gmane.comp.lib.opencv/36167

此链接包含一些示例代码,如果有帮助:http: //permalink.gmane.org/gmane.comp.lib.opencv/36167

回答by Dat Chu

#include <cv.h>
#include <highgui.h>

using namespace cv;

Mat im = imread("cameraman.tif");
Mat im2 = imread("lena.tif");

Mat diff_im = im - im2;

Change the image names. Also make sure they have the same size.

更改图像名称。还要确保它们具有相同的尺寸。

回答by John Smith

Instead of using diffor just plain subtraction im1-im2I would rather suggest the OpenCV method cv::absdiff

而不是使用diff或只是简单的减法,im1-im2我宁愿建议 OpenCV 方法cv::absdiff

using namespace cv;
Mat im1 = imread("image1.jpg");
Mat im2 = imread("image2.jpg");
Mat diff;
absdiff(im1, im2, diff);

Since images are usually stored using unsigned formats, the subtraction methods of @Dat and @ssh99 will kill all the negative differences. For example, if some pixel of a BMP image has value [20, 50, 30]for im1and [70, 80, 90]for im2, using both im1 - im2and diff(im1, im2, diff)will produce value [0,0,0], since 20-70 = -50, 50-80 = -30, 30-90 = -60and all negative results will be converted to unsigned value of 0, which, in most cases, is not what you want. Method absdiffwill instead calculate the absolute values of all subtractions, thus producing more reasonable [50,30,60].

由于图像通常使用无符号格式存储,@Dat 和@ssh99 的减法方法将消除所有负差异。例如,如果一个BMP图像的某些像素具有价值[20, 50, 30]im1,并[70, 80, 90]im2,同时使用im1 - im2diff(im1, im2, diff)会产生价值[0,0,0],因为20-70 = -5050-80 = -3030-90 = -60和所有的阴性结果将被转换为无符号值0,其中,在大多数情况下,是不是你想要的。方法absdiff将改为计算所有减法的绝对值,从而产生更合理的[50,30,60]

回答by ssh99

use cv::subtract() method.

使用 cv::subtract() 方法。

Mat img1=some_img;
Mat img2=some_img;

Mat dest;

cv::subtract(img1,img2,dest); 

This performs elementwise subtract of (img1-img2). you can find more details about it http://docs.opencv.org/modules/core/doc/operations_on_arrays.html

这将执行 (img1-img2) 的逐元素减法。您可以找到有关它的更多详细信息http://docs.opencv.org/modules/core/doc/operations_on_arrays.html