개요
OpenCV에서는 org.opencv.core.Core 클래스가 제공하는 bitwise_xor() 메서드를 사용하여 두 이미지 간의 비트 단위 배타적 논리합(XOR) 연산을 손쉽게 수행할 수 있습니다.
이 메서드는 소스(source), 결과(destination) 행렬 등 세 개의 Mat 객체를 매개변수로 받으며, 소스 행렬의 각 요소에 대해 비트 단위 XOR 연산을 계산한 뒤 그 결과를 결과 행렬에 저장합니다.
예제 코드
다음 Java 예제에서는 이미지를 그레이스케일과 이진(binary) 이미지로 변환한 후, 두 결과 이미지에 대해 비트 단위 XOR 연산을 수행합니다.
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 BitwiseXORExample {
public static void main(String args[]) throws Exception {
// OpenCV 핵심 라이브러리 로드
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
// 이미지 읽기
String file = "D://images//elephant.jpg";
Mat src = Imgcodecs.imread(file, Imgcodecs.IMREAD_GRAYSCALE );
HighGui.imshow("Grayscale Image", src);
// 결과를 저장할 빈 행렬 생성
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());
// 그레이스케일 이미지를 이진 이미지로 변환
Imgproc.threshold(src, threshold, 100, 255, Imgproc.THRESH_BINARY_INV);
HighGui.imshow("Binary Image", threshold);
// 비트 단위 XOR 연산 적용
Core.bitwise_xor(src, threshold, dst);
HighGui.imshow("Bitwise XOR operation", dst);
HighGui.waitKey();
}
}입력 이미지

실행 결과
위 프로그램을 실행하면 다음과 같은 창들이 순서대로 나타납니다.
그레이스케일 이미지(Gray Scale Image)

이진 이미지(Binary Image)

비트 단위 XOR 연산 결과(Bitwise XOR)
