比较简单,闲话少说,直接上码。
#include <iostream>
#include <vector>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace std;
using namespace cv;
int main()
{
Mat dot = imread("dots.jpg");
Mat dog = imread("dog.jpg");
cout << "dot.size() = " << dot.size() << endl;
cout << "dog.size() = " << dog.size() << endl;
//将两张输入图像都截取至较小一张图像的大小
Rect rect(0,0, dot.cols, dot.rows);
Mat sub_dot = dot(rect);
Mat sub_dog = dog(rect);
imshow("sub_dog", sub_dog);
waitKey(0);
imwrite("sub_dog.bmp", sub_dog);
// 将一张图像转换成灰度图并进行二值化
Mat grayImg, binImg;
cvtColor(sub_dot, grayImg, COLOR_BGR2GRAY);
threshold(grayImg, binImg, 0, 255, CV_THRESH_OTSU);
imshow("binImg", binImg);
waitKey(0);
imwrite("binImg.bmp",binImg);
//将二值化后的图作为掩膜
Mat masked_img;
sub_dog.copyTo(masked_img, binImg);
imshow("masked_img", masked_img);
waitKey(0);
imwrite("masked_img.bmp", masked_img);
return 0;
}
编译:
g++ -std=c++11 test_mask.cpp -o test_mask `pkg-config --cflags --libs opencv`
运行结果:
原图dot.jpg
原图dog.jpg
二值掩膜图、做掩膜拷贝之后的dog图。