用c ++将1D转换为2D

时间:2018-05-14 22:50:26

标签: c++ type-conversion

我将1D内的点转换为2D图像存在问题,反之亦然。目前检查的图像是正方形时没有问题。但是,它对矩形图像不起作用。 (即width不等于height

    // dimension of image
    int width = image.rows; // width
    int height = image.cols; // height

    std::vector<float> vertici_1;
    for(int x=0; x<width; x++)
        for(int y=0; y<height; y++)
            vertici_1.push_back( float(y*width+x) ); // from 2D to 1D
    ...
    cv::Point((index1/width), (index1%width)); // from 1D to 2D

2 个答案:

答案 0 :(得分:1)

您的循环未正确放置以进行2D到1D转换。如果您打算将同一行图像存储为向量vertici_1的连续元素,则循环变量为y的循环应该是外部for循环。

std::vector<float> vertici_1;
for(int y=0; y<height; y++)
    for(int x=0; x<width; x++)
        vertici_1.push_back( float(y*width+x) );

或者,如果您打算将同一列的元素作为连续条目存储到vertici_1(即,当前在您的代码中是),那么您应该执行1D到2D转型如下。

cv::Point((index1 % height), (index1 / height));

答案 1 :(得分:0)

#include<iostream>
#include <stdio.h>#include <string.h>
using namespace std;int main(){enum {N=4,M=5,SZ=N*M};
    const int one_d[SZ]={1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0};int two_d[N][M] ;memcpy(two_d[0],one_d,SZ*sizeof(int));for( inti=0;i<N;i++){for(intj=0;j< M;j++){cout<< two_d[i][j]<<" ";cout<<endl;}}return 0;}