代码之家  ›  专栏  ›  技术社区  ›  Rahul

在PIL python中,如何获取文本的x,y坐标,这些文本已经被旋转了一个角度?

  •  0
  • Rahul  · 技术社区  · 8 年前

    我将在图像上的某个位置(x,y)添加一个文本,然后围绕它绘制一个矩形(x,y,x+文本宽度,y+文本高度)。现在我将图像旋转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)
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Koustav    8 年前

    在 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 关注博客文章。