似乎有些图像具有不均匀的光照,因此我使用初始代码对某些图像应用了自适应阈值并且它起作用。
由于我(仍然)不熟悉Python中的OpenCV,我将使用C ++ OpenCV提供我的解决方案。我评论了每一行,尽可能简单地移植到Python。
// Read input image. cv::Mat img = cv::imread("e9dzM.png", cv::IMREAD_GRAYSCALE); // Initialize mask. cv::Mat mask = img.clone(); // Adaptive thresholding, 201 x 201 neighbourhood. cv::adaptiveThreshold(img, mask, 255, cv::ADAPTIVE_THRESH_GAUSSIAN_C, cv::THRESH_BINARY, 201, -1); // Morphological opening, 7 x 7 ellipsoid. cv::morphologyEx(mask, mask, cv::MORPH_OPEN, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(7, 7))); // Morphological dilating, 7 x 7 ellipsoid. cv::dilate(mask, mask, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(11, 11))); // Temporary image: Subtract ring like structure from original image. cv::Mat temp = img - mask; // Plain thresholding using Otsu method. cv::threshold(temp, temp, 0, 255, cv::THRESH_OTSU); // Morphological closing, 7 x 7 ellipsoid. cv::morphologyEx(temp, temp, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(7, 7))); // Find contours in temporary image. std::vector<std::vector<cv::Point>> contours; cv::findContours(temp, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE); // Draw found contours in input image. cv::drawContours(img, contours, -1, cv::Scalar(255), 1); // Save image. cv::imwrite("output.png", img);
您将获得以下输出图像:
此解决方案可能适用于您提供的特定图像。我非常怀疑,这段代码可以用于更一般的问题。请记住这一点。