尝试 1 和 2:
注意:删除了减少问题大小的第一次尝试。有关以前的尝试,请参阅社区 wiki。
尝试 3:
根据模糊华夫饼的示例,我已经实现了以下内容,但似乎无法正常工作。有什么想法我可能做错了吗?
ImageMatrix ImageMatrix::GetRotatedCopy(VDouble angle)
{
// Copy the specifications of the original.
ImageMatrix &source = *this;
ImageMatrix &target = CreateEmptyCopy();
double centerX = ((double)(source.GetColumnCount()-1)) / 2;
double centerY = ((double)(source.GetRowCount()-1)) / 2;
// Remember: row = y, column = x
for (VUInt32 y = 0; y < source.GetRowCount(); y++)
{
for (VUInt32 x = 0; x < source.GetColumnCount(); x++)
{
double dx = ((double)x) - centerX;
double dy = ((double)y) - centerY;
double newX = cos(angle) * dx - sin(angle) * dy + centerX;
double newY = cos(angle) * dy + sin(angle) * dx + centerY;
int ix = (int)round(newX);
int iy = (int)round(newY);
target[x][y][0] = source[ix][iy][0];
}
}
return target;
}
有了这个原型(prototype)矩阵...1 2 1
0 0 0
-1 -2 -1
...prototype.GetRotatedCopy(0)(这是正确的)...1 2 1
0 0 0
-1 -2 -1
...prototype.GetRotatedCopy(90)(不正确)...-2 0 0
-2 0 2
0 0 2
...prototype.GetRotatedCopy(180) (不正确 - 但有点合乎逻辑?) ...0 -1 -2
1 0 -1
2 1 0
...prototype.GetRotatedCopy(270)(不正确 - 为什么这与 0 旋转相同?) ...1 2 1
0 0 0
-1 -2 -1
解决方案:正如 Mark Ransom 所指出的,我应该使用弧度,而不是度数;我已将我的代码调整如下:
ImageMatrix ImageMatrix::GetRotatedCopy(VDouble degrees)
{
// Copy the specifications of the original.
ImageMatrix &source = *this;
ImageMatrix &target = CreateEmptyCopy();
// Convert degree measurement to radians.
double angle = degrees / 57.3;
// ... rest of code as in attempt #3 ...
感谢您的所有帮助!1 2 1
0 0 0
-1 -2 -1
1 2 1
0 0 0
-1 -2 -1
-1 0 1
-2 0 2
-1 0 1
-1 -2 -1
0 0 0
1 2 1
1 0 -1
2 0 -2
1 0 -1
最佳答案
除非我读错了,否则该算法似乎围绕点 0,0 旋转,这不是您想要的。也许您需要在插入之前将 height/2 和 width/2 添加到行和列值。
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 10; x++) {
VUInt32 newX = (cos(angle) * (x-5)) - (sin(angle) * (y-5));
VUInt32 newY = (sin(angle) * (x-5)) + (cos(angle) * (y-5));
target[newY][newX][0] = source[y][x][0];
}
}
这基本上将旋转中心从左上角调整到图像的中心。
关于math - 为什么我的图像旋转算法不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/697520/