OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试

1、OpenCV_contrib的安装与一个问题的解决

在新版本的opencv中,我们失去了一些函数例如sift,以及这次我们需要使用的grabCut,因此我们需要安装OpenCV-contrib。
新手(我)安装可以参考这篇csdn:VS2017和opencv-4.1.2配置。
(注意一定要选择相同版本的opencv与opencv-contrib)

我遇到的问题:无法打开opencv_stitching412d.lib
在实际使用时,例如错误信息为:无法打开opencv_stitching412d.lib
解决方法:
1、首先打开你在cmake过程中选择的空文件夹(cmake操作中)
OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第1张图片
到路径:D:\opencv_contrib-4.1.2\build\lib\Debug,(这是我的文件路径)
去检查文件夹中是否有你所缺失的lib文件(下图红线所示)OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第2张图片
我在报错的时候是没有这个包的,在求助老师后,方才得知VS在编译时也是需要联网下载的。就如git clone和python的pip一样,有些资源是很难下载的。
2、打开OpenCV.sln,在解决方案资源管理器中,找到modules中的opencv_stitching,右键–生成。等待编译结束。这个时候,我遇到的错误是:我的xfeatures2d.lib缺失了(我现在配好了所以没法截图),而这个xfeatures2d.libopencv_stitching的依赖项(由我之前配sift的经验来看,这个xfeatures2d.lib**应该是很多东西的依赖项)。
最终在老师的帮助下,我得到了缺失的文件资源

OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第3张图片
将得到的压缩包解压到路径:图中那个build就是你cmake存放生成文件的文件夹OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第4张图片
3、回到VS,在modules中找到opencv_xfeatures2d,右键–生成(我在添加了文件之后就生成成功了)。
OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第5张图片
然后这时再选中opencv_stitching,右键–生成,等待编译结束。这个时候注意,有可能还是会报错。你转到第一步中的那个文件夹,此时应该就存在了opencv_stitching412d.lib。至此,问题得到解决。

2、grabCut的学习与使用

cv::grabCut的函数原型如下:

void cv::grabCut	(	InputArray 	img,
								InputOutputArray 	mask,
								Rect 	rect,
								InputOutputArray 	bgdModel,
								InputOutputArray 	fgdModel,
								int 	iterCount,
								int 	mode = GC_EVAL 
							)		

