2016-09-23 278 views
-2

嗨我有一个函数应该旋转一个2d向量,它保存来自pgm文件的像素值。顺时针旋转2d向量90度

void pgm_cw(vector <IVec> &p) 
{ 
    vector <IVec> temp;  // temporary vector of vectors of ints 
    int count = 0;   // count variable 
    int count2 = 0;  // 2nd count variable 

    temp.resize(p.size()); 
    for(count = 0; count < p.size(); count++) 
    { 
     temp[count].resize(p[count].size()); 
     for(count2 = 0; count2 < temp[count].size(); count2++) 
     { 
      temp[count][count2] = p[count][count2]; 
     } 
    } 
    for(count = 0; count < temp.size(); count++) 
    { 
     for(count2 = 0; count2 < temp[count].size(); count2++) 
     { 
      temp[count][count2] = temp[count][temp[count].size()-count2-1]; 
        // set temp vector to p with 90 degree rotation 
     } 
    } 
    p = temp;  // set p equal to temp 
} 

输出不正确。任何想法如何解决它?谢谢

+0

在未来的问题,你可能需要准备[MCVE(http://stackoverflow.com/help/mcve),不包含类,如'IVec'需要猜测。另外,对于不起作用的简短程序,您可能希望在程序的各个阶段添加打印输出,指出他们正在做什么。 –

回答

0

你的代码实际上是做一个关于垂直中心的镜像转换。此外,你正在循环一个矢量,然后重新分配给该矢量。这意味着你将会在第二个for循环中的某个点处使用不反映原始传递向量的值来填充向量。

一种算法通用于像素X中的编号,y这里的东西:

typedef std::vector<int> IVec; 

void pgm_cw(std::vector<IVec> &p) 
{ 
    // Need to allocate an array to store the transform 
    std::vector<IVec> temp(p[0].size(), IVec(p.size())); 

    int count = 0;  // count variable 
    int count2 = 0;  // 2nd count variable 

    for(count = 0; count < p.size(); count++) 
    { 
     for(count2 = 0; count2 < p[0].size(); count2++) 
     { 
      // Clockwise rotation 
      temp[count2][temp[0].size()-count-1] = p[count][count2]; 
      // Counter-clockwise rotation 
      //temp[temp.size()-count2-1][count] = p[count][count2]; 
     } 
    } 

    p = temp;  // set p equal to temp 
} 

我已经包括了一个明确的typedef,这样我可以测试它。这里有一个快速测试:

BEFORE: 
    1 2 3 4 
    5 6 7 8 
    9 10 11 12 
AFTER: 
    9 5 1 
10 6 2 
11 7 3 
12 8 4 

希望这有助于不对称阵列的情况。

+0

这种做出输出更糟糕。它编译但给了我一个错误,当我跑它说,无效的下一个isze – miamidawgs

+0

你想做一个方阵,或者你的x,y像素大小不同? – Jvinniec

+0

我已经更新了答案,以说明二维数组中的尺寸不相等的答案。另外,我添加了一个示例,表明它应该可以工作。 – Jvinniec

1

更简单的方法来解决您的问题。

void pgm_cw(vector <IVec> &temp) 
{ 

    int N = temp.size(); 

    for (int x = 0; x < N/2; x++) 
    { 
     for (int y = x; y < N-x-1; y++) 
     { 
      // store current cell in temp variable 
      int tmp = temp[x][y]; 

      // move values from right to top 
      temp[x][y] = temp[y][N-1-x]; 

      // move values from bottom to right 
      temp[y][N-1-x] = temp[N-1-x][N-1-y]; 

      // move values from left to bottom 
      temp[N-1-x][N-1-y] = temp[N-1-y][x]; 

      // assign temp to left 
      temp[N-1-y][x] = tmp; 
     } 
    } 
    //std::swap(p,temp); 
    //p = temp;  // set p equal to temp 
} 

Inplace rotate square matrix by 90 degrees

+1

请注意,在这种情况下,你不会需要'std :: swap(p,temp)'。这个答案比我的效率更高,因为它不需要分配整个额外的数组,这可能是昂贵的,这取决于你试图旋转的数组的大小。 – Jvinniec

+0

@Jvinniec,感谢您的纠正。 – v78

+0

另外,该问题询问“顺时针旋转2d矢量90度”,但此时您的算法逆时针旋转。对不起是一个害虫! :P – Jvinniec