Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set every pixel of a Mat to a certain value, if it´s lower than a value?

Im trying to do the following in OpenCV. How can I set every pixel of a Mat to a certain value, if it´s lower than a value?

So I want to do something like the threshold, but not quite, as I don't want to touch pixels above the given threshold.

For example: Set every pixel to 50 which is smaller than 50.

Any ideas?

like image 261
J.J Avatar asked May 20 '16 09:05

J.J


1 Answers

Regarding your particular request:

set to 50 all pixels < 50

using matrix expressions and setTo is straightforward:

Mat m = ...
m.setTo(50, m < 50);

In OpenCV, you compute can compute thresholds using cv::threshold, or comparison Matrix Expression.

As you're probably already doing, you can set to 255 all values > th with:

double th = 100.0;
Mat m = ...
Mat thresh;
threshold(m, thresh, th, 255, THRESH_BINARY);

or:

double th = 100.0;
Mat m = ...
Mat thresh = m > th;

For the other way around, i.e. set to 255 all values < th, you can do like:

double th = 100.0;
Mat m = ...
Mat thresh;
threshold(m, thresh, th, 255, THRESH_BINARY_INV); // <-- using INVerted threshold

or:

double th = 100.0;
Mat m = ...
Mat thresh = m <= th; // <-- using less-or-equal comparison 

//Mat thresh = m < th; // Will also work, but result will be different from the "threshold" version

Please note that while threshold will produce a result matrix of the same type of the input, the matrix expression will always produce a CV_8U result.

like image 90
Miki Avatar answered Sep 27 '22 22:09

Miki