Reputation: 43
I have a problem with matrix logical operation. I want to use bitwise_and
with image A and image B to get the result image C.
The image data type are all Mat
, image A was processed after some functions and it was a binary image with 3 channels. Image B was also a binary image after some processing but just with 1 channel.
Because the channel numbers are different, I get error when do bitwise_and
.
How should I do to merge the channel or any else methods to solve this problem?
Here shows image A,B,C:
Upvotes: 4
Views: 1784
Reputation: 7919
You can split the three channel matrix and apply bitwise "and operation" separately on each channel:
vector<Mat> channels(3);
// split img:
split(imageA, channels);
bitwise_and(channels[0], imageB, channels[0]);
bitwise_and(channels[1], imageB, channels[1]);
bitwise_and(channels[2], imageB, channels[2]);
Then merge channels to get 3 channel Mat object:
merge(channels, imageC);
Upvotes: 1
Reputation: 2675
I do like the following in Java.
Thresholded channel 1. webcam_image channel 3.
OPENCV 3.0
// convert 3 channel
Imgproc.cvtColor(thresholded, thresholded, Imgproc.COLOR_GRAY2BGR);
Core.bitwise_and(thresholded, webcam_image, webcam_image);
Maybe it'll help you.
Upvotes: 1
Reputation: 41765
You need A
and B
to have same size, type and number of channels. You can use cvtColor
to convert from 3 to 1 channel, or viceversa. It depends on the type you want for C
:
Mat A; // CV_8UC3
Mat B; // CV_8UC1
If you want C
to be 3 channels:
cvtColor(B, B, COLOR_GRAY2BGR);
Mat C;
bitwise_and(A,B,C); // C will be 3 channel, CV_8UC3
else if you want C
to be 1 channel:
cvtColor(A, A, COLOR_BGR2GRAY);
Mat C;
bitwise_and(A,B,C); // C will be 1 channel, CV_8UC1
Also, if you don't need to use a mask, you can simply do:
Mat C = A & B;
Upvotes: 3