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 106 107 108 109 110 111 112 113 114 115 116 117
| #include<opencv2/imgcodecs.hpp> #include<opencv2/highgui.hpp> #include<opencv2/imgproc.hpp> #include<iostream> #include<opencv2/core.hpp>
using namespace std; using namespace cv;
Mat img; vector<vector<int>> newPoints;
vector<vector<int>> myColors{ {0,142,120,179,255,255}, {0,0,0,0,0,0} };
vector<Scalar> myColorValues{ {255,0,255}, {0,255,0} };
Point getContours(Mat imgDil) { vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(imgDil, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE);
vector<vector<Point>> conPoly(contours.size()); vector<Rect> boundRect(contours.size());
Point myPoint(0, 0);
for (int i = 0; i < contours.size(); i++) { double area = contourArea(contours[i]);
string objectType; if (area > 10) { double peri = arcLength(contours[i], true); approxPolyDP(contours[i], conPoly[i], 0.02 * peri, true);
boundRect[i] = boundingRect(conPoly[i]);
myPoint.x = boundRect[i].x; myPoint.y = boundRect[i].y + boundRect[i].height / 2;
if (conPoly[i].size() > 4) putText(img, "Small Ball", Point(boundRect[i].x, boundRect[i].y - 10), FONT_HERSHEY_PLAIN, 3, Scalar(0, 255, 0), 6);
rectangle(img, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 5); drawContours(img, conPoly, i, Scalar(255, 0, 0), 2); } } 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); Point myPoint = getContours(mask); if (myPoint.x != 0 && myPoint.y != 0) { newPoints.push_back({ myPoint.x,myPoint.y,i }); } } return newPoints;
}
void drawOnCanvas(vector<vector<int>> newPoints, vector<Scalar> myColorValues) { for (int i = 1; i < newPoints.size(); i++) { line(img, Point(newPoints[i - 1][0], newPoints[i - 1][1]), Point(newPoints[i][0], newPoints[i][1]), Scalar(0, 255, 255), 10); } }
int main() { VideoCapture cap("D:/Summer Holiday Practice/opencv learning/Resources/TrackBall2.mp4"); if (!cap.isOpened()) { cout << "fail to open!" << endl; return -1; } char c; bool stop = false;
namedWindow("Image", WINDOW_FREERATIO); while (c = waitKey(1)) { if (c == 27) break; if (c == 'p') { stop = !stop; } if (!stop) { cap >> img;
newPoints = findColor(img); drawOnCanvas(newPoints, myColorValues); imshow("Image", img); } } return 0; }
|