代码比较乱,自己也是初学。
最近在看视频教学,所以用的是某站上面教学视频的配套代码。
教学视频主要是C/C++在VS环境下的编程,某站上观看量比较多的一个教学视频,下面贴上链接。
我检测的是一块白布上面的黑点,因此很容易检测出来。
某站教学视频链接
//阈值调为90的时候能够检测出污点
#include
#include
#include
using namespace std;
using namespace cv;
Mat src, gray_src, drawImg;
int threshold_v = 170;
int threshold_max = 255;
const char* output_win = "rectangle-demo";
const char* binary_win = "binary image";
RNG rng(12345);
void Contours_Callback(int, void*);
int main(int argc, char** argv) {
src = imread("E:/spot.jpg");//文件路径设置
if (!src.data) {
printf("could not load image...\n");
return -1;
}
cvtColor(src, gray_src, CV_BGR2GRAY);
blur(gray_src, gray_src, Size(3, 3), Point(-1, -1));
const char* source_win = "input image";
namedWindow(source_win, 0);
namedWindow(output_win, 0);
imshow(source_win, src);
createTrackbar("Threshold Value:", output_win, &threshold_v, threshold_max, Contours_Callback);
Contours_Callback(0, 0);
waitKey(0);
return 0;
}
void Contours_Callback(int, void*) {
Mat binary_output;
vector> contours;
vector hierachy;
threshold(gray_src, binary_output, threshold_v, threshold_max, THRESH_BINARY);
//膨胀再腐蚀
Mat element = getStructuringElement(MORPH_RECT, Size(11, 11), Point(-1, -1)); //定义结构元素
dilate(binary_output, binary_output, element);
namedWindow("dilate", 0);
imshow("dilate", binary_output);
erode(binary_output, binary_output, element);
namedWindow("erode", 0);
imshow("erode", binary_output);
namedWindow(binary_win, 0);
imshow("binary image", binary_output);
findContours(binary_output, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(-1, -1));
vector> contours_ploy(contours.size());
vector ploy_rects(contours.size());
vector ccs(contours.size());
vector radius(contours.size());
vector minRects(contours.size());
vector myellipse(contours.size());
for (size_t i = 0; i < contours.size(); i++) {
approxPolyDP(Mat(contours[i]), contours_ploy[i], 3, true);
ploy_rects[i] = boundingRect(contours_ploy[i]);
/*minEnclosingCircle(contours_ploy[i], ccs[i], radius[i]);*/
//if (contours_ploy[i].size() > 5) {
// myellipse[i] = fitEllipse(contours_ploy[i]);
// minRects[i] = minAreaRect(contours_ploy[i]);
//}
}
// draw it
src.copyTo(drawImg);
Point2f pts[4];
for (size_t t = 0; t < contours.size(); t++) {
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
rectangle(drawImg, ploy_rects[t], color, 2, 8);
/*circle(drawImg, ccs[t], radius[t], color, 2, 8);*/
//if (contours_ploy[t].size() > 5) {
// ellipse(drawImg, myellipse[t], color, 1, 8);
// minRects[t].points(pts);
// for (int r = 0; r < 4; r++) {
// line(drawImg, pts[r], pts[(r + 1) % 4], color, 1, 8);
// }
//}
}
imshow(output_win, drawImg);
return;
}