#include #include #include #include #include #include #include #include #include #include #include using namespace cv; using namespace cv::dnn; // 图像结构体定义 typedef struct { unsigned char* data; int width; int height; int channels; } Image; static std::string last_error; // YOLO 检测器 class YOLODetector { public: Net net; std::vector classNames; float confThreshold; float nmsThreshold; YOLODetector() : confThreshold(0.5f), nmsThreshold(0.4f) {} }; static std::map yolo_detectors; extern "C" { // 图像解码 Image* cv_imdecode(const unsigned char* buf, size_t size) { try { std::vector data(buf, buf + size); cv::Mat mat = cv::imdecode(data, cv::IMREAD_COLOR); if (mat.empty()) { last_error = "无法解码图像"; return nullptr; } Image* img = new Image(); img->width = mat.cols; img->height = mat.rows; img->channels = mat.channels(); size_t data_size = mat.total() * mat.elemSize(); img->data = (unsigned char*)malloc(data_size); memcpy(img->data, mat.data, data_size); return img; } catch (const std::exception& e) { last_error = e.what(); return nullptr; } } // 释放图像 void cv_image_free(Image* img) { if (img) { if (img->data) { free(img->data); } delete img; } } // 加载 YOLO ONNX 模型 int cv_yolo_load(const char* name, const char* model_path, const char* classes_path) { try { YOLODetector* detector = new YOLODetector(); // 加载 ONNX 模型 detector->net = readNetFromONNX(model_path); if (detector->net.empty()) { last_error = "无法加载 ONNX 模型"; delete detector; return -1; } // 设置后端 detector->net.setPreferableBackend(DNN_BACKEND_OPENCV); detector->net.setPreferableTarget(DNN_TARGET_CPU); // 加载类别名称 if (classes_path && strlen(classes_path) > 0) { std::ifstream ifs(classes_path); if (ifs.is_open()) { std::string line; while (std::getline(ifs, line)) { if (!line.empty()) { detector->classNames.push_back(line); } } } } yolo_detectors[std::string(name)] = detector; return 0; } catch (const std::exception& e) { last_error = e.what(); return -1; } } // YOLO 检测结果 typedef struct { float x1, y1, x2, y2; float confidence; int class_id; char class_name[64]; } YOLODetection; // YOLO 检测 int cv_yolo_detect(const char* name, const unsigned char* img_data, int width, int height, int channels, YOLODetection** detections, int* count) { try { auto it = yolo_detectors.find(std::string(name)); if (it == yolo_detectors.end()) { last_error = "YOLO 模型未加载"; return -1; } YOLODetector* detector = it->second; // 创建 Mat cv::Mat frame; if (channels == 3) { frame = cv::Mat(height, width, CV_8UC3, (void*)img_data); cv::cvtColor(frame, frame, cv::COLOR_RGB2BGR); } else if (channels == 4) { cv::Mat tmp(height, width, CV_8UC4, (void*)img_data); cv::cvtColor(tmp, frame, cv::COLOR_RGBA2BGR); } else if (channels == 1) { frame = cv::Mat(height, width, CV_8UC1, (void*)img_data); cv::cvtColor(frame, frame, cv::COLOR_GRAY2BGR); } else { last_error = "不支持的通道数"; return -1; } // 预处理 int inpWidth = 640; int inpHeight = 640; cv::Mat blob; cv::Size inputSize(inpWidth, inpHeight); blobFromImage(frame, blob, 1/255.0, inputSize, Scalar(0,0,0), true, false); // 推理 detector->net.setInput(blob); std::vector outs; detector->net.forward(outs, detector->net.getUnconnectedOutLayersNames()); // 后处理 std::vector classIds; std::vector confidences; std::vector boxes; float scaleX = (float)frame.cols / inpWidth; float scaleY = (float)frame.rows / inpHeight; for (size_t i = 0; i < outs.size(); ++i) { // YOLO11 输出格式: [1, 5+num_classes, 8400] (通道在前) // 需要转置为 [8400, 5+num_classes] Mat out = outs[i]; int num_detections = out.size[2]; // 8400 int num_features = out.size[1]; // 5 + num_classes // 转置输出 Mat out_transposed; if (out.size[1] < out.size[2]) { // [1, features, detections] -> [detections, features] Mat out_2d(out.size[1], out.size[2], CV_32F, out.data); transpose(out_2d, out_transposed); } else { out_transposed = out; } for (int j = 0; j < num_detections; ++j) { float* data = out_transposed.ptr(j); float obj_conf = data[4]; if (obj_conf < detector->confThreshold) continue; // 找最大类别分数 int classId = 0; float maxScore = 0; for (int k = 5; k < num_features; ++k) { if (data[k] > maxScore) { maxScore = data[k]; classId = k - 5; } } float confidence = obj_conf * maxScore; if (confidence > detector->confThreshold) { float cx = data[0]; float cy = data[1]; float w = data[2]; float h = data[3]; int centerX = (int)(cx * scaleX); int centerY = (int)(cy * scaleY); int width = (int)(w * scaleX); int height = (int)(h * scaleY); int left = centerX - width / 2; int top = centerY - height / 2; classIds.push_back(classId); confidences.push_back(confidence); boxes.push_back(Rect(left, top, width, height)); } } } // NMS std::vector indices; NMSBoxes(boxes, confidences, detector->confThreshold, detector->nmsThreshold, indices); // 分配结果 *count = (int)indices.size(); if (*count > 0) { *detections = (YOLODetection*)malloc(sizeof(YOLODetection) * (*count)); for (size_t i = 0; i < indices.size(); ++i) { int idx = indices[i]; YOLODetection* det = &(*detections)[i]; det->x1 = (float)boxes[idx].x; det->y1 = (float)boxes[idx].y; det->x2 = (float)(boxes[idx].x + boxes[idx].width); det->y2 = (float)(boxes[idx].y + boxes[idx].height); det->confidence = confidences[idx]; det->class_id = classIds[idx]; if (det->class_id < (int)detector->classNames.size()) { strncpy(det->class_name, detector->classNames[det->class_id].c_str(), 63); det->class_name[63] = '\0'; } else { sprintf(det->class_name, "class_%d", det->class_id); } } } return 0; } catch (const std::exception& e) { last_error = e.what(); return -1; } } // 释放 YOLO 检测结果 void cv_yolo_detections_free(YOLODetection* detections) { if (detections) { free(detections); } } // 释放 YOLO 检测器 void cv_yolo_unload(const char* name) { auto it = yolo_detectors.find(std::string(name)); if (it != yolo_detectors.end()) { delete it->second; yolo_detectors.erase(it); } } // 滑块缺口匹配 int cv_slider_match(const Image* target, const Image* background, int* out_x) { try { cv::Mat target_mat(target->height, target->width, CV_8UC3, target->data); cv::Mat bg_mat(background->height, background->width, CV_8UC3, background->data); cv::Mat target_gray, bg_gray; cv::cvtColor(target_mat, target_gray, cv::COLOR_BGR2GRAY); cv::cvtColor(bg_mat, bg_gray, cv::COLOR_BGR2GRAY); // Canny 边缘检测 cv::Mat target_edges, bg_edges; cv::Canny(target_gray, target_edges, 100, 200); cv::Canny(bg_gray, bg_edges, 100, 200); // 模板匹配 cv::Mat result; cv::matchTemplate(bg_edges, target_edges, result, cv::TM_CCOEFF_NORMED); double min_val, max_val; cv::Point min_loc, max_loc; cv::minMaxLoc(result, &min_val, &max_val, &min_loc, &max_loc); *out_x = max_loc.x; return 0; } catch (const std::exception& e) { last_error = e.what(); return -1; } } // 阴影滑块匹配(对齐上游 AntiCAP 的 solve_slider_comparison) // // 上游语义:target 与 background 是同一张图的两份,只有滑块阴影区域不同。 // image = ImageChops.difference(background, target) // image = image.point(lambda x: 255 if x > 80 else 0) # 逐通道阈值 80 // 逐列扫描:某列差异像素 >= 5 个 → start_x = 列号 + 2,start_y = 首次达到 5 个时的行号 - 5 // // 旧实现有两个问题: // 1) 不校验尺寸,target/background 尺寸不同时 absdiff 直接抛 OpenCV -209; // 2) threshold 后仍是三通道图像就丢给 findContours,报 // "FindContours supports only CV_8UC1 images"。 int cv_slider_comparison(const Image* target, const Image* background, int* out_x, int* out_y) { try { if (target->width != background->width || target->height != background->height) { last_error = "target 与 background 尺寸必须一致(阴影滑块是同一张图的两份)"; return -2; } cv::Mat t_mat(target->height, target->width, CV_8UC3, target->data); cv::Mat b_mat(background->height, background->width, CV_8UC3, background->data); cv::Mat diff; cv::absdiff(b_mat, t_mat, diff); // BGR 各自绝对差 // 逐通道 > 80 记为差异像素,合成单通道掩码 std::vector ch(3); cv::split(diff, ch); cv::Mat m0, m1, m2, mask; cv::compare(ch[0], 80, m0, cv::CMP_GT); cv::compare(ch[1], 80, m1, cv::CMP_GT); cv::compare(ch[2], 80, m2, cv::CMP_GT); cv::bitwise_or(m0, m1, mask); cv::bitwise_or(mask, m2, mask); const int H = mask.rows, W = mask.cols; int start_x = 0, start_y = 0; bool found = false; for (int x = 0; x < W && !found; ++x) { int count = 0; for (int y = 0; y < H; ++y) { if (mask.at(y, x) == 0) continue; ++count; if (count >= 5 && start_y == 0) { start_y = y - 5; if (start_y < 0) start_y = 0; } } if (count >= 5) { start_x = x + 2; if (start_x > W) start_x = W; found = true; } } if (!found) { // 退化情况:没有满足列扫描的区域,退回最大差异区域的外接矩形 std::vector> contours; cv::findContours(mask.clone(), contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); int max_area = 0; cv::Rect best; for (const auto& c : contours) { cv::Rect r = cv::boundingRect(c); if (r.width * r.height > max_area) { max_area = r.width * r.height; best = r; } } start_x = best.x; start_y = best.y; } *out_x = start_x; *out_y = start_y; return 0; } catch (const std::exception& e) { last_error = e.what(); return -1; } } // 检测旋转角度(简化版,使用特征点) float cv_detect_rotation(const Image* img) { try { cv::Mat mat(img->height, img->width, CV_8UC3, img->data); // 转灰度 cv::Mat gray; cv::cvtColor(mat, gray, cv::COLOR_BGR2GRAY); // 简化处理:返回 0 度 // 实际实现需要更复杂的特征点匹配 return 0.0f; } catch (const std::exception& e) { last_error = e.what(); return 0.0f; } } // 双图旋转(按上游 AntiCAP solve_double_rotate 逐行移植) // // 上游流程: // 1) 内圈:连续 rot90 四次,每次数「整行只有纯黑/纯白像素」的行数,得到上下左右要剪掉的边; // 剪完按短边取偶数直径 resize,半径 = 直径/2。 // 2) 外圈:以中心为起点,沿四条射线往里走,找到第一个「既不是纯黑也不是纯白」的像素, // 再外扩 resize_check_pixel 像素,得到外圈要剪的边;剪完同样 resize。 // 3) 两边各做一个圆环 mask(外半径 R、内半径 R-check_pixel),得到内圈环带与外圈环带。 // 4) 把内圈环带按候选角度 warpAffine 旋转,和 外圈环带 做 matchTemplate(TM_CCOEFF_NORMED), // 取最大相似度。先粗搜 1..360 step 10,命中更好就追加 angle±10 的细化窗口,最多保留 5 个候选。 // 5) inner_angle = round(best_angle * speed_ratio / (speed_ratio + 1), 2) // // 返回值:0 成功;-1 异常;-2 裁剪后为空(调用方当参数错误处理)。 extern "C" int cv_double_rotate( const Image* inner, const Image* outer, int check_pixel, double speed_ratio, int grayscale, int anticlockwise, int cut_pixel_value, int* out_raw_angle, double* out_inner_angle, double* out_similarity) { try { auto to_mat = [](const Image* im, bool gray) { cv::Mat m(im->height, im->width, CV_8UC3, im->data); cv::Mat out; if (gray) { cv::cvtColor(m, out, cv::COLOR_BGR2GRAY); } else { out = m.clone(); } return out; }; cv::Mat inner_img = to_mat(inner, grayscale != 0); cv::Mat outer_img = to_mat(outer, grayscale != 0); const bool is_gray = (inner_img.channels() == 1); auto is_blank = [&](const cv::Mat& m, int y, int x) -> bool { if (is_gray) { int v = (int)m.at(y, x); return v == 0 || v == 255; } cv::Vec3b p = m.at(y, x); bool black = (p[0] == 0 && p[1] == 0 && p[2] == 0); bool white = (p[0] == 255 && p[1] == 255 && p[2] == 255); return black || white; }; auto is_cut = [&](const cv::Mat& m, int y, int x) -> bool { if (is_gray) { int v = (int)m.at(y, x); return v <= cut_pixel_value || v >= 255 - cut_pixel_value; } cv::Vec3b p = m.at(y, x); for (int k = 0; k < 3; ++k) { if (p[k] <= cut_pixel_value || p[k] >= 255 - cut_pixel_value) return true; } return false; }; // ---------- 1) 内圈剪边 ---------- const int h_inner = inner_img.rows, w_inner = inner_img.cols; int cut_inner[4] = {0, 0, 0, 0}; for (int k = 0; k < 4; ++k) { cv::Mat rot; // np.rot90 是逆时针:k=0 原图,1=逆时针 90°,2=180°,3=顺时针 90°。 // cv::rotate 的枚举是 0=顺时针90、1=180、2=逆时针90,两者不能直接把 k 传进去。 switch (k) { case 0: rot = inner_img.clone(); break; case 1: cv::rotate(inner_img, rot, cv::ROTATE_90_COUNTERCLOCKWISE); break; case 2: cv::rotate(inner_img, rot, cv::ROTATE_180); break; default: cv::rotate(inner_img, rot, cv::ROTATE_90_CLOCKWISE); break; } int cnt = 0; for (int y = 0; y < rot.rows; ++y) { bool only_blank = true; for (int x = 0; x < rot.cols; ++x) { if (!is_blank(rot, y, x)) { only_blank = false; break; } } if (only_blank) cnt++; else break; } cut_inner[k] = cnt; } cut_inner[2] = h_inner - cut_inner[2]; cut_inner[3] = w_inner - cut_inner[3]; int up_i = cut_inner[0], left_i = cut_inner[1], down_i = cut_inner[2], right_i = cut_inner[3]; if (down_i <= up_i || right_i <= left_i || up_i < 0 || left_i < 0 || down_i > h_inner || right_i > w_inner) { last_error = "内圈裁剪区域为空或越界(图片可能不是环形旋转验证码)"; return -2; } cv::Mat cut_inner_img = inner_img(cv::Rect(left_i, up_i, right_i - left_i, down_i - up_i)).clone(); int diameter_inner = (std::min(cut_inner_img.rows, cut_inner_img.cols) / 2) * 2; if (diameter_inner <= 0) { last_error = "内圈直径为 0"; return -2; } cv::resize(cut_inner_img, cut_inner_img, cv::Size(diameter_inner, diameter_inner)); int cut_inner_radius = cut_inner_img.rows / 2; // ---------- 2) 外圈剪边 ---------- const int h_outer = outer_img.rows, w_outer = outer_img.cols; int yc = h_outer / 2, xc = w_outer / 2; int resize_check_pixel = (int)std::ceil( (double)cut_inner_radius / (double)(cut_inner_radius - check_pixel) * (double)check_pixel); int cut_outer[4] = {0, 0, 0, 0}; int idx = 0; for (int i : {-1, 1}) { for (int p : {yc, xc}) { int pos = p + i * cut_inner_radius; for (int step = 0; step < p - cut_inner_radius; ++step) { int p_x = (idx % 2 == 0) ? xc : pos; int p_y = (idx % 2 == 0) ? pos : yc; if (p_x < 0 || p_y < 0 || p_x >= w_outer || p_y >= h_outer) { pos += i; continue; } if (is_blank(outer_img, p_y, p_x)) { pos += i; continue; } if (is_cut(outer_img, p_y, p_x)) { pos += i; continue; } break; } cut_outer[idx] = pos + i * resize_check_pixel; idx++; } } int up_o = cut_outer[0], left_o = cut_outer[1], down_o = cut_outer[2], right_o = cut_outer[3]; up_o = std::max(0, std::min(up_o, h_outer)); down_o = std::max(0, std::min(down_o, h_outer)); left_o = std::max(0, std::min(left_o, w_outer)); right_o = std::max(0, std::min(right_o, w_outer)); if (down_o <= up_o || right_o <= left_o) { last_error = "外圈裁剪区域为空(外圈可能不是圆环)"; return -2; } cv::Mat cut_outer_img = outer_img(cv::Rect(left_o, up_o, right_o - left_o, down_o - up_o)).clone(); int diameter_outer = (std::min(cut_outer_img.rows, cut_outer_img.cols) / 2) * 2; if (diameter_outer <= 0) { last_error = "外圈直径为 0"; return -2; } cv::resize(cut_outer_img, cut_outer_img, cv::Size(diameter_outer, diameter_outer)); // ---------- 3) 圆环 mask ---------- int radius_inner = cut_inner_img.rows / 2; cv::Mat mask_inner = cv::Mat::zeros(radius_inner * 2, radius_inner * 2, CV_8UC1); cv::circle(mask_inner, cv::Point(radius_inner, radius_inner), radius_inner, 255, -1); cv::circle(mask_inner, cv::Point(radius_inner, radius_inner), radius_inner - check_pixel, 0, -1); cv::Mat inner_annulus(radius_inner * 2, radius_inner * 2, cut_inner_img.type(), cv::Scalar::all(0)); cut_inner_img.copyTo(inner_annulus, mask_inner); int radius_outer = cut_outer_img.rows / 2; cv::Mat mask_outer = cv::Mat::zeros(radius_outer * 2, radius_outer * 2, CV_8UC1); cv::circle(mask_outer, cv::Point(radius_outer, radius_outer), radius_outer, 255, -1); cv::circle(mask_outer, cv::Point(radius_outer, radius_outer), radius_outer - check_pixel, 0, -1); cv::Mat outer_annulus(radius_outer * 2, radius_outer * 2, cut_outer_img.type(), cv::Scalar::all(0)); cut_outer_img.copyTo(outer_annulus, mask_outer); if (inner_annulus.cols != outer_annulus.cols || inner_annulus.rows != outer_annulus.rows) { // matchTemplate 要求尺寸一致:把内圈环带缩到外圈的尺寸 cv::resize(inner_annulus, inner_annulus, outer_annulus.size()); } // 上游例图只有 ~110px;遇到大图(400~600px)时 matchTemplate 每次要几十毫秒, // 36 次粗搜就会把接口拖到分钟级。这里把环带统一压到 256 以内,角度精度不受影响。 const int kMaxAnnulus = 256; if (inner_annulus.cols > kMaxAnnulus) { cv::resize(inner_annulus, inner_annulus, cv::Size(kMaxAnnulus, kMaxAnnulus)); cv::resize(outer_annulus, outer_annulus, cv::Size(kMaxAnnulus, kMaxAnnulus)); } // ---------- 4) 由粗到细搜索 ---------- // // 上游是「边遍历边往列表里追加细化窗口」,Python 的 list 迭代器允许这种写法; // 直接用下标 for 去模拟会退化成死循环(删掉下标小于 cur 的元素后 cur 又退回原位)。 // 这里改成 FIFO 队列 + 已算角度集合 + 评估次数上限,语义等价但一定终止。 struct Window { int start, end, step; }; std::deque queue; queue.push_back({1, 361, 10}); std::vector> top; // (相似度, 角度),最多 5 条 std::set visited; const int rtype = anticlockwise ? -1 : 1; const int hh = inner_annulus.rows, ww = inner_annulus.cols; int evals = 0; const int kMaxEvals = 600; // 粗搜 360 + 细化,安全上限 auto worst_top = [&]() -> double { double m = 1e9; for (const auto& t : top) m = std::min(m, t.first); return top.size() < 5 ? -1e9 : m; }; while (!queue.empty() && evals < kMaxEvals) { Window w = queue.front(); queue.pop_front(); for (int angle = w.start; angle < w.end && evals < kMaxEvals; angle += w.step) { if (visited.count(angle)) continue; visited.insert(angle); cv::Mat M = cv::getRotationMatrix2D(cv::Point2f(hh * 0.5f, ww * 0.5f), rtype * angle, 1.0); cv::Mat dst; cv::warpAffine(inner_annulus, dst, M, cv::Size(ww, hh)); if (dst.type() != outer_annulus.type() || dst.size() != outer_annulus.size()) continue; cv::Mat res; cv::matchTemplate(outer_annulus, dst, res, cv::TM_CCOEFF_NORMED); double mn = 0, mx = 0; cv::minMaxLoc(res, &mn, &mx); evals++; if (mx < worst_top()) continue; top.push_back({mx, angle}); std::sort(top.begin(), top.end(), [](const std::pair& a, const std::pair& b) { return a.first > b.first; }); if (top.size() > 5) top.resize(5); // 命中更好 → 在这个角度附近再细化(step 10 覆盖 ±10) queue.push_back({angle - 10, angle + 11, 10}); } } if (top.empty()) { last_error = "环形匹配没有找到任何有效角度"; return -1; } int raw_angle = top[0].second; double inner_angle = raw_angle * speed_ratio / (speed_ratio + 1.0); *out_raw_angle = raw_angle; *out_inner_angle = std::round(inner_angle * 100.0) / 100.0; *out_similarity = top[0].first; return 0; } catch (const std::exception& e) { last_error = e.what(); return -1; } } // 图像相似度比较 float cv_compare_similarity(const Image* img1, const Image* img2) { try { cv::Mat mat1(img1->height, img1->width, CV_8UC3, img1->data); cv::Mat mat2(img2->height, img2->width, CV_8UC3, img2->data); // 确保 same size if (mat1.size() != mat2.size()) { cv::resize(mat2, mat2, mat1.size()); } // 计算 histogram cv::Mat hsv1, hsv2; cv::cvtColor(mat1, hsv1, cv::COLOR_BGR2HSV); cv::cvtColor(mat2, hsv2, cv::COLOR_BGR2HSV); int h_bins = 50, s_bins = 60; int histSize[] = {h_bins, s_bins}; float h_ranges[] = {0, 180}; float s_ranges[] = {0, 256}; const float* ranges[] = {h_ranges, s_ranges}; int channels[] = {0, 1}; cv::Mat hist1, hist2; cv::calcHist(&hsv1, 1, channels, cv::Mat(), hist1, 2, histSize, ranges); cv::calcHist(&hsv2, 1, channels, cv::Mat(), hist2, 2, histSize, ranges); cv::normalize(hist1, hist1, 0, 1, cv::NORM_MINMAX); cv::normalize(hist2, hist2, 0, 1, cv::NORM_MINMAX); double similarity = cv::compareHist(hist1, hist2, cv::HISTCMP_CORREL); return (float)similarity; } catch (const std::exception& e) { last_error = e.what(); return 0.0f; } } const char* cv_get_last_error() { return last_error.c_str(); } } // extern "C"