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 118 119 120 121 122 123
|
#include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" using namespace cv; using namespace std;
#define WINDOW_NAME1 "Original" #define WINDOW_NAME2 "Result"
Mat g_srcImage; Mat g_grayImage; int g_nThresh = 50; int g_nMaxThresh = 255; RNG g_rng(12345);
void on_ContoursChange(int, void *); static void ShowHelpText();
int main() { ShowHelpText();
g_srcImage = imread("1.jpg", 1); if (!g_srcImage.data) { printf("读取图片错误,请确定目录下是否有imread函数指定的图片存在~! \n"); return false; }
cvtColor(g_srcImage, g_grayImage, COLOR_BGR2GRAY); blur(g_grayImage, g_grayImage, Size(3, 3));
namedWindow(WINDOW_NAME1, WINDOW_AUTOSIZE); imshow(WINDOW_NAME1, g_srcImage);
createTrackbar(" 阈值:", WINDOW_NAME1, &g_nThresh, g_nMaxThresh, on_ContoursChange); on_ContoursChange(0, 0);
waitKey(0);
return (0); }
void on_ContoursChange(int, void *) { Mat threshold_output; vector<vector<Point>> contours; vector<Vec4i> hierarchy;
threshold(g_grayImage, threshold_output, g_nThresh, 255, THRESH_BINARY);
findContours(threshold_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
vector<vector<Point>> contours_poly(contours.size()); vector<Rect> boundRect(contours.size()); vector<Point2f> center(contours.size()); vector<float> radius(contours.size());
for (unsigned int i = 0; i < contours.size(); i++) { approxPolyDP(Mat(contours[ i ]), contours_poly[ i ], 3, true); boundRect[ i ] = boundingRect(Mat(contours_poly[ i ])); minEnclosingCircle(contours_poly[ i ], center[ i ], radius[ i ]); }
Mat drawing = Mat::zeros(threshold_output.size(), CV_8UC3); for (int unsigned i = 0; i < contours.size(); i++) { Scalar color = Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255)); drawContours(drawing, contours_poly, i, color, 1, 8, vector<Vec4i>(), 0, Point()); rectangle(drawing, boundRect[ i ].tl(), boundRect[ i ].br(), color, 2, 8, 0); circle(drawing, center[ i ], (int)radius[ i ], color, 2, 8, 0); }
namedWindow(WINDOW_NAME2, WINDOW_AUTOSIZE); imshow(WINDOW_NAME2, drawing); }
static void ShowHelpText() { printf("\n\n\t\t\t非常感谢购买《OpenCV3编程入门》一书!\n"); printf("\n\n\t\t\t此为本书OpenCV3版的第75个配套示例程序\n"); printf("\n\n\t\t\t 当前使用的OpenCV版本为:" CV_VERSION); printf("\n\n ----------------------------------------------------------------------------\n");
printf("\n\n\n\t欢迎来到【创建包围轮廓的矩形和圆形边界框】示例程序~\n\n"); printf("\n\n\t按键操作说明: \n\n" "\t\t键盘按键【ESC】- 退出程序\n\n" "\t\t滑动滚动条 - 改变阈值\n\n"); }
|