在PIL中旋转正方形

时间:2016-01-12 15:45:30

标签: python python-imaging-library pillow

使用PIL,我想通过指定方形边​​长和旋转角来在图像上绘制旋转的方形。方块应为白色,背景为灰色。例如,以下图像的旋转角度为45度:

enter image description here

我知道如何在PIL中进行旋转的唯一方法是旋转整个图像。但是,如果我从下面的图像开始:

enter image description here

然后旋转45度,我明白了:

enter image description here

该方法只引入黑色部分来填充" undefined"图像的区域。

如何只旋转方块?

生成原始方块的代码(第二个图)如下:

from PIL import Image

image = Image.new('L', (100, 100), 127)
pixels = image.load()

for i in range(30, image.size[0] - 30):
    for j in range(30, image.size[1] - 30):
        pixels[i, j] = 255

rotated_image = image.rotate(45)
rotated_image.save("rotated_image.bmp")

2 个答案:

答案 0 :(得分:5)

如果要做的只是以任意角度绘制纯色方块,可以使用三角法计算旋转方块的顶点,然后使用polygon绘制它。

import math
from PIL import Image, ImageDraw

#finds the straight-line distance between two points
def distance(ax, ay, bx, by):
    return math.sqrt((by - ay)**2 + (bx - ax)**2)

#rotates point `A` about point `B` by `angle` radians clockwise.
def rotated_about(ax, ay, bx, by, angle):
    radius = distance(ax,ay,bx,by)
    angle += math.atan2(ay-by, ax-bx)
    return (
        round(bx + radius * math.cos(angle)),
        round(by + radius * math.sin(angle))
    )

image = Image.new('L', (100, 100), 127)
draw = ImageDraw.Draw(image)

square_center = (50,50)
square_length = 40

square_vertices = (
    (square_center[0] + square_length / 2, square_center[1] + square_length / 2),
    (square_center[0] + square_length / 2, square_center[1] - square_length / 2),
    (square_center[0] - square_length / 2, square_center[1] - square_length / 2),
    (square_center[0] - square_length / 2, square_center[1] + square_length / 2)
)

square_vertices = [rotated_about(x,y, square_center[0], square_center[1], math.radians(45)) for x,y in square_vertices]

draw.polygon(square_vertices, fill=255)

image.save("output.png")

结果:

enter image description here

答案 1 :(得分:1)

让我们概括为一个矩形:

  • x的长度 l ,y的宽度 w
  • 使用"旋转矩阵"。

轮换代码:

import math

def makeRectangle(l, w, theta, offset=(0,0)):
    c, s = math.cos(theta), math.sin(theta)
    rectCoords = [(l/2.0, w/2.0), (l/2.0, -w/2.0), (-l/2.0, -w/2.0), (-l/2.0, w/2.0)]
    return [(c*x-s*y+offset[0], s*x+c*y+offset[1]) for (x,y) in rectCoords]

绘图代码:

from PIL import Image
from PIL import ImageDraw
import math

L=512; W=512
image = Image.new("1", (L, W))
draw = ImageDraw.Draw(image)

vertices = makeRectangle(100, 200, 45*math.pi/180, offset=(L/2, W/2))
draw.polygon(vertices, fill=1)

image.save("test.png")