Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Cách đảo ngược ảnh nhị phân trong OpenCV bằng C++

Đảo ngược ảnh nhị phân nghĩa là đảo ngược giá trị pixel. Về mặt thị giác, pixel trắng thành đen, pixel đen thành trắng.

Quy trình: Chuyển ảnh gốc sang xám, sau đó ngưỡng thành ảnh nhị phân, cuối cùng dùng bitwise_not() để đảo ngược.

cvtColor(original_image, grayscale_image, COLOR_BGR2GRAY);
threshold(grayscale_image, binary_image, 100, 255, THRESH_BINARY);
bitwise_not(source_matrix, destination_matrix);

Ví dụ

#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;

int main(int argc, char** argv) {
    Mat original_image, grayscale_image, binary_image, inverted_binary_image;
    namedWindow("Binary Image");
    namedWindow("Inverted Binary Image");
    original_image = imread("mountain.jpg");
    cvtColor(original_image, grayscale_image, COLOR_BGR2GRAY);
    threshold(grayscale_image, binary_image, 100, 255, THRESH_BINARY);
    bitwise_not(binary_image, inverted_binary_image);
    imshow("Binary Image", binary_image);
    imshow("Inverted Binary Image", inverted_binary_image);
    waitKey(0);
    return 0;
}

Kết quả

Cách đảo ngược ảnh nhị phân trong OpenCV bằng C++