cpp
int ReadModelNum::CutImg(cv::Mat imSrc, cv::Mat& crt, std::vector<std::pair<double, int>>& dataRestorationParameters) {
try {
// 预处理
cv::Mat binaryImage, dstSrc;
int iScal = 10;
cv::resize(imSrc, dstSrc, cv::Size(imSrc.cols / iScal, imSrc.rows / iScal));
cv::inRange(dstSrc, 90, 250, binaryImage);
cv::Mat kernel = cv::Mat::ones(5, 5, CV_8U);
cv::erode(binaryImage, binaryImage, kernel);
cv::dilate(binaryImage, binaryImage, kernel);
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(binaryImage, contours, hierarchy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
std::vector<std::pair<cv::Rect, double>> rects;
for (const auto& cont : contours) {
cv::Rect rect = cv::boundingRect(cont);
double area = cv::contourArea(cont);
rects.push_back(std::make_pair(rect, area));
}
std::sort(rects.begin(), rects.end(), [](const std::pair<cv::Rect, double>& a, const std::pair<cv::Rect, double>& b) {
return a.second > b.second;
});
if (!rects.empty()) {
cv::Rect largest_rect = rects[0].first;
largest_rect.x *= iScal;
largest_rect.y *= iScal;
largest_rect.width *= iScal;
largest_rect.height *= iScal;
// 计算中心点
int centerX = largest_rect.x + largest_rect.width / 2;
int centerY = largest_rect.y + largest_rect.height / 2;
// 目标尺寸
int targetWidth = 500;
int targetHeight = 380;
// 计算左上角坐标
int topLeftX = centerX - targetWidth / 2;
int topLeftY = centerY - targetHeight / 2;
// 确保裁剪区域在图像边界内
topLeftX = std::max(0, std::min(topLeftX, imSrc.cols - targetWidth));
topLeftY = std::max(0, std::min(topLeftY, imSrc.rows - targetHeight));
// 打印左上角坐标
std::cout << "Top-left corner: (" << topLeftX << ", " << topLeftY << ")" << std::endl;
// 裁剪图像
cv::Rect crop_rect(topLeftX, topLeftY, targetWidth, targetHeight);
crt = imSrc(crop_rect).clone();
return 0; // 成功
}
} catch (const std::exception& e) {
std::cerr << "An error occurred: " << e.what() << std::endl;
}
return -1; // 失败
}