How to perform a union operation in java opencv

2020-05-03 11:09发布

问题:

I need to write an equivalent Java OpenCV code as this C++ code

Mat1b mask1, mask2;
inRange(hsv, Scalar(0, 70, 50), Scalar(10, 255, 255), mask1);
inRange(hsv, Scalar(170, 70, 50), Scalar(180, 255, 255), mask2);

Mat1b mask = mask1 | mask2;

When i tried to use the | operator it leads to an error.

Mat mask1 = new Mat();
Mat mask2 = new Mat();
Core.inRange(hsv, new Scalar(0, 70, 50), new Scalar(10, 255, 255), mask1);
Core.inRange(hsv, new Scalar(170, 70, 50), new Scalar(180, 255, 255), mask2);

Mat hsvThres = mask1 | mask2;

Error:The operator | is undefined for the argument type(s) org.opencv.core.Mat

回答1:

Union operator, logic-or (|) for two matrix of the OpenCV:

Code in C++:

inRange(hsv, Scalar(0, 70, 50), Scalar(10, 255, 255), mask1);
inRange(hsv, Scalar(170, 70, 50), Scalar(180, 255, 255), mask2);

Mat mask = mask1 | mask2; 

Code in Java:

Mat mask1 = new Mat();
Mat mask2 = new Mat();
Core.inRange(hsv, new Scalar(0, 70, 50), new Scalar(10, 255, 255), mask1);
Core.inRange(hsv, new Scalar(170, 70, 50), new Scalar(180, 255, 255), mask2);

Mat mask= new Mat();
Core.bitwise_or(mask1, mask2, mask);

Code in Python:

mask1 = cv2.inRange(hsv, (0, 70, 50), (10, 255, 255))
mask2 = cv2.inRange(hsv, (170, 70, 50), (180, 255, 255))
mask = cv2.bitwise_or(mask1, mask2)


回答2:

I think what you're mistaking is that you are trying to compare two Mat object refrences and not the values beneath them. I'm not super familiar with openCV but my guess is you are trying to combine the values under them, so you could use the method https://docs.opencv.org/java/2.4.2/org/opencv/core/Mat.html#nativeObj. which that line in question would be re-written as: Mat hsvThres = new Mat(mask1.nativeObj | mask2.nativeObj);