简介
从超声采集的图像会带有部分用户操作界面的组件,若使用全局图片进行病灶检测,操作界面的组件可能会对检测结果造成干扰,通过扇形区域检测可防止这种情况的出现。
Code
LargestConnecttedComponent函数出自该博客《opencv 获取图像最大连通域 c++和python版》
// 获取检测区域边界
cv::Rect GetBorder(cv::Mat img) {
cv::Mat gray;
// rgb转灰度图
cvtColor(img, gray, cv::COLOR_BGR2GRAY);
int counts[256] = { 0 };
int value;
// 统计0~255各颜色出现次数
for (int row_id = 0; row_id < gray.rows; row_id++) {
for (int col_id = 0; col_id < gray.cols; col_id++)
{
counts[(int)gray.at<uchar>(row_id, col_id)] += 1;
}
}
// 找出出现次数最多的颜色
int max_val = 0;
int max_index = 0;
for (int i = 0; i < 256; i++)
{
if (counts[i] > max_val) {
max_index = i;
max_val = counts[i];
}
}
cv::Mat thresh, morph_open_mat, morph_close_mat;
// 阈值处理
threshold(gray, thresh, max_index, 255, cv::THRESH_BINARY);
// 定义kernel
cv::Mat kernel = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(1, 5));
// 开运算
morphologyEx(thresh, morph_open_mat, cv::MORPH_OPEN, kernel);
// 闭运算
morphologyEx(morph_open_mat, morph_close_mat, cv::MORPH_CLOSE, kernel);
cv::Mat lcc_mat;
// 最大连通区域检测
LargestConnecttedComponent(morph_close_mat, lcc_mat);
int max_x = 0, max_y = 0, min_x = gray.cols, min_y = gray.rows;
// 找到矩形角点
for (int row_id = 0; row_id < gray.rows; row_id++) {
for (int col_id = 0; col_id < gray.cols; col_id++)
{
if ((int)lcc_mat.at<uchar>(row_id, col_id) == 255) {
if (col_id > max_x) {
max_x = col_id;
}
if (col_id < min_x) {
min_x = col_id;
}
if (row_id > max_y) {
max_y = row_id;
}
if (row_id < min_y) {
min_y = row_id;
}
}
}
}
// 返回角点
cv::Rect rect(cv::Point(min_x, min_y), cv::Point(max_x, max_y));
return rect;
}