Ask Your Question

Multiplying Intensity Image Subtraction

asked 2016-10-22 08:27:00 -0600

Jishan gravatar image

updated 2016-10-22 08:39:00 -0600

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.


edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2016-10-22 08:53:28 -0600

berak gravatar image

updated 2016-10-22 08:57:01 -0600

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;
edit flag offensive delete link more


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

Jishan gravatar imageJishan ( 2016-10-22 09:15:23 -0600 )edit

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..)

berak gravatar imageberak ( 2016-10-22 09:24:12 -0600 )edit

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

Jishan gravatar imageJishan ( 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.

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

Question Tools

1 follower


Asked: 2016-10-22 08:27:00 -0600

Seen: 1,479 times

Last updated: Oct 22 '16