#include <opencv2/opencv.hpp>
#include <iostream>
int main()
{
// 加载两张灰度图像
cv::Mat img1 = cv::imread("path_to_your_image1.jpg", cv::IMREAD_GRAYSCALE);
cv::Mat img2 = cv::imread("path_to_your_image2.jpg", cv::IMREAD_GRAYSCALE);
if (img1.empty() || img2.empty())
{
std::cout << "Could not open or find the images.\n";
return -1;
}
// 确保两张图像尺寸相同
if (img1.size() != img2.size())
{
std::cout << "Images must have the same size.\n";
return -1;
}
// 创建一个保存相减结果的图像
cv::Mat diff;
cv::subtract(img1, img2, diff);
// 遍历结果图像,任何小于5的值设置为0
for (int y = 0; y < diff.rows; y++)
{
for (int x = 0; x < diff.cols; x++)
{
if (diff.at<uchar>(y, x) < 5)
{
diff.at<uchar>(y, x) = 0;
}
}
}
// 显示结果
cv::namedWindow("Result", cv::WINDOW_AUTOSIZE);
cv::imshow("Result", diff);
cv::waitKey(0);
return 0;
}
#include <opencv2/opencv.hpp>
#include <iostream>
int main()
{
// 加载两张灰度图像
cv::Mat img1 = cv::imread("path_to_your_image1.jpg", cv::IMREAD_GRAYSCALE);
cv::Mat img2 = cv::imread("path_to_your_image2.jpg", cv::IMREAD_GRAYSCALE);
if (img1.empty() || img2.empty())
{
std::cout << "Could not open or find the images.\n";
return -1;
}
// 确保两张图像尺寸相同
if (img1.size() != img2.size())
{
std::cout << "Images must have the same size.\n";
return -1;
}
// 创建一个保存相减结果的图像
cv::Mat diff;
cv::subtract(img1, img2, diff);
// 使用 threshold 处理
// 将所有小于5的像素值设置为0,其余保持不变
cv::threshold(diff, diff, 5, 0, cv::THRESH_TOZERO_INV);
cv::threshold(diff, diff, 4, 255, cv::THRESH_BINARY); // 注意:这里使用4是因为THRESH_TOZERO_INV步骤中值小于5的部分变为0,其它值保持不变,而我们需要的是把小于5的变为0,所以这里直接将非0值变为255即可(或者根据实际情况设定)
// 显示结果
cv::namedWindow("Result", cv::WINDOW_AUTOSIZE);
cv::imshow("Result", diff);
cv::waitKey(0);
return 0;
}