Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does saturate_cast in OpenCV work?

Tags:

opencv

Unable to understand, the results of the expression Vxy and Vxy_nocast

uchar init_m0[] = {10,10,30};
cv::Mat m0(3,1,CV_8UC1,init_m0,sizeof(uchar));
uchar& Vxy = m0.at<uchar>(0);
uchar& Vxy_nocast = m0.at<uchar>(1);
std::cout << m0 << std::endl;
Vxy = cv::saturate_cast<uchar>((Vxy-128)*2 + 128);
Vxy_nocast = (Vxy_nocast-128)*2 + 128;
std::cout << m0 << std::endl;

Result

[ 10;
  10;
  30]
[  0;
 148;
  30]
like image 745
infoclogged Avatar asked Mar 08 '23 05:03

infoclogged


1 Answers

(10-128)*2 + 128 = -108. cv::saturate_cast<uchar> is a saturating cast to unsigned char, and unsigned char can only be >= 0. A normal uchar cast, which is what happens implicitly if you specify nothing, will wrap a negative value around to positive by just reinterpreting the bits, -108 is 10010100 in 2's complement binary, which is the same as 148 (and it will also wrap around a larger value, eg 257 to 1). A saturating cast instead will cast negative values to 0, saturating at the minimum value of 0 for the type (and likewise positive values will saturate at the maximum of 255).

See saturation arithmetic for more details.

like image 185
hcs Avatar answered May 13 '23 03:05

hcs