拥有一个整数矩阵 MxN 如何将它们分组为具有增强几何形状的多边形?

2024-03-28

我们有一个给定整数的矩阵(从 1 到 INT_MAX 的任何一个),例如

1 2 3
1 3 3
1 3 3
100 2 1

我们希望为矩阵中的每个唯一整数创建具有相同颜色的多边形,因此我们的多边形将具有如下所示的坐标/分组。

我们可以生成这样的图像:

其中*(由于执行的向量化会缩放到这样的大小):

enter image description here (sorry for crappy drawings)

是否可能以及如何使用增强几何来做这样的事情?

Update:

So @sehe悲伤:I'd simply let Boost Geometry do most of the work. https://stackoverflow.com/questions/8039896/having-a-matrix-mxn-of-integers-how-to-group-them-into-polygons-with-boost-geome/8044058#8044058所以我创建了this https://stackoverflow.com/questions/8048860/boostgeometry-union-simplification-how-it-works纯粹使用 Boost.Geometry 的逐像素类 aeria planter 进行编译、运行,但我需要它在集群数据上运行..并且我有 1000 x 1800 个 uchar 文件(每个唯一的 uchar == 数据属于该集群)。这段代码的问题:在第 18 行,它变得非常慢,每个点的创建开始需要超过一秒=(

code:

//Boost
#include <boost/assign.hpp>
#include <boost/foreach.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/algorithm/string.hpp>

#include <boost/geometry/geometry.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/multi/geometries/multi_polygon.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>

//and this is why we use Boost Geometry from Boost trunk 
//#include <boost/geometry/extensions/io/svg/svg_mapper.hpp>

BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)


void make_point(int x, int y,  boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > & ring)
{
    using namespace boost::assign;

    boost::geometry::append(  ring,     boost::geometry::model::d2::point_xy<double>(x-1, y-1));
    boost::geometry::append(  ring,     boost::geometry::model::d2::point_xy<double>(x, y-1));
    boost::geometry::append(  ring,      boost::geometry::model::d2::point_xy<double>(x, y));
    boost::geometry::append(  ring,      boost::geometry::model::d2::point_xy<double>(x-1, y));
    boost::geometry::append(  ring,     boost::geometry::model::d2::point_xy<double>(x-1, y-1));
    boost::geometry::correct(ring);
}

void create_point(int x, int y, boost::geometry::model::multi_polygon< boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > > & mp)
{
    boost::geometry::model::multi_polygon< boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > > temp;
    boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > ring;
    make_point(x, y, ring);
    boost::geometry::union_(mp, ring, temp);
    boost::geometry::correct(temp);
    mp=temp;
}

int main()
{
    using namespace boost::assign;


    boost::geometry::model::multi_polygon< boost::geometry::model::polygon < boost::geometry::model::d2::point_xy<double> > > pol, simpl;

    //read image
    std::ifstream in("1.mask", std::ios_base::in | std::ios_base::binary);
    int sx, sy;
    in.read(reinterpret_cast<char*>(&sy), sizeof(int));
    in.read(reinterpret_cast<char*>(&sx), sizeof(int));
    std::vector< std::vector<unsigned char> > image(sy);

    for(int i =1; i <= sy; i++)
    {
        std::vector<unsigned char> row(sx);
        in.read(reinterpret_cast<char*>(&row[0]), sx);
        image[i-1] = row;
    }

    //
    std::map<unsigned char,  boost::geometry::model::multi_polygon < boost::geometry::model::polygon < boost::geometry::model::d2::point_xy<double> > >  > layered_image;

    for(int y=1; y <= sy; y++)
    {
        for(int x=1; x <= sx; x++)
        {
            if (image[y-1][x-1] != 1)
            {
                create_point(x, y, layered_image[image[y-1][x-1]]);
                std::cout << x << " : " << y << std::endl;
            }
        }
    }
}

正如你所看到的,我的代码很糟糕..所以我决定创建一个渲染器@sehe代码 https://stackoverflow.com/questions/8039896/having-a-matrix-mxn-of-integers-how-to-group-them-into-polygons-with-boost-geome/8044058#8044058:

#include <iostream>
#include <fstream>

#include <vector>
#include <string>
#include <set>

//Boost
#include <boost/assign.hpp>
#include <boost/array.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/geometry/geometry.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/multi/geometries/multi_polygon.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/mersenne_twister.hpp>


//and this is why we use Boost Geometry from Boost trunk 
#include <boost/geometry/extensions/io/svg/svg_mapper.hpp>

BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)

    namespace mxdetail
{
    typedef size_t cell_id; // row * COLS + col

    template <typename T> struct area
    {
        T value;
        typedef std::vector<cell_id> cells_t;
        cells_t cells;
    };

