Java에서 org.opencv.core.Core 클래스가 제공하는 bitwise_and() 메서드를 사용하면 두 이미지 간의 비트 단위 논리곱(AND) 연산을 손쉽게 수행할 수 있습니다.
이 메서드는 소스 행렬 두 개와 연산 결과를 저장할 대상 행렬에 해당하는 총 세 개의 Mat 객체를 인수로 받습니다. 소스 행렬의 모든 요소에 대해 비트 단위 논리곱을 계산한 뒤, 그 결과를 대상 행렬에 저장합니다.
예제 코드
다음 Java 예제에서는 하나의 이미지를 그레이스케일과 이진(binary) 이미지로 변환한 후, 두 결과 이미지에 대해 비트 AND 연산을 수행합니다.
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 {
// 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);
// 비트 AND 연산 적용
Core.bitwise_and(src, threshold, dst);
HighGui.imshow("Bitwise And operation", dst);
HighGui.waitKey();
}
}동작 원리
Imgproc.threshold() 메서드는 임계값 100을 기준으로 픽셀 값을 반전된 이진 형태(THRESH_BINARY_INV)로 변환합니다. 이후 Core.bitwise_and()가 원본 그레이스케일 이미지와 이진 이미지의 대응되는 픽셀 값들을 비트 단위로 AND 연산하여 최종 결과 이미지를 생성합니다.
입력 이미지

실행 결과
위 프로그램을 실행하면 다음과 같은 창들이 순서대로 표시됩니다.
그레이스케일 이미지

이진 이미지

비트 AND 연산 결과
