Ask Your Question
0

Pixelwise subtract, with negative numbers

asked 2014-11-02 13:10:06 -0600

kovand11 gravatar image

I would like to implement the following pixelwise operation between two images:

  • Subtract the pixels (RGB) (important: if the result is negative, keep it)
  • Convert to absolute value (RGB)
  • Somehow merge the three channels (for starter, I use the cv::COLOR_RGB2GRAY which is a weighted add)

But, the problem is, that the cv::substract() and the operator - on cv::Mat fails to calculate negative values, and uses 0 instead.

How can I easily implement the behavior I need?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
3

answered 2014-11-02 13:32:50 -0600

rwong gravatar image

updated 2014-11-02 13:34:46 -0600

Option 1

Use cv::absdiff.

Link to documentation


Option 2

When performing the subtraction, specify an "intermediate data depth" capable of storing all possible intermediate values - from the positive limit to the negative limit.

Example:

cv::Mat matDiff; // will be filled with result.
cv::Mat matTemp; // temporarily holds the intermediate result.
cv::subtract(matOne, matTwo, matTemp, cv::noArray(), CV_32S);
matTemp = cv::abs(matTemp);
matTemp.convertTo(matDiff, CV_8U); // Or other precisions (depths).

Both options should work. However, if you find that one of the options is not working as documented, be sure to file a bug report or share your findings here. Thanks.

I posted both options because my use of an earlier version of OpenCV had a bug in absdiff that requires the workaround. I haven't checked ever since. Anyone using the advice above should manually verify that the code works on their version of OpenCV before further use.

edit flag offensive delete link more

Question Tools

Stats

Asked: 2014-11-02 13:10:06 -0600

Seen: 5,956 times

Last updated: Nov 02 '14