    template <typename T, size_t Rows, size_t Cols>
    std::vector<area<T> > getareas(const boost::array<boost::array<T, Cols>, Rows>& matrix)
    {
        typedef boost::array<boost::array<T, Cols>, Rows> mtx;
        std::vector<area<T> > areas;

        struct visitor_t
        {
            const mtx& matrix;
            std::set<cell_id> visited;

            visitor_t(const mtx& mtx) : matrix(mtx) { }

            area<T> start(const int row, const int col)
            {
                area<T> result;
                visit(row, col, result);
                return result;
            }

            void visit(const int row, const int col, area<T>& current)
            {
                const cell_id id = row*Cols+col;
                if (visited.end() != visited.find(id))
                    return;

                bool matches = current.cells.empty() || (matrix[row][col] == current.value);

                if (matches)
                {
                    visited.insert(id);
                    current.value = matrix[row][col];
                    current.cells.push_back(id);

                    // process neighbours
                    for (int nrow=std::max(0, row-1); nrow < std::min((int) Rows, row+2); nrow++)
                        for (int ncol=std::max(0, col-1); ncol < std::min((int) Cols, col+2); ncol++)
                            /* if (ncol!=col || nrow!=row) */
                            visit(nrow, ncol, current);
                }
            }
        } visitor(matrix);

        for (int r=0; r < (int) Rows; r++)
            for (int c=0; c < (int) Cols; c++)
            {
                mxdetail::area<int> area = visitor.start(r,c);
                if (!area.cells.empty()) // happens when startpoint already visited
                    areas.push_back(area);
            }

            return areas;
    }
}




typedef boost::array<int, 4> row;

template <typename T, size_t N>
boost::array<T, N> make_array(const T (&a)[N])
{
    boost::array<T, N> result;
    std::copy(a, a+N, result.begin());
    return result;
}


void make_point(int x, int y,  boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > & ring)
{
    using namespace boost::assign;

    boost::geometry::append(  ring,     boost::geometry::model::d2::point_xy<double>(x-1, y-1));
    boost::geometry::append(  ring,     boost::geometry::model::d2::point_xy<double>(x, y-1));
    boost::geometry::append(  ring,      boost::geometry::model::d2::point_xy<double>(x, y));
    boost::geometry::append(  ring,      boost::geometry::model::d2::point_xy<double>(x-1, y));
    boost::geometry::append(  ring,     boost::geometry::model::d2::point_xy<double>(x-1, y-1));
    boost::geometry::correct(ring);
}

void create_point(int x, int y, boost::geometry::model::multi_polygon< boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > > & mp)
{
    boost::geometry::model::multi_polygon< boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > > temp;
    boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > ring;
    make_point(x, y, ring);
    boost::geometry::union_(mp, ring, temp);
    boost::geometry::correct(temp);
    mp=temp;
}
boost::random::mt19937 rng;  
boost::random::uniform_int_distribution<> color(10,255);

std::string fill_rule()
{ 
    int red, green, blue;
    red = color(rng);
    green = color(rng);
    blue = color(rng);

    std::ostringstream rule;
    rule << "fill-rule:nonzero;fill-opacity:0.5;fill:rgb("
        << red  << ","  << green << "," << blue
        << ");stroke:rgb("
        << (red - 5) << "," << (green - 5) << "," << (blue -5) 
        <<  ");stroke-width:2";
    return rule.str();
}

int main()
{
    int sx = 4;
    int sy = 5;

    int row0[] = { 1  , 2, 3, 3, };
    int row1[] = { 1  , 3, 3, 3,};
    int row2[] = { 1  , 3, 3, 3, };
    int row3[] = { 2  , 2, 1, 2, };
    int row4[] = { 100, 2, 2, 2, };

    boost::array<row, 5> matrix;
    matrix[0] = make_array(row0);
    matrix[1] = make_array(row1);
    matrix[2] = make_array(row2);
    matrix[3] = make_array(row3);
    matrix[4] = make_array(row4);

    typedef std::vector<mxdetail::area<int> > areas_t;
    typedef areas_t::value_type::cells_t cells_t; 

    areas_t areas = mxdetail::getareas(matrix);

    using namespace boost::assign;

    typedef boost::geometry::model::polygon
        <
        boost::geometry::model::d2::point_xy<double>
        > polygon;

    typedef boost::geometry::model::multi_polygon<polygon> mp;

    typedef boost::geometry::point_type<mp>::type point_type;

    std::string filename = "draw.svg";
    std::ofstream svg(filename.c_str());


    boost::geometry::svg_mapper<point_type> mapper(svg, 400, 400);
    for (areas_t::const_iterator it=areas.begin(); it!=areas.end(); ++it)
    {
        mp pol;
        std::cout << "area of " << it->value << ": ";
        for (cells_t::const_iterator pit=it->cells.begin(); pit!=it->cells.end(); ++pit)
        {
            int row = *pit / 3, col = *pit % 3;
            std::cout << "(" << row << "," << col << "), ";
            create_point( (row+1), (col+1), pol);
        }

        std::cout << std::endl;
        mapper.add(pol);
        mapper.map(pol, fill_rule());
    }
    std::cout << "areas detected: " << areas.size() << std::endl;
    std::cin.get();
}

