Skip to content

Instantly share code, notes, and snippets.

@sgarciav
Last active March 15, 2021 05:28
Show Gist options
  • Save sgarciav/4843393510c57ba00bf2a67031121215 to your computer and use it in GitHub Desktop.
Save sgarciav/4843393510c57ba00bf2a67031121215 to your computer and use it in GitHub Desktop.
Determine the unique values in a CV matrix
// function declaration
std::vector<float> unique(const cv::Mat& input, bool sort);
// the actual function
std::vector<float> unique(const cv::Mat& input, bool sort)
{
if (input.channels() > 1 || input.type() != CV_32F)
{
std::cerr << "unique !!! Only works with CV_32F 1-channel Mat" << std::endl;
return std::vector<float>();
}
std::vector<float> out;
for (int y = 0; y < input.rows; ++y)
{
const float* row_ptr = input.ptr<float>(y);
for (int x = 0; x < input.cols; ++x)
{
float value = row_ptr[x];
if ( std::find(out.begin(), out.end(), value) == out.end() )
out.push_back(value);
}
}
if (sort)
std::sort(out.begin(), out.end());
return out;
}
// previously defined
cv::Mat cv_matrix;
// function usage
std::vector<float> unik = unique(cv_matrix, true);
for (unsigned int i = 0; i < unik.size(); i++)
{
std::cout << unik[i] << " ";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment