Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
OPENCV CONNECTED COMPONENT LIBRARY WRAPPER CODE
#include "opencv2/opencv.hpp"
#include "opencv2/xfeatures2d.hpp"
#include <istream>
#include <string>
#include <stdint.h>
using namespace std;
using namespace cv;
/*
بسم الله الرحمن الرحيم
*/
/* TESTED CONNECTED COMPONENT ANALYSIS OPENCV WRAPPER */
class cca_opencv_wrapper{
private:
Mat inp;
Mat labels;
Mat stats;
Mat centroids;
public:
cca_opencv_wrapper( Mat input )
{
inp = input.clone();
labels = Mat(input.size(), CV_16U);
if(inp.channels() == 3)
cvtColor(inp, inp, cv::COLOR_BGR2GRAY);
connectedComponentsWithStats(inp, labels, stats, centroids, 8, CV_16U);
}
uint32_t get_most_left_of_centroid(int centroid_index)
{
return stats.at<uint32_t>(centroid_index, CC_STAT_LEFT);
}
uint32_t get_most_top_of_centroid(int centroid_index)
{
return stats.at<uint32_t>(centroid_index, CC_STAT_TOP);
}
uint32_t get_width_of_centroid(int centroid_index)
{
return stats.at<uint32_t>(centroid_index, CC_STAT_WIDTH);
}
uint32_t get_heigth_of_centroid(int centroid_index)
{
return stats.at<uint32_t>(centroid_index, CC_STAT_HEIGHT);
}
uint32_t get_area_of_component(int centroid_index)
{
return stats.at<uint32_t>(centroid_index, CC_STAT_AREA);
}
uint16_t get_label_of_pixel(int x_pos, int y_pos)
{
return labels.at<uint16_t>(x_pos, y_pos);
}
uint8_t get_centroid_x(int index)
{
return centroids.at<uint8_t>(index, 0);
}
uint8_t get_centroid_y(int index)
{
return centroids.at<uint8_t>(index, 1);
}
size_t get_connected_component_count()
{
return centroids.rows;
}
uint32_t get_max_component_area()
{
uint32_t max_ = 0;
for(auto i = 0; i < get_connected_component_count(); i++)
{
if(get_area_of_component(i) > max_)
max_ = get_area_of_component(i);
}
return max_;
}
uint32_t get_min_component_area()
{
uint32_t min_ = inp.rows * inp.cols;
for(auto i = 0; i < get_connected_component_count(); i++)
{
if(get_area_of_component(i) < min_)
min_ = get_area_of_component(i);
}
return min_;
}
float get_average_component_area()
{
uint32_t sum = 0;
for(auto i = 0; i < get_connected_component_count(); i++)
{
sum = sum + get_area_of_component(i);
}
return ((float) sum) / (float) get_connected_component_count();
}
float get_standard_deviation_of_connected_compenent_areas()
{
uint32_t sum = 0;
for(auto i = 0; i < get_connected_component_count(); i++)
{
sum = sum + abs( get_area_of_component(i) - get_average_component_area() );
}
return ((float) sum) / (float) get_connected_component_count();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment