在 PIL 中旋转一个正方形 [英] Rotating a square in PIL

查看:60
本文介绍了在 PIL 中旋转一个正方形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 PIL,我想通过指定正方形边长和旋转角度在图像上绘制一个旋转的正方形.正方形应该是白色的,背景是灰色的.例如,下图旋转了 45 度:

With PIL, I want to draw a rotated square on an image, by specifying the square side length, and the rotation angle. The square should be white, and the background grey. For example, the following image has a rotation of 45 degrees:

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

The only way I know how to do rotations in PIL is by rotating the entire image. But if I start with the following image:

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

And then rotate it by 45 degrees, I get this:

该方法只是引入黑色部分来填充图像的未定义"区域.

That method just introduces black parts to fill in the "undefined" region of the image.

如何只旋转正方形?

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

The code to generate my original square (the second figure) is as follows:

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")

推荐答案

如果你只想画一个任意角度的纯色正方形,你可以用三角函数计算旋转正方形的顶点,然后画出来带有多边形.

If all you want to do is draw a solid color square at some arbitrary angle, you can use trigonometry to calculate the vertices of the rotated square, then draw it with 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")

结果:

这篇关于在 PIL 中旋转一个正方形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