如何使用 Java OpenCV 对两张图片执行按位与运算?
可以使用 org.opencv.core.Core 类的 bitwise_and() 方法计算两幅图像之间的按位与运算。
此方法接受三个表示源矩阵、目标矩阵和结果矩阵的 Mat 对象,计算源矩阵中每幅图像的按位与运算,并将结果存储在目标矩阵中。
示例
在以下 Java 示例中,我们将一张图像转换为二进制和灰度,并计算结果的按位与运算。
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class BitwiseAndExample {
public static void main(String args[]) throws Exception {
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Reading the Image
String file ="D://images//elephant.jpg";
Mat src = Imgcodecs.imread(file, Imgcodecs.IMREAD_GRAYSCALE );
HighGui.imshow("Grayscale Image", src);
//Creating an empty matrix to store the results
Mat dst = new Mat(src.rows(), src.cols(), src.type());
Mat threshold = new Mat(src.rows(), src.cols(), src.type());
Mat gray = new Mat(src.rows(), src.cols(), src.type());
//Converting the gray scale image to binary image
Imgproc.threshold(src, threshold, 100, 255, Imgproc.THRESH_BINARY_INV);
HighGui.imshow("Binary Image", threshold);
//Applying bitwise and operation
Core.bitwise_and(src, threshold, dst);
HighGui.imshow("Bitwise And operation", dst);
HighGui.waitKey();
}
}输入图像

输出
执行上述程序时,会生成以下窗口 −
灰度图像 −

二进制图像 −

按位与 −

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP