简体   繁体   English

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

[英]subtract one image from another using openCV

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 ++中完成它

#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. 还要确保它们具有相同的尺寸。

Use LoadImage to load your images into memory, then use the Sub method. 使用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

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. 由于图像通常使用无符号格式存储,因此@Dat和@ ssh99的减法方法将消除所有负差异。 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. 例如,如果BMP图像的某些像素对于im1具有值[20, 50, 30] im1 [70, 80, 90]对于im2具有[ im1 - im2 [70, 80, 90] ,则使用im1 - im2diff(im1, im2, diff)将产生值[0,0,0] ,因为20-70 = -50 50-80 = -30 30-90 = -60并且所有否定结果将被转换为无符号值0 ,在大多数情况下,这不是什么你要。 Method absdiff will instead calculate the absolute values of all subtractions, thus producing more reasonable [50,30,60] . 方法absdiff将改为计算所有减法的绝对值,从而产生更合理的[50,30,60]

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). 这执行元素减法(img1-img2)。 you can find more details about it http://docs.opencv.org/modules/core/doc/operations_on_arrays.html 你可以找到更多关于它的细节http://docs.opencv.org/modules/core/doc/operations_on_arrays.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM