In Matlab a(a>50)=0
can replace all elements of a
that are greater than 50 to 0. I want to do same thing with Mat in OpenCV. How to do it?
-
2a>50 gives you a matrix with 0 elements everywhere where a <= 50 and 255 everywhere where your condition holds. So (0 * (a>50)).copyTo(a, a>50) would do this for example. Or just use `a.setTo(cv::Scalar(0), a>50)` – Micka Jan 15 '15 at 14:43
3 Answers
Naah. to do that, just one line:
cv::Mat img = imread('your image path');
img.setTo(0,img>50);
as simple as that.

- 670
- 7
- 15
-
1
-
I generally use ther thresholding method... that's also just one statement but this is wayy more flexible and I love it – Shravya Boggarapu Aug 06 '19 at 08:21
What you want is to truncate the image with cv::threshold.
The following should do what you require:
cv::threshold(dst, dst, 50, 0, CV_THRESH_TOZERO_INV);
this is the function definition
double threshold(InputArray src, OutputArray dst, double thresh, double maxval, int type)

- 6,437
- 14
- 61
- 119
-
I think the OP is actually looking for `THRESH_TOZERO_INV`, which sets values greater than the threshold to 0. `THRESH_TRUNC` sets values greater than the threshold to the threshold. – beaker Jan 15 '15 at 18:35
-
1Sorry, OP is "Original Post" or "Original Poster"... either the question or the person who asked it. – beaker Jan 15 '15 at 22:15
-
definition of threshold says not only values greater than threshold will be changed to maxvalue but it will set all values less than threshold to 0. but I want them values less than threshold as it is. – sam ran Jan 16 '15 at 10:46
Sometimes threshold doesn't work because you can have a diferent kind of Mat. If your Mat type supports double, threshold will crash (at least in my android studio).
You can find compare here: http://docs.opencv.org/2.4/modules/core/doc/operations_on_arrays.html
So I use the function compare:
Mat mask = new Mat(yourMat.rows(), yourMat.cols(), CvType.CV_64FC1);
Mat ones = org.opencv.core.Mat.ones(yourMat.rows(), yourMat.cols(), CvType.CV_64FC1);
Scalar alpha = new Scalar(50, CvType.CV_64FC1);
Core.multiply(ones, alpha, ones);
Core.compare(yourMat, zeros, mask, Core.CMP_LT);
Here I am creating a matrix with only 50 in all points. After that i am comparing it with yourMat, using CMP_LT (Less than). So all pixels less than 50 will turn in 255 in your mask and 0 if bigger. It is a mask. So you can just:
yourMat.copyTo(yourMat, mask);
Now all the pixels bigger than 50 will be zero and all the other will have their own values.

- 771
- 9
- 15