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
subtract one image from another using openCV
提问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 LoadImage
to 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 diff
or just plain subtraction im1-im2
I 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 im1
and [70, 80, 90]
for im2
, using both im1 - im2
and diff(im1, im2, diff)
will produce value [0,0,0]
, since 20-70 = -50
, 50-80 = -30
, 30-90 = -60
and all negative results will be converted to unsigned value of 0
, which, in most cases, is not what you want. Method absdiff
will 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 - im2
并diff(im1, im2, diff)
会产生价值[0,0,0]
,因为20-70 = -50
,50-80 = -30
,30-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