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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With