OpenCV пытается обвести поврежденное печенье

Я новичок в OpenCV, и я пытаюсь написать код, который обводит поврежденные печенья на картинке, сейчас я смог обвести только один (самый большой), и я не могу понять, как получить код, чтобы обвести все печенье, независимо от его размера. Исходное изображение: https://imgur.com/a/5Zw8WzT , Последний результат, который я получил: https://imgur.com/a/mAILBS2

Код:

 #include <stdio.h>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <vector>
#include <iostream>
#include <string>

using namespace cv;
using namespace std;

int biscuit_detector(const Mat gray, vector<Point> & biscuit)
{
Mat img2;
threshold(gray, img2, 100, 255, THRESH_BINARY_INV);

vector<vector<Point>> contour;
findContours(img2, contour, RETR_EXTERNAL, CHAIN_APPROX_NONE);

int maxIndex = -1;
double maxArea = 0.0;

for (int i = 0; i < contour.size(); ++i)
{
double area = contourArea(contour[i]);
if (area > maxArea)
{
maxArea = area;
maxIndex = i;
}
}

if (maxIndex == -1)
return 0; // no biscuit
biscuit = contour[maxIndex];
return 1;
}int main()
{
Mat img = imread("img", IMREAD_COLOR);
Mat gray;
cvtColor(img, gray, COLOR_BGR2GRAY);

vector <Point> biscuit;

if (biscuit_detector(gray, biscuit) == 0)
{
cout << "no biscuit" << endl;
system("pause");
exit(-1);
}

vector<vector<Point>> contours;
contours.push_back(biscuit);
drawContours(img, contours, 0, Scalar(0, 255, 0), 3);

vector<Point> hull;
convexHull(biscuit, hull, false, true);
polylines(img, hull, true, (Scalar(0, 0, 50)));

vector<int> hull2;
convexHull(biscuit, hull2, false, false);
vector<Vec4i> defects;
convexityDefects(biscuit, hull2, defects);

for (int i = 0; i < defects.size(); ++i)
{
Vec4i v = defects[i];
double distance = v[3] / 256.0;
if (distance > 1)
{
Point dp = biscuit[v[2]];
circle(img, dp, 10, Scalar(255, 0, 0), -1);
}
}

imshow("Image result", img);
waitKey();
}

-3

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]