Multiplying Intensity Image Subtraction

So I am creating an intensity image as follows:

void convertToGrayImg(Mat& img, Mat& result) {
Mat gray_img;
cvtColor(img, gray_img, CV_BGR2GRAY);
result = gray_img;
}


Now I have to multiply the intensity image I by 0.5 and subtract it from each color channel. How can this be done?

I am confused, do I multiply every pixel with 0.5 or is there a function to do the same? I am very new to OpenCV.

Thanks.

edit retag close merge delete

Sort by ยป oldest newest most voted

no, you don't have to do that "per-pixel". it's just 2 easy steps:

// 0. that's what you already got:
Mat img = ... // bgr image from somewhere
Mat gray;
cvtColor(img, gray, CV_BGR2GRAY);
// 1. make a 3-channel grayscale image with half the original intensity:
// (to subtract later, we need images with equal channel count, so just duplicate gray 3 times)
Mat gray_half;
cvtColor(gray * 0,5, gray_half, CV_GRAY2BGR);
// 2. subtract that from original:
Mat result = img - gray_half;

more

Thanks a lot for clearing my understanding. Is it possible to do it with subtract?

( 2016-10-22 09:15:23 -0600 )edit
2

ofc., you can:

Mat result;
subtract(img, gray_half, result);


same for the multiplication above:

Mat gray2;
multiply(gray, 0.5, gray2);
Mat gray_half;
cvtColor(gray2, gray_half, CV_GRAY2BGR);


(in the end, it's just a matter of taste..)

( 2016-10-22 09:24:12 -0600 )edit
1

Thanks a lot. You have been a great help. my regards.

( 2016-10-22 09:55:11 -0600 )edit

Maybe do remind that doing a subtract or a multiply on a given image can result in unexpected data, like negative values or value overflows. So do this with caution.

( 2016-10-24 08:15:00 -0600 )edit