영상처리

[OpenCV 3.2] 비디오 영상으로부터 findcontours 적용

GR_Wyatt 2019. 3. 28. 11:00
반응형

앞에서 lena 사진을 이용하여 findcontours()함수를 적용하였고, 이번에는 웹캠 영상을 받아서 실시간으로 contours를 그리는 코드이다. 입력 영상이 비디오이냐 사진이냐의 차이만 있을 뿐이다.

#include "opencv2\opencv.hpp"
#include <iostream>
#include <cstdlib>
using namespace cv;
using namespace std;
RNG rng(12345);

int main(int argc, char ** argv)
{
	VideoCapture cap(0);
	if (!cap.isOpened())
	{
		cout << "[INFO] Input error" << endl;
		return -1;
	}
	else
		cout << "[INFO] Input success" << endl;

	Mat frame, GRAY;
	while (1)
	{
		cap.read(frame);
		cvtColor(frame, GRAY, COLOR_BGR2GRAY);
		imshow("Source", frame);
		
		Mat cannyimage;
		Canny(GRAY, cannyimage, 10, 100);
		imshow("Canny", cannyimage);

		vector<vector<Point>> contours;
		vector<Vec4i> hierarchy;
		findContours(cannyimage, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
		
		Mat dstimage = Mat::zeros(frame.rows, frame.cols, CV_8UC3);
		for (int i = 0; i< contours.size(); i++)
		{
			Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
			drawContours(dstimage, contours, i, color, 2, 8, hierarchy, 0, Point());
		}

		imshow("dstimage", dstimage);

		if (waitKey(10) == 27) break;
	}
	return 0;
}

뭔가 엄청 이쁜 결과가 나온다 ㅎㅎㅎㅎ

반응형