获取旋转图像中点的新x,y坐标

2024-05-16 19:47:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有Google地图图标,在使用MarkerImage绘制地图之前,我需要旋转一定的角度。我使用PIL在Python中动态地进行旋转,得到的图像与原始的-32x32大小相同。例如,使用以下默认谷歌地图标记: icon before rotation ,使用以下python代码实现30度顺时针旋转:

# full_src is a variable holding the full path to image
# rotated is a variable holding the full path to where the rotated image is saved
image = Image.open(full_src)
png_info = image.info
image = image.copy()
image = image.rotate(30, resample=Image.BICUBIC)
image.save(rotated, **png_info)

结果图像是icon rotated 30 degrees counter-clockwise

棘手的一点是在使用新的旋转图像创建MarkerImage时使用新的定位点。这应该是图标的尖端。默认情况下,定位点是底部中间[在x,y坐标中定义为(16,32),其中(0,0)是左上角]。有人能给我解释一下我如何用JavaScript轻松完成这项工作吗?

谢谢。

2011年6月22日更新: 张贴了错误的旋转图像(原始图像为逆时针330度)。我已经纠正了。还添加了重采样(Image.BICUBIC),使旋转的图标更清晰。


Tags: thepath图像imageinfosrcis地图
3条回答

在图像中,向下是正Y,向右是正X。但是,要应用rotation formula,我们需要向上作为正Y。因此,步骤1将应用f(x,y) = f(x,h-y),其中“h”是图像的高度。 假设图像相对于x0,y0旋转。然后你需要把原点转换到这一点。因此,步骤2将是f(x,y) = f(x-x0,y-y0)。在这个阶段(即两个步骤之后),你的新坐标是x-x0h-y-y0。现在可以应用旋转公式了

x1 = x*cos(theta) - y*sin(theta) 

y1 = xsin(theta) + ycos(theta) 

使用步骤2后获得的x和y值。 你会得到

x1 = (x-x0)*cos(theta) - (h-y-y0)*sin(theta) 

y1 = (x-x0)*sin(theta) + (h-y-y0)*cos(theta)

现在,撤消在步骤2和步骤1中完成的转换(按此顺序)。

撤消步骤2后:xNew = x1 + x0yNew = y1 + y0

撤消步骤1后:xNew = x1 + x0yNew = h - (y1 + y0)

这给了你:

xNew = (x-x0)*cos(theta) - (h-y-y0)*sin(theta) + x0

yNew = -(x-x0)*sin(theta) - (h-y-y0)*cos(theta) + (h-y0)

旋转约0,0的公式为:

x1 = cos(theta) x0 - sin(theta) y0
y1 = sin(theta) x0 + cos(theta) y0

但这是对于规则轴,旋转0,0。PIL的旋转是顺时针的,带有“图形”轴。另外,它在图像的中心。最后一个令人困惑的事情是图像的大小可能会改变,这需要在最终结果中加以说明。

步骤:取原点,减去图像中心,应用“图形轴”校正旋转,找到新的图像大小,添加新图像的后中心位置。

使用图形轴的旋转是:

x1 = cos(theta) x0 + sin(theta) y0
y1 = -sin(theta) x0 + cos(theta) y0

16,32-16,16等于0,16。顺时针旋转30度(基于图像),得到一个点cos(-30)*0+sin(-30)*16,-sin(-30)*0+cos(-30)*16=-8,13.86。最后一步是添加回旋转位置的中心位置。

要计算旋转点的位置,可以使用rotation matrix

转换为JavaScript后,将计算旋转点:

function rotate(x, y, xm, ym, a) {
    var cos = Math.cos,
        sin = Math.sin,

        a = a * Math.PI / 180, // Convert to radians because that is what
                               // JavaScript likes

        // Subtract midpoints, so that midpoint is translated to origin
        // and add it in the end again
        xr = (x - xm) * cos(a) - (y - ym) * sin(a)   + xm,
        yr = (x - xm) * sin(a) + (y - ym) * cos(a)   + ym;

    return [xr, yr];
}

rotate(16, 32, 16, 16, 30); // [8, 29.856...]

相关问题 更多 >