python将图像在画布上排成一圈 [英] python arrange images on canvas in a circle
问题描述
我有一堆图像(比如说10张),它们都是作为数组或PIL对象生成的.
I have bunch of images (say 10) I have generated both as array or PIL object.
我需要将它们集成为圆形以显示它们,并且它应该根据屏幕的分辨率进行调整,python中有什么可以做到这一点?
I need to integrate them into a circular fashion to display them and it should adjust itself to the resolution of the screen, is there anything in python that can do this?
我尝试使用粘贴,但是弄清楚要粘贴的分辨率画布和位置很痛苦,想知道是否有更简单的解决方案?
I have tried using paste, but figuring out the resolution canvas and positions to paste is painful, wondering if there is an easier solution?
推荐答案
我们可以说,当相邻点之间的角度theta
恒定时,点均匀地排列在一个圆中. theta
可以计算为2 * pi弧度除以点数.第一个点相对于x轴的角度为0
,第二个点相对于x轴的角度为theta*1
,第三点相对于x轴的角度为theta*2
,等等.
We can say that points are arranged evenly in a circle when there is a constant angle theta
between neighboring points. theta
can be calculated as 2*pi radians divided by the number of points. The first point is at angle 0
with respect to the x axis, the second point at angle theta*1
, the third point at angle theta*2
, etc.
使用简单的三角函数,可以找到位于圆边缘上的任何点的X和Y坐标.对于角度为ohm
的点位于半径为r
的圆上:
Using simple trigonometry, you can find the X and Y coordinates of any point that lies on the edge of a circle. For a point at angle ohm
lying on a circle with radius r
:
xFromCenter = r*cos(ohm)
yFromCenter = r*sin(ohm)
使用这种数学方法,可以将图像均匀地排列在一个圆上:
Using this math, it is possible to arrange your images evenly on a circle:
import math
from PIL import Image
def arrangeImagesInCircle(masterImage, imagesToArrange):
imgWidth, imgHeight = masterImage.size
#we want the circle to be as large as possible.
#but the circle shouldn't extend all the way to the edge of the image.
#If we do that, then when we paste images onto the circle, those images will partially fall over the edge.
#so we reduce the diameter of the circle by the width/height of the widest/tallest image.
diameter = min(
imgWidth - max(img.size[0] for img in imagesToArrange),
imgHeight - max(img.size[1] for img in imagesToArrange)
)
radius = diameter / 2
circleCenterX = imgWidth / 2
circleCenterY = imgHeight / 2
theta = 2*math.pi / len(imagesToArrange)
for i, curImg in enumerate(imagesToArrange):
angle = i * theta
dx = int(radius * math.cos(angle))
dy = int(radius * math.sin(angle))
#dx and dy give the coordinates of where the center of our images would go.
#so we must subtract half the height/width of the image to find where their top-left corners should be.
pos = (
circleCenterX + dx - curImg.size[0]/2,
circleCenterY + dy - curImg.size[1]/2
)
masterImage.paste(curImg, pos)
img = Image.new("RGB", (500,500), (255,255,255))
#red.png, blue.png, green.png are simple 50x50 pngs of solid color
imageFilenames = ["red.png", "blue.png", "green.png"] * 5
images = [Image.open(filename) for filename in imageFilenames]
arrangeImagesInCircle(img, images)
img.save("output.png")
结果:
这篇关于python将图像在画布上排成一圈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!