How to modify Mat values ​​according to some condition in opencv?

In matlab a (a> 50) = 0, you can replace all elements of a that are greater than 50 with 0. I want to do the same with Mat in openCV. how to do it?

+4
source share
3 answers

You want to truncate the image using the cv :: threshold.

The following should accomplish what you need:

cv::threshold(dst, dst, 50, 0, CV_THRESH_TOZERO_INV);

this is a function definition

double threshold(InputArray src, OutputArray dst, double thresh, double maxval, int type)

http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=threshold#threshold

+2
source

Naah. for this, only one line:

cv::Mat img = imread('your image path');
img.setTo(0,img>50);

just as easy.

+3
source

, Mat. Mat double, ( , Android).

: http://docs.opencv.org/2.4/modules/core/doc/operations_on_arrays.html

, :

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 create a matrix with only 50 at all points. After that, I compare it with yourMat using CMP_LT (less). Thus, all pixels less than 50 will be displayed 255 in your mask and 0 if they are larger. This is a mask. So you can simply:

yourMat.copyTo(yourMat, mask);

Now all pixels greater than 50 will be zero, and all the rest will have their own values.

0
source

All Articles