python - 如何在PIL python中获取已旋转角度的文本的x,y坐标?

标签 python image-processing computer-vision python-imaging-library

我在图像上的位置 (x,y) 添加文本,然后在其周围绘制一个矩形 (x,y,x+text_width,y+text_height)。现在我将图像旋转 30 度。如何获得新坐标?

from PIL import Image
im = Image.open('img.jpg')
textlayer = Image.new("RGBA", im.size, (0,0,0,0))
textdraw = ImageDraw.Draw(textlayer)
textsize = textdraw.textsize('Hello World', font='myfont.ttf')
textdraw.text((75,267), 'Hello World', font='myfont.ttf', fill=(255,255,255))
textlayer = textlayer.rotate(30)

我试过this 。但我没有正确理解这一点。谁能指出我做错了什么。

textpos = (75,267)
theta = 30
x0,y0 = 0,0
h = textsize[0] - textsize[1]
x,y = textpos[0], textpos[1]
xNew = (x-x0)*cos(theta) - (h-y-y0)*sin(theta) + x0
yNew = -(x-x0)*sin(theta) - (h-y-y0)*cos(theta) + (h-y0)

最佳答案

PIL 中,旋转围绕图像的中心进行。因此,考虑到图像的中心由以下公式给出:

cx = int(image_width / 2)
cy = int(image_height / 2)

指定旋转角度:

theta = 30

给定坐标(px, py),可以使用以下公式获得新坐标:

rad = radians(theta)

new_px = cx + int(float(px-cx) * cos(rad) + float(py-cy) * sin(rad))
new_py = cy + int(-(float(px-cx) * sin(rad)) + float(py-cy) * cos(rad))

请注意,角度必须以弧度指定,而不是

这个答案的灵感来自this以下博客文章。

关于python - 如何在PIL python中获取已旋转角度的文本的x,y坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51908166/

相关文章:

安装 Pygame 时 Python pip3 Egg_info 错误代码 1

c - 如何使用 OpenMP 优化中值滤波器(C)?

python - TensorFlow 中的图像变形

c - RGB565 转灰度

algorithm - OpenCV检测网后网球场线

python - 计算相关矩阵

python - matplotlib 中的图形和轴方法

python - 为什么 python 使用 .而不是/用于导入语句中的路径?

python - 关于如何在单词列表上创建随机森林分类器有什么建议吗?

opencv - 如何将 SIFT 描述符与局部敏感散列结合使用?