본문 바로가기
전체보기/C&C++

find_red.cpp

by 피망우유 2019. 11. 22.
#include <opencv2/opencv.hpp>

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <vector>

using namespace cv;
using namespace std;


int main()
{

	Mat image1;   // 웹캠 원본 영상
	VideoCapture cap(0); // open No. 0 camera

	vector<Point> save_poly;

	int iLowH, iHighH, iLowS, iHighS, iLowV, iHighV;

	if (!cap.isOpened()) {
		cout << "camera is not Opened\n" << endl;
		return -1;
	}
		
	namedWindow("Webcam Frame Capture");

	while (true)
	{
		// 특징점 벡터****************************************************
		cap >> image1;	


		//////////////////////Color Detection///////////////////////////
		Mat imgHSV;

		cvtColor(image1, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV

		///RED///

		Mat RED;

		inRange(imgHSV, Scalar(iLowH = 0, iLowS = 78, iLowV = 150), Scalar(iHighH = 16, iHighS = 255, iHighV = 255), RED); //Threshold the image

		//morphological opening (remove small objects from the foreground)
		erode(RED, RED, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
		dilate(RED, RED, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));

		//morphological closing (fill small holes in the foreground)
		dilate(RED, RED, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
		erode(RED, RED, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));

		imshow("RED", RED); //show the thresholded image

		// 외곽선을 포함하는 벡터 
		vector<vector<Point>> contours_R;

		// 연결 성분의 외곽선 얻기
		findContours(RED, contours_R, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

		// 모든 외관선에 대해  
		vector<vector<Point>>::iterator it_R = contours_R.begin();

		// POLY  
		vector<Point> poly_R;  // poly 벡터로 생성되어있졍!!!! 요거 요거ㅗ!!!

		float R_X = 0.0;
		float R_Y = 0.0;

		while (it_R != contours_R.end())
		{
			poly_R.clear();

			// 다각형으로 외곽선 근하솨                     
			approxPolyDP(*it_R, poly_R, 10, true);

			if (poly_R.size() > 4)
			{
				polylines(image1, poly_R, true, Scalar(0, 0, 255), 2);

				for (vector<int>::size_type index = 0; index < poly_R.size(); ++index)
				{
					R_X = R_X + poly_R.at(index).x;
					R_Y = R_Y + poly_R.at(index).y;
				}

				R_X = R_X / poly_R.size();
				R_Y = R_Y / poly_R.size();

				circle(image1, Point(R_X, R_Y), 2, Scalar(0, 0, 255), 2);
				
			}
			++it_R;
		}

		//////////////////////////////////////////////////////////////////////////////////////////////////////////////RED

		imshow("Webcam Frame Capture", image1);

		int key = waitKey(10);

		if (key == 32)      //Space key  
			break;

	}

	return 0;

}

 

'전체보기 > C&C++' 카테고리의 다른 글

int 형을 string 으로, integer to string c++  (0) 2019.11.14
VS2017 (성가신) 에러  (0) 2019.11.14
VS2017 단축키 변경  (0) 2019.11.14

댓글