其中各个变量的解释:
OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第6张图片
今天时间有限,我们就先来看看tutorial中给出的grabCut函数的示例。

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include 
using namespace std;
using namespace cv;
static void help()
{
	cout << "\nThis program demonstrates GrabCut segmentation -- select an object in a region\n"
		"and then grabcut will attempt to segment it out.\n"
		"Call:\n"
		"./grabcut \n"
		"\nSelect a rectangular area around the object you want to segment\n" <<
		"\nHot keys: \n"
		"\tESC - quit the program\n"
		"\tr - restore the original image\n"
		"\tn - next iteration\n"
		"\n"
		"\tleft mouse button - set rectangle\n"
		"\n"
		"\tCTRL+left mouse button - set GC_BGD pixels\n"
		"\tSHIFT+left mouse button - set GC_FGD pixels\n"
		"\n"
		"\tCTRL+right mouse button - set GC_PR_BGD pixels\n"
		"\tSHIFT+right mouse button - set GC_PR_FGD pixels\n" << endl;
}
const Scalar RED = Scalar(0, 0, 255);
const Scalar PINK = Scalar(230, 130, 255);
const Scalar BLUE = Scalar(255, 0, 0);
const Scalar LIGHTBLUE = Scalar(255, 255, 160);
const Scalar GREEN = Scalar(0, 255, 0);
const int BGD_KEY = EVENT_FLAG_CTRLKEY;
const int FGD_KEY = EVENT_FLAG_SHIFTKEY;
static void getBinMask(const Mat& comMask, Mat& binMask)
{
	if (comMask.empty() || comMask.type() != CV_8UC1)
		CV_Error(Error::StsBadArg, "comMask is empty or has incorrect type (not CV_8UC1)");
	if (binMask.empty() || binMask.rows != comMask.rows || binMask.cols != comMask.cols)
		binMask.create(comMask.size(), CV_8UC1);
	binMask = comMask & 1;
}
class GCApplication
{
public:
	enum { NOT_SET = 0, IN_PROCESS = 1, SET = 2 };
	static const int radius = 2;
	static const int thickness = -1;
	void reset();
	void setImageAndWinName(const Mat& _image, const string& _winName);
	void showImage() const;
	void mouseClick(int event, int x, int y, int flags, void* param);
	int nextIter();
	int getIterCount() const { return iterCount; }
private:
	void setRectInMask();
	void setLblsInMask(int flags, Point p, bool isPr);
	const string* winName;
	const Mat* image;
	Mat mask;
	Mat bgdModel, fgdModel;
	uchar rectState, lblsState, prLblsState;
	bool isInitialized;
	Rect rect;
	vector fgdPxls, bgdPxls, prFgdPxls, prBgdPxls;
	int iterCount;
};
void GCApplication::reset()
{
	if (!mask.empty())
		mask.setTo(Scalar::all(GC_BGD));
	bgdPxls.clear(); fgdPxls.clear();
	prBgdPxls.clear();  prFgdPxls.clear();
	isInitialized = false;
	rectState = NOT_SET;
	lblsState = NOT_SET;
	prLblsState = NOT_SET;
	iterCount = 0;
}
void GCApplication::setImageAndWinName(const Mat& _image, const string& _winName)
{
	if (_image.empty() || _winName.empty())
		return;
	image = &_image;
	winName = &_winName;
	mask.create(image->size(), CV_8UC1);
	reset();
}
void GCApplication::showImage() const
{
	if (image->empty() || winName->empty())
		return;
	Mat res;
	Mat binMask;
	if (!isInitialized)
		image->copyTo(res);
	else
	{
		getBinMask(mask, binMask);
		image->copyTo(res, binMask);
	}
	vector::const_iterator it;
	for (it = bgdPxls.begin(); it != bgdPxls.end(); ++it)
		circle(res, *it, radius, BLUE, thickness);
	for (it = fgdPxls.begin(); it != fgdPxls.end(); ++it)
		circle(res, *it, radius, RED, thickness);
	for (it = prBgdPxls.begin(); it != prBgdPxls.end(); ++it)
		circle(res, *it, radius, LIGHTBLUE, thickness);
	for (it = prFgdPxls.begin(); it != prFgdPxls.end(); ++it)
		circle(res, *it, radius, PINK, thickness);
	if (rectState == IN_PROCESS || rectState == SET)
		rectangle(res, Point(rect.x, rect.y), Point(rect.x + rect.width, rect.y + rect.height), GREEN, 2);
	imshow(*winName, res);
}
void GCApplication::setRectInMask()
{
	CV_Assert(!mask.empty());
	mask.setTo(GC_BGD);
	rect.x = max(0, rect.x);
	rect.y = max(0, rect.y);
	rect.width = min(rect.width, image->cols - rect.x);
	rect.height = min(rect.height, image->rows - rect.y);
	(mask(rect)).setTo(Scalar(GC_PR_FGD));
}
void GCApplication::setLblsInMask(int flags, Point p, bool isPr)
{
	vector *bpxls, *fpxls;
	uchar bvalue, fvalue;
	if (!isPr)
	{
		bpxls = &bgdPxls;
		fpxls = &fgdPxls;
		bvalue = GC_BGD;
		fvalue = GC_FGD;
	}
	else
	{
		bpxls = &prBgdPxls;
		fpxls = &prFgdPxls;
		bvalue = GC_PR_BGD;
		fvalue = GC_PR_FGD;
	}
	if (flags & BGD_KEY)
	{
		bpxls->push_back(p);
		circle(mask, p, radius, bvalue, thickness);
	}
	if (flags & FGD_KEY)
	{
		fpxls->push_back(p);
		circle(mask, p, radius, fvalue, thickness);
	}
}
void GCApplication::mouseClick(int event, int x, int y, int flags, void*)
{
	// TODO add bad args check
	switch (event)
	{
	case EVENT_LBUTTONDOWN: // set rect or GC_BGD(GC_FGD) labels
	{
		bool isb = (flags & BGD_KEY) != 0,
			isf = (flags & FGD_KEY) != 0;
		if (rectState == NOT_SET && !isb && !isf)
		{
			rectState = IN_PROCESS;
			rect = Rect(x, y, 1, 1);
		}
		if ((isb || isf) && rectState == SET)
			lblsState = IN_PROCESS;
	}
	break;
	case EVENT_RBUTTONDOWN: // set GC_PR_BGD(GC_PR_FGD) labels
	{
		bool isb = (flags & BGD_KEY) != 0,
			isf = (flags & FGD_KEY) != 0;
		if ((isb || isf) && rectState == SET)
			prLblsState = IN_PROCESS;
	}
	break;
	case EVENT_LBUTTONUP:
		if (rectState == IN_PROCESS)
		{
			rect = Rect(Point(rect.x, rect.y), Point(x, y));
			rectState = SET;
			setRectInMask();
			CV_Assert(bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty());
			showImage();
		}
		if (lblsState == IN_PROCESS)
		{
			setLblsInMask(flags, Point(x, y), false);
			lblsState = SET;
			showImage();
		}
		break;
	case EVENT_RBUTTONUP:
		if (prLblsState == IN_PROCESS)
		{
			setLblsInMask(flags, Point(x, y), true);
			prLblsState = SET;
			showImage();
		}
		break;
	case EVENT_MOUSEMOVE:
		if (rectState == IN_PROCESS)
		{
			rect = Rect(Point(rect.x, rect.y), Point(x, y));
			CV_Assert(bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty());
			showImage();
		}
		else if (lblsState == IN_PROCESS)
		{
			setLblsInMask(flags, Point(x, y), false);
			showImage();
		}
		else if (prLblsState == IN_PROCESS)
		{
			setLblsInMask(flags, Point(x, y), true);
			showImage();
		}
		break;
	}
}
int GCApplication::nextIter()
{
	if (isInitialized)
		grabCut(*image, mask, rect, bgdModel, fgdModel, 1);
	else
	{
		if (rectState != SET)
			return iterCount;
		if (lblsState == SET || prLblsState == SET)
			grabCut(*image, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_MASK);
		else
			grabCut(*image, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_RECT);
		isInitialized = true;
	}
	iterCount++;
	bgdPxls.clear(); fgdPxls.clear();
	prBgdPxls.clear(); prFgdPxls.clear();
	return iterCount;
}
GCApplication gcapp;
static void on_mouse(int event, int x, int y, int flags, void* param)
{
	gcapp.mouseClick(event, x, y, flags, param);
}
int main(int argc, char** argv)
{
	cv::CommandLineParser parser(argc, argv, "{@input| messi5.jpg |}");
	help();
	string filename = parser.get("@input");
	if (filename.empty())
	{
		cout << "\nDurn, empty filename" << endl;
		return 1;
	}
	Mat image = imread(samples::findFile(filename), IMREAD_COLOR);
	if (image.empty())
	{
		cout << "\n Durn, couldn't read image filename " << filename << endl;
		return 1;
	}
	const string winName = "image";
	namedWindow(winName, WINDOW_AUTOSIZE);
	setMouseCallback(winName, on_mouse, 0);
	gcapp.setImageAndWinName(image, winName);
	gcapp.showImage();
	for (;;)
	{
		char c = (char)waitKey(0);
		switch (c)
		{
		case '\x1b':
			cout << "Exiting ..." << endl;
			goto exit_main;
		case 'r':
			cout << endl;
			gcapp.reset();
			gcapp.showImage();
			break;
		case 'n':
			int iterCount = gcapp.getIterCount();
			cout << "<" << iterCount << "... ";
			int newIterCount = gcapp.nextIter();
			if (newIterCount > iterCount)
			{
				gcapp.showImage();
				cout << iterCount << ">" << endl;
			}
			else
				cout << "rect must be determined>" << endl;
			break;
		}
	}
exit_main:
	destroyWindow(winName);
	return 0;
}

OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第7张图片
OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第8张图片
随手操作一下,今日力竭,明天会进一步研究并补充。(to myself:及时总结哦!!!)

7月6日:研究grabCut示例程序。

参考:grabCut使用

1、运行界面:OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第9张图片
解释一下最后四个参数:

	GCD_BGD(=0),背景;
	GCD_FGD(=1),前景;
	GCD_PR_BGD(=2),可能的背景;
	GCD_PR_FGD(=3),可能的前景。

依照上述含义进行兴趣部位的抓取:(只设置背景与前景,可能手法粗略了一些)
OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第10张图片
OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第11张图片
OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第12张图片
可以发现,提取的效果还可以。(应老师的建议,看看不同阴影角度的房屋提取的效果)OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第13张图片
OpenCV学习笔记(四):OpenCV_contrib的安装与测试、grabCut的样例测试_第14张图片
效果也的确可以接受。(肉眼可见一处错误,提取图像下方有一处应该是地面,由于颜色纹理相近被划分到屋顶)

3、grabCut算法原理

可以参考这个:grabCut算法详解

你可能感兴趣的:(opencv,c++)