本文主要是介绍骨架细化算法实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原理:
参考OpenCV学习(13) 细化算法(1)
实现:
void skeleton(cv::Mat& src, cv::Mat& dst, int maxIterations = -1)
{dst = src.clone();cv::Mat mid = src.clone();;int count = 0; while (true){count++;if (maxIterations != -1 && count > maxIterations) break;std::vector<uchar*> mFlag; for (int i = 0; i < mid.rows; ++i){uchar * p = dst.ptr<uchar>(i);for (int j = 0; j < mid.cols; ++j){uchar p1 = p[j];if (p1 != 1) continue;uchar p4 = (j == mid.cols - 1) ? 0 : *(p + j + 1);uchar p8 = (j == 0) ? 0 : *(p + j - 1);uchar p2 = (i == 0) ? 0 : *(p - dst.step + j);uchar p3 = (i == 0 || j == mid.cols - 1) ? 0 : *(p - dst.step + j + 1);uchar p9 = (i == 0 || j == 0) ? 0 : *(p - dst.step + j - 1);uchar p6 = (i == mid.rows- 1) ? 0 : *(p + dst.step + j);uchar p5 = (i == mid.rows- 1 || j == mid.cols - 1) ? 0 : *(p + dst.step + j + 1);uchar p7 = (i == mid.rows- 1 || j == 0) ? 0 : *(p + dst.step + j - 1);if ((p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9) >= 2 && (p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9) <= 6){int ap = 0;if (p2 == 0 && p3 == 1) ++ap;if (p3 == 0 && p4 == 1) ++ap;if (p4 == 0 && p5 == 1) ++ap;if (p5 == 0 && p6 == 1) ++ap;if (p6 == 0 && p7 == 1) ++ap;if (p7 == 0 && p8 == 1) ++ap;if (p8 == 0 && p9 == 1) ++ap;if (p9 == 0 && p2 == 1) ++ap;if (ap == 1 && p2 * p4 * p6 == 0 && p4 * p6 * p8 == 0){ mFlag.push_back(p + j); }}}}for (std::vector<uchar*>::iterator i = mFlag.begin(); i != mFlag.end(); ++i){**i = 0;}if (mFlag.empty())break;elsemFlag.clear();for (int i = 0; i < mid.rows; ++i){uchar* p = dst.ptr<uchar>(i);for (int j = 0; j < mid.cols; ++j){uchar p1 = p[j];if (p1 != 1) continue;uchar p4 = (j == mid.cols - 1) ? 0 : *(p + j + 1);uchar p8 = (j == 0) ? 0 : *(p + j - 1);uchar p2 = (i == 0) ? 0 : *(p - dst.step + j);uchar p3 = (i == 0 || j == mid.cols - 1) ? 0 : *(p - dst.step + j + 1);uchar p9 = (i == 0 || j == 0) ? 0 : *(p - dst.step + j - 1);uchar p6 = (i == mid.rows- 1) ? 0 : *(p + dst.step + j);uchar p5 = (i == mid.rows- 1 || j == mid.cols - 1) ? 0 : *(p + dst.step + j + 1);uchar p7 = (i == mid.rows- 1 || j == 0) ? 0 : *(p + dst.step + j - 1);if ((p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9) >= 2 && (p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9) <= 6){int ap = 0;if (p2 == 0 && p3 == 1) ++ap;if (p3 == 0 && p4 == 1) ++ap;if (p4 == 0 && p5 == 1) ++ap;if (p5 == 0 && p6 == 1) ++ap;if (p6 == 0 && p7 == 1) ++ap;if (p7 == 0 && p8 == 1) ++ap;if (p8 == 0 && p9 == 1) ++ap;if (p9 == 0 && p2 == 1) ++ap;if (ap == 1 && p2 * p4 * p8 == 0 && p2 * p6 * p8 == 0){ mFlag.push_back(p + j); }}}}for (std::vector<uchar*>::iterator i = mFlag.begin(); i != mFlag.end(); ++i){**i = 0;}if (mFlag.empty())break;elsemFlag.clear();}dst *= 255;
}
代码传送门:https://github.com/taifyang/OpenCV-algorithm
这篇关于骨架细化算法实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!