C++的OpenCV边缘检测代码

使用时更改图片地址

#include
#include
#include
#include
#include"opencv2/imgcodecs.hpp"
#include
#include
using namespace std;
using namespace cv;
#pragma comment (lib,"opencv_world455d.lib")
int main(int argc, char* argv[])
{
	int op;
	printf("enter 1--4");
	scanf_s("%d", &op);
	
	Mat imageSource = imread("F:\\C++\\OPENCVtest\\Project2\\PA.png", 0);
	imshow("Source Image", imageSource);
	Mat image;

	GaussianBlur(imageSource, image, Size(3, 3), 0);//高斯模糊,size影响核的大小
	Canny(image, image, 100, 250);
	vector> contours;
	vector hierarchy;
	if (op == 1)
	{
		findContours(image, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point());
	}
	else if (op == 2)
	{
		findContours(image, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE, Point());
	}
	else if (op == 3)
	{
		findContours(image, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE, Point());
	}
	else if (op == 4)
	{
		findContours(image, contours, hierarchy, RETR_TREE, CHAIN_APPROX_NONE, Point());
	}

	Mat imageContours = Mat::zeros(image.size(), CV_8UC1);
	Mat Contours=Mat::zeros(image.size(), CV_8UC1);
	for (int i = 0; i < contours.size(); i++)
	{
		for (int j = 0; j < contours[i].size(); j++)
		{
			Point P = Point(contours[i][j].x, contours[i][j].y);
			Contours.at(P) = 255;
		}
		char ch[256];
		sprintf_s(ch, "%d", i);
		string str = ch;
		cout << "向量第" << str << "个元素为" << endl << hierarchy[i] << endl;
		drawContours(imageContours, contours, i, Scalar(255), 1, 8, hierarchy);
	}
	imshow("Contours image", imageContours);
	imshow("Point of contours", Contours);
	waitKey(0);
	return 0;


}

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