gpt4 book ai didi

c++ - 如何从 OpenCV 中的图像中过滤小片段?

转载 作者:太空狗 更新时间:2023-10-29 23:05:24 25 4
gpt4 key购买 nike

我按以下方式打印轮廓:

std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours( mask, contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_TC89_KCOS);
for ( size_t i=0; i<contours.size(); ++i )
{
cv::drawContours( img, contours, i, Scalar(200,0,0), 1, 8, hierarchy, 0, Point() );
cv::Rect brect = cv::boundingRect(contours[i]);
cv::rectangle(img, brect, Scalar(255,0,0));
}

一旦我有了二值图像,我想消除较小的轮廓。关于如何这样做有什么建议吗?

我的输入图片:

enter image description here

我想要实现的目标:

enter image description here

编辑:

我正试图摆脱较小的部分。有什么提示吗?

最佳答案

我构建了一个函数,它只打印属于较大段的点。它使用 pointPolygonTest ,一个很棒的 OpenCV 函数,可以判断一个点是在给定轮廓的内部、外部还是边界处。检查一下:

// Gets only the biggest segments
Mat Morphology::threshSegments(Mat &src, double threshSize) {
// FindContours:
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Mat srcBuffer, output;
src.copyTo(srcBuffer);
findContours(srcBuffer, contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_TC89_KCOS);

vector<vector<Point> > allSegments;

// For each segment:
for (size_t i = 0; i < contours.size(); ++i) {
cv::drawContours(srcBuffer, contours, i, Scalar(200, 0, 0), 1, 8, hierarchy, 0, Point());
cv::Rect brect = cv::boundingRect(contours[i]);
cv::rectangle(srcBuffer, brect, Scalar(255, 0, 0));

int result;
vector<Point> segment;
for (unsigned int row = brect.y; row < brect.y + brect.height; ++row) {
for (unsigned int col = brect.x; col < brect.x + brect.width; ++col) {
result = pointPolygonTest(contours[i], Point(col, row), false);
if (result == 1 || result == 0) {
segment.push_back(Point(col, row));
}
}
}
allSegments.push_back(segment);
}

output = Mat::zeros(src.size(), CV_8U);
int totalSize = output.rows*output.cols;
for (int segmentCount = 0; segmentCount < allSegments.size(); ++segmentCount) {
vector<Point> segment = allSegments[segmentCount];
if(segment.size() > totalSize*threshSize){
for (int idx = 0; idx < segment.size(); ++idx) {
output.at<uchar>(segment[idx].y, segment[idx].x) = 255;
}
}
}

return output;
}

关于c++ - 如何从 OpenCV 中的图像中过滤小片段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19732431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com