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

问题描述 投票:2回答:2

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

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

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

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

哪个*(因为执行的vectirisation将扩展到如此大小):

(抱歉蹩脚的图纸)

是否有可能以及如何使用提升几何来做这样的事情?

Update:

所以@sehe sad: I'd simply let Boost Geometry do most of the work.所以我创建this像素类aeria种植者使用纯粹的Boost.Geometry,编译,运行但我需要它在集群数据上运行..我有1000个1800个文件的uchars(每个独特的uchar ==数据属于那个claster)。这段代码的问题:在第18行,它变得很慢,每个点创建开始花费超过一秒=(

码:

//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 code创建一个渲染器:

#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();
}

这段代码是可编译的,但它很糟糕(似乎我毕竟没有得到如何处理数组...):

c++ vector boost vector-graphics boost-geometry
2个回答
3
投票

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

对于NxM的样本矩阵,创建NxM'flyweight'矩形多边形以在视觉上对应于每个矩阵单元。

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

* 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:]

请注意,此算法的结果可能是具有相同值的不同组(表示析取多边形)。例如。来自OP中样本的值2将导致两组。

现在,对于每个组,只需调用Boost Geometry's Union_ algorithm以查找表示该组的合并多边形。

示例实施

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

编辑请参阅此处查看C++03 version (using Boost)

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

#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), 

0
投票

当点数很大(比如说超过1000x1000)时,上面的解决方案会占用大量内存。这正是主题启动者所发生的事情。

下面我展示了更具伸缩性的方法

我将在这里分开两个问题:一个是找到区域,另一个是将它们转换为多边形。

第一个问题实际上相当于找到网格图的连通分量,其中邻居有边,当且仅当它们具有相等的“颜色”时才附加。可以使用的网格图。

#include <boost/graph/grid_graph.hpp>
// Define dimension lengths, a MxN in this case
boost::array<int, 2> lengths = { { M, N } };

// Create a MxN two-dimensional, unwrapped grid graph 
grid_graph<2> graph(lengths);

接下来,我们应该将给定矩阵M转换为边缘滤波器:如果邻居的“颜色”相同,则存在网格边缘。

template <class Matrix>
struct GridEdgeFilter
{  
    typedef grid_graph<2> grid;
    GridEdgeFilter(const Matrix & m, const grid&g):_m(&m),_g(&g){}

    /// \return true iff edge is present in the graph
    bool operator()(grid::edge_descriptor e) const
    {
        grid::vertex_descriptor src = source(e,*_g), tgt = target(e,*_g);
        //src[0] is x-coord of src, etc. The value (*m)[x,y] is the color of the point (x,y).
        //Edge is preserved iff matrix values are equal
        return (*_m)[src[0],src[1]] == (*_m)[tgt[0],tgt[1]];
    }

    const Matrix * _m;
    const grid* _g;
};

最后,我们定义了网格和boost::filtered_graphEdgeFilter,并为连接组件调用Boost.Graph算法。

每个连通分量代表一组单色的点,即我们想要变换为多边形的区域。

这里有另一个问题。 Boost.Geometry仅允许逐个合并多边形。因此,当多边形的数量很大时,它变得非常慢。

更好的方法是使用Boost.Polygon,即它的Property Merge功能。一个以空的property_merge对象开始,然后通过插入给定颜色的矩形继续(您可以将颜色设置为属性)。然后一个人调用方法merge并得到一个polygon_set作为输出。

© www.soinside.com 2019 - 2024. All rights reserved.