#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
string rootdir = "F:/Study/opencv/opencv-4.8.0/opencv/sources/samples/data/";
void sort_box(vector<Rect> &boxes) {
int size = boxes.size();
for (int i = 0; i < size - 1; i++) {
for (int j = i; j < size; j++) {
int x = boxes[j].x;
int y = boxes[j].y;
if (y < boxes[i].y) {
Rect temp = boxes[i];
boxes[i] = boxes[j];
boxes[j] = temp;
}
}
}
}
void detect_defect(Mat &binary, vector<Rect> rects, vector<Rect> &defect, Mat &tpl) {
int h = tpl.rows;
int w = tpl.cols;
int size = rects.size();
for (int i = 0; i < size; i++) {
// 构建diff
Mat roi = binary(rects[i]);
resize(roi, roi, tpl.size());
Mat mask;
subtract(tpl, roi, mask);
Mat se = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
morphologyEx(mask, mask, MORPH