一個利用OpenCV進行帶掩膜的圖像拷貝的例子

比較簡單,閒話少說,直接上碼。

#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圖。

       

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章