我有一个坐标列表,这些坐标表示5x5平面上的某些粒子。例如:
coords = [ [1.4, 3.2], [2.221, 4.313], [0.411, 4.3221] ]
我想获取一张图像,尺寸为64x64,其中像素在坐标处为黑色,在其他位置均为白色。
答案 0 :(得分:3)
这样的事情应该做得很好:
#!/usr/bin/env python3
from PIL import Image
import numpy as np
# Coordinates
coords = [ [1.4, 3.2], [2.221, 4.313], [0.411, 4.3221] ]
# Make white 64x64 image, all pixels = 255
im = np.ones((64,64),dtype=np.uint8)*255
# Make each pixel at given coordinates black (0)
for c in coords:
x,y = c
im[round(y*64/5),round(x*64/5)] = 0
# Save result
Image.fromarray(im).save('result.png')
请注意,Python将数组的第一个索引作为y
,第二个作为x
。我也不是按比例放大尺寸,而是人为地在图像周围添加了红色边框,目的只是为了在Stack Overflow的白色背景上显示图像的范围。
如果您想对其进行动画处理并制作GIF动画,则可以使用以下方式:
#!/usr/bin/env python3
from PIL import Image
import numpy as np
import random
# Create a list of frames of the animation
frames = []
# Loop, making 30 frames
for f in range(30):
# Make white 64x64 image, all pixels = 255
im = np.ones((64,64),dtype=np.uint8)*255
# Make 3 pixels at random coordinates black (0)
for c in range(3):
x,y = random.randint(0,63), random.randint(0,63)
im[y,x] = 0
# Append new frame to our list
frames.append(Image.fromarray(im))
# Save result
frames[0].save('anim.gif', save_all=True, append_images=frames[1:], duration=100, loop=0)
请注意,您实际上不需要编写任何Python代码即可执行此操作,您可以使用 ImageMagick ,该软件已安装在大多数Linux发行版中,并且可用于macOS和Windows。因此,仅在终端机中:
magick -size 64x64 xc:white -fill black \
-draw "point 25,10" \
-draw "point 50,50" \
-draw "point 5,25" result.png
关键字:Python,PIL,Pillow,动画GIF,动画,粒子,粒子,图像,图像处理,坐标。