您似乎需要用黑色填充图像的外部,因为这样更容易识别鸡蛋,因为它们将被隔离为白色。
但是,如果寄生虫卵神奇地显示为蓝色怎么办?我稍后会解释这一点,但这种方法可以让您摆脱每次需要新样本时单击图像的负担待分析。
我用 C++ 编写了答案,但如果你按照代码的内容进行操作,我相信你可以快速将其翻译成 Python。
#include <iostream>
#include <vector>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
int main(int argc, char* argv[])
{
// Load input image (3-channel)
cv::Mat input = cv::imread(argv[1]);
if (input.empty())
{
std::cout << "!!! failed imread()" << std::endl;
return -1;
}
// Convert the input to grayscale (1-channel)
cv::Mat grayscale = input.clone();
cv::cvtColor(input, grayscale, cv::COLOR_BGR2GRAY);
灰度此时的样子:
// Locate the black circular shape in the grayscale image
std::vector<std::vector<cv::Point> > contours;
cv::findContours(grayscale, contours, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);
// Fill the interior of the largest circular shape found with BLUE
cv::Mat circular_shape = input.clone();
for (size_t i = 0; i < contours.size(); i++)
{
std::vector<cv::Point> cnt = contours[i];
double area = cv::contourArea(cv::Mat(cnt));
if (area > 500000 && area < 1000000) // magic numbers to detect the right circular shape
{
std::cout << "* Area: " << area << std::endl;
cv::drawContours(circular_shape, contours, i, cv::Scalar(255, 0, 0),
cv::FILLED, 8, std::vector<cv::Vec4i>(), 0, cv::Point() );
}
}
circular_shape此时的样子:
// Create the output image with the same attributes of the original, i.e. dimensions & 3-channel, so we have a colored result at the end
cv::Mat output = cv::Mat::zeros(input.size(), input.type());
// copyTo() uses circular_shape as a mask and copies that exact portion of the input to the output
input.copyTo(output, circular_shape);
cv::namedWindow("Eggs", cv::WINDOW_NORMAL | cv::WINDOW_KEEPRATIO);
cv::imshow("Eggs", output);
cv::resizeWindow("Eggs", 800, 600);
cv::waitKey(0);
return 0;
}
窗口上显示的输出是:
这种解决方案的优点是用户不需要与应用程序交互来促进检测鸡蛋,因为它们已经被涂成蓝色。
在此之后,可以对输出图像进行其他操作,例如图像其余部分的cv::inRange() 到isolate colored objects。
因此,为了完整起见,我将添加几行文本/代码来演示从现在开始您可以做些什么来将鸡蛋与图像的其余部分完全隔离:
// Isolate blue pixels on the output image
cv::Mat blue_pixels_only;
cv::inRange(output, cv::Scalar(255, 0, 0), cv::Scalar(255, 0, 0), blue_pixels_only);
blue_pixels_only 在这个阶段的样子:
// Get rid of pixels on the edges of the shape
int erosion_type = cv::MORPH_RECT; // MORPH_RECT, MORPH_CROSS, MORPH_ELLIPSE
int erosion_size = 3;
cv::Mat element = cv::getStructuringElement(erosion_type,
cv::Size(2 * erosion_size + 1, 2 * erosion_size + 1),
cv::Point(erosion_size, erosion_size));
cv::erode(blue_pixels_only, blue_pixels_only, element);
cv::dilate(blue_pixels_only, blue_pixels_only, element);
cv::imshow("Eggs", blue_pixels_only);
cv::imwrite("blue_pixels_only.png", blue_pixels_only);
blue_pixels_only 在这个阶段的样子: