Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

I got the C++ code for LBerger's algorithm! Hopefully it's not hard to convert it to Python. Does Python even support the opencv contrib modules?

Here's the input image: image description

Here's the code:

#include <opencv2/opencv.hpp>
#include <opencv2/ximgproc.hpp>
using namespace cv;
using namespace cv::ximgproc;
#pragma comment(lib, "opencv_world331.lib")

#include <iostream>
#include <map>
using namespace std;


int main(void)
{
    Mat frame = imread("snake.png");

    if (frame.empty())
    {
        cout << "Error loading image file" << endl;
        return -1;
    }

    cvtColor(frame, frame, CV_RGB2GRAY);

    bitwise_not(frame, frame);

    threshold(frame, frame, 190, 255, CV_THRESH_BINARY);

    thinning(frame, frame);

    Mat labels;
    connectedComponents(frame, labels, 8);

    map<size_t, size_t> counts;

    for (int j = 0; j < labels.rows; j++)
    {
        for (int i = 0; i < labels.cols; i++)
        {
            counts[labels.at<int>(j, i)]++;

            if (labels.at<int>(j, i) == 2)
                frame.at<unsigned char>(j, i) = 255;
            else if (labels.at<int>(j, i) == 1)
                frame.at<unsigned char>(j, i) = 127;
            else if (labels.at<int>(j, i) == 0)
                frame.at<unsigned char>(j, i) = 0;
        }
    }

    cout << counts.size() << endl;

    cout << counts[1] << endl;

    imshow("Frame", frame);

    waitKey();

    return 0;
}

I got the C++ code for LBerger's algorithm! Hopefully it's not hard to convert it to Python. Does Python even support the opencv contrib modules?

Here's the input image: image description

Here's the code:

#include <opencv2/opencv.hpp>
#include <opencv2/ximgproc.hpp>
using namespace cv;
using namespace cv::ximgproc;
#pragma comment(lib, "opencv_world331.lib")

#include <iostream>
#include <map>
using namespace std;


int main(void)
{
    Mat frame = imread("snake.png");

    if (frame.empty())
    {
        cout << "Error loading image file" << endl;
        return -1;
    }

    cvtColor(frame, frame, CV_RGB2GRAY);

    bitwise_not(frame, frame);

    threshold(frame, frame, 190, 255, CV_THRESH_BINARY);

    thinning(frame, frame);

    Mat labels;
    connectedComponents(frame, labels, 8);

    map<size_t, size_t> counts;

    for (int j = 0; j < labels.rows; j++)
    {
        for (int i = 0; i < labels.cols; i++)
        {
            counts[labels.at<int>(j, i)]++;

            if (labels.at<int>(j, i) == 2)
                frame.at<unsigned char>(j, i) = 255;
            else if (labels.at<int>(j, i) == 1)
                frame.at<unsigned char>(j, i) = 127;
            else if (labels.at<int>(j, i) == 0)
                frame.at<unsigned char>(j, i) = 0;
        }
    }

    cout << counts.size() << endl;

    cout << counts[1] << endl;
endl; // The snake is this long in pixels.

    imshow("Frame", frame);

    waitKey();

    return 0;
}