Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace branch statements by bit-shifting operations

I'm writing an image binarization algorithm which simply converts each pixel's luminance value (grayscale image) to a black or white. Currently the algorithm for binarizing each pixel is roughly this

if( grayscale[x] < thresholdValue)
{
bitonal[x] = 1;
}

(this is actually a simplification of the ACTUAL algorithm because the bitonal image is actually a bitpacked image (each array index holds 8 pixels) so I actually bitpack the 1 inside the current array index...but I don't think that changes my question.

What I'm attempting to do is to remove the need for the if-statement.

What I was thinking was to do something along the lines of this. Subtract the thresholdValue by the grayscale and then perform some bit manipulation trickery to clear out or shift bits such that if the result of (grayscale[x]-threshold) is less than 0, I get a 0. otherwise I would get a 1 . If it's easier to do it the other way around (if grayscale[x]-threshold < 0 + bitwise trickery get a 1, else get a 0) that would also work... as long as I can get rid of the branch statements...any help appreciated..

like image 426
alessandro ferrucci Avatar asked Dec 05 '22 03:12

alessandro ferrucci


1 Answers

bitonal[x] = (grayscale[x] < thresholdValue);

like image 127
Mark Byers Avatar answered Dec 31 '22 13:12

Mark Byers