这段代码是可以编译的,但是很糟糕(似乎我毕竟不知道如何使用数组......):


简而言之,如果我的问题是正确的,我会让 Boost Geometry 完成大部分工作。

对于 NxM 的样本矩阵,创建 NxM 'flyweight' 矩形多边形以对应于每个矩阵单元visually.

现在,使用迭代加深算法找到所有组:

* for each _unvisited_ cell in matrix
  * start a new group
  * [visit:] 
     - mark _visited_
     - for each neighbour with equal value: 
          - add to curent group and
          - recurse [visit:]

请注意,该算法的结果可以是distinct具有相同值的组(表示不连续的多边形)。例如。价值2从OP中的样本将导致two groups.

现在对于每个组,只需调用增强几何体Union_算法 http://www.boost.org/doc/libs/1_47_0/libs/geometry/doc/html/geometry/reference/algorithms/union_.html找到代表该组的合并多边形。

示例实现

Update这是 C++11 中的非优化实现:

Edit 请参阅此处C++03版本(使用Boost) http://ideone.com/ATY4q

测试中使用的样本数据对应于问题中的矩阵。

#include <iostream>
#include <array>
#include <vector>
#include <set>

namespace mxdetail
{
    typedef size_t cell_id; // row * COLS + col

    template <typename T> struct area
    {
        T value;
        std::vector<cell_id> cells;
    };

    template <typename T, size_t Rows, size_t Cols>
        std::vector<area<T> > getareas(const std::array<std::array<T, Cols>, Rows>& matrix)
    {
        typedef std::array<std::array<T, Cols>, Rows> mtx;
        std::vector<area<T> > areas;

        struct visitor_t
        {
            const mtx& matrix;
            std::set<cell_id> visited;

            visitor_t(const mtx& mtx) : matrix(mtx) { }

            area<T> start(const int row, const int col)
            {
                area<T> result;
                visit(row, col, result);
                return result;
            }

            void visit(const int row, const int col, area<T>& current)
            {
                const cell_id id = row*Cols+col;
                if (visited.end() != visited.find(id))
                    return;

                bool matches = current.cells.empty() || (matrix[row][col] == current.value);

                if (matches)
                {
                    visited.insert(id);
                    current.value = matrix[row][col];
                    current.cells.push_back(id);

                    // process neighbours
                    for (int nrow=std::max(0, row-1); nrow < std::min((int) Rows, row+2); nrow++)
                    for (int ncol=std::max(0, col-1); ncol < std::min((int) Cols, col+2); ncol++)
                        /* if (ncol!=col || nrow!=row) */
                            visit(nrow, ncol, current);
                }
            }
        } visitor(matrix);

        for (int r=0; r < Rows; r++)
            for (int c=0; c < Cols; c++)
            {
                auto area = visitor.start(r,c);
                if (!area.cells.empty()) // happens when startpoint already visited
                    areas.push_back(area);
            }

        return areas;
    }
}

int main()
{
    typedef std::array<int, 3> row;
    std::array<row, 4> matrix = { 
        row { 1  , 2, 3, },
        row { 1  , 3, 3, },
        row { 1  , 3, 3, },
        row { 100, 2, 1, },
    };

    auto areas = mxdetail::getareas(matrix);

    std::cout << "areas detected: " << areas.size() << std::endl;
    for (const auto& area : areas)
    {
        std::cout << "area of " << area.value << ": ";
        for (auto pt : area.cells)
        {
            int row = pt / 3, col = pt % 3;
            std::cout << "(" << row << "," << col << "), ";
        }
        std::cout << std::endl;
    }
}

编译为gcc-4.6 -std=c++0x输出是:

areas detected: 6
area of 1: (0,0), (1,0), (2,0), 
area of 2: (0,1), 
area of 3: (0,2), (1,1), (1,2), (2,1), (2,2), 
area of 100: (3,0), 
area of 2: (3,1), 
area of 1: (3,2), 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

拥有一个整数矩阵 MxN 如何将它们分组为具有增强几何形状的多边形? 的相关文章

随机推荐