-
Notifications
You must be signed in to change notification settings - Fork 76
/
Project1.cpp
105 lines (78 loc) · 2.58 KB
/
Project1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
///////////////// Project 1 - Virtual Painter //////////////////////
Mat img;
VideoCapture cap(0);
vector<vector<int>> newPoints; // to store all points
///////////////////// COLOR VALUES ////////////////////////////////
// hmin, smin, vmin hmax, smax, vmax
vector<vector<int>> myColors{ {124,48,117,143,170,255}, // Purple
{68,72,156,102,126,255} };// Green
vector<Scalar> myColorValues{ {255,0,255}, // Purple
{0,255,0} };// Green
////////////////////////////////////////////////////////////////////
Point getContours(Mat image) {
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(image, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
//drawContours(img, contours, -1, Scalar(255, 0, 255), 2);
vector<vector<Point>> conPoly(contours.size());
vector<Rect> boundRect(contours.size());
Point myPoint(0, 0);
for (int i = 0; i < contours.size(); i++)
{
int area = contourArea(contours[i]);
cout << area << endl;
string objectType;
if (area > 1000)
{
float peri = arcLength(contours[i], true);
approxPolyDP(contours[i], conPoly[i], 0.02 * peri, true);
cout << conPoly[i].size() << endl;
boundRect[i] = boundingRect(conPoly[i]);
myPoint.x = boundRect[i].x + boundRect[i].width / 2;
myPoint.y = boundRect[i].y;
//drawContours(img, conPoly, i, Scalar(255, 0, 255), 2);
//rectangle(img, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 5);
}
}
return myPoint;
}
vector<vector<int>> findColor(Mat img)
{
Mat imgHSV;
cvtColor(img, imgHSV, COLOR_BGR2HSV);
for (int i = 0; i < myColors.size(); i++)
{
Scalar lower(myColors[i][0], myColors[i][1], myColors[i][2]);
Scalar upper(myColors[i][3], myColors[i][4], myColors[i][5]);
Mat mask;
inRange(imgHSV, lower, upper, mask);
//imshow(to_string(i), mask);
Point myPoint = getContours(mask);
if (myPoint.x != 0 ) {
newPoints.push_back({ myPoint.x,myPoint.y,i });
}
}
return newPoints;
}
void drawOnCanvas(vector<vector<int>> newPoints, vector<Scalar> myColorValues)
{
for (int i = 0; i < newPoints.size(); i++)
{
circle(img, Point(newPoints[i][0],newPoints[i][1]), 10, myColorValues[newPoints[i][2]], FILLED);
}
}
void main() {
while (true) {
cap.read(img);
newPoints = findColor(img);
drawOnCanvas(newPoints, myColorValues);
imshow("Image", img);
waitKey(1);
}
}