테두리 추출

2020. 2. 13. 13:26기타

웹에서 이것저것 검색하면서 짬뽕으로 테두리 추출함

 

다음에 써 먹을 데가 있을라나?

 

#include <iostream>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;

string title = "Main Window";

int threshold_min = 200;
int threshold_max = 255;
int obj_index = 0;

void onChange(int value, void* userdata) {
	cout << "Value : " << value << endl;
}



int main()
{

	namedWindow(title, WINDOW_AUTOSIZE);
	createTrackbar("Min Threshold", title, &threshold_min, 255,  onChange);
	createTrackbar("Max Threshold", title, &threshold_max, 255, onChange);
	createTrackbar("Object",        title, &obj_index,     255, onChange);

	cv::VideoCapture cap(0);
	cv::Mat image, gray, binary, draw;

	vector<vector<Point> > contours;
	vector<Vec4i> hierarchy;

	while (true) {

		//cap >> image;

		image = cv::imread("image.png");
		draw = image.clone();
		draw = 0;

		//cap.read(image);
		// check if we succeeded

		if (image.empty()) {
			std::cerr << "ERROR! blank frame grabbed\n";
			break;
		}

		cv::cvtColor(image, gray, cv::COLOR_RGB2GRAY);
		cv::threshold(gray, binary, threshold_min, threshold_max, cv::THRESH_BINARY);
		cv::bitwise_not(binary, binary);

		cv::findContours(binary, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
		
		Scalar color = Scalar(255, 255, 255);
		Scalar sel_color = Scalar(255, 0, 0);

		for (int i = 0; i < contours.size(); ++i)
		{
			if(obj_index == i)
				cv::drawContours(draw, contours, i, sel_color, 1);
			else
				cv::drawContours(draw, contours, i, color, 1);
		}

		cv::imshow("binary", binary);
		cv::imshow(title, image);
		cv::imshow("draw", draw);
		if (cv::waitKey(10) == 27)
			break;
	}

    return 0;
}