Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle elements in a matrix with range[0,1]?

Tags:

c++

opencv

I have this matrix,

0 1 0
1 0 1
0 1 0

And I want to toggle each 1-valued elements to 0 and vice versa:

1 0 1
0 1 0
1 0 1

If I use the bitwise complement operator i.e. dst = ~src I got this result

255 254 255
254 255 254
255 254 255

Of cource I can get the result I want with some arithmetic and looping. But is there any easy way to achieve the matrix I want in OpenCV? Thanks.

Update:

Here is the code snippet:

#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

int main()
{
    cv::Mat a = (cv::Mat_<uchar>(3,3) << 0, 1, 0,
                                         1, 0, 1, 
                                         0, 1, 0 );
    cv::Mat b = ~a;
    std::cout << b << std::endl;

    return 0;
}
like image 870
flowfree Avatar asked Nov 19 '25 01:11

flowfree


1 Answers

If you have only ones and zeros, you can do this:

cv::Mat b = 1 - a;

like image 97
sgarizvi Avatar answered Nov 21 '25 14:11

sgarizvi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!