Python-PIL如何在全黑squ中粘贴图像

2024-04-18 23:39:17 发布

您现在位置:Python中文网/ 问答频道 /正文

目标是在1000 x 1000的基础图像上粘贴一个透明的PNG文件。到目前为止,我的代码将一个250x250的图像粘贴到基础图像上,但它随机地放置在整个基础图像中。结果如下enter image description here

这是一段代码,你们可以看看发生了什么。在

import random
from PIL import Image, ImageDraw, ImageOps, ImageFont 

###This creates the base image ###
base = Image.new('RGB',(1000,1000),'black')
base.save('base_image.jpg')

### Opens up all the images that will be used###
jon = Image.open('jon_snow.jpg')
rejon = Image.open('resized_jon.jpg')
wolf = Image.open('wolf.png')


### The List of locations around the base image ###
location = [(0,0),(0,250),(0,500),(0,750),(250,0),(250,250),(250,500),(250,750),(500,0),(500,250),(500,500),(500,750),(750,0),(750,250),(750,500),(750,750),(0,0),(0,250),(0,500),(0,750),(250,0),(250,250),(250,500),(250,750),(500,0),(500,250),(500,500),(500,750),(750,0),(750,250),(750,500),(750,750)]
### Opertaions used ###
def image_resize(image,size):
  image.resize((size))
  image.save('resized_jon.jpg')
  return


def image_invert(image):
  inverted = ImageOps.invert(image)
  base.paste(inverted,random.choice(location))
  base.save('base_image.jpg')
  return

def fill_base():
  for x in range(6):
    image_invert(rejon)

我并不是为了节省时间而加上所有的操作。所以,正如你所看到的,当随机数被使用时,它并没有在生成的时候填满所有的黑色方块。所以这就是为什么我想创建一个for循环,或者当那些方块是黑色的时候检查一下,然后我可以在那个位置粘贴一个PNG文件。可以检查一下那些黑色方块吗?有什么帮助吗


Tags: the图像imagebase粘贴savedefopen
2条回答

您可以跟踪random.choice的结果,以便您已经知道哪些方块是空白的(/black),例如,使用tile粘贴函数的返回值:

def image_invert(image):
    inverted = ImageOps.invert(image)
    r = random.choice(location)
    base.paste(inverted, r)
    base.save('base_image.jpg')
    return r

(注意:如果函数没有返回值,则不需要return语句)


每贴瓷砖收缩location的Mcve:

^{pr2}$

结果:

# locations used:
# (500, 250)                                              
# (0, 750)                                                   
# (250, 0)                                                   
# (750, 500)                                                  
# (0, 500)                                                    
# (250, 500)                                                 
# (750, 0)                                                    
# (750, 750)                                                  
# (0, 250)                                                   
# (500, 500)                                

# locations left black:                                      
# [(0, 0), (250, 250), (250, 750), (500, 0), (500, 750), (750, 250)]        

如果您真的想测试图像的分片是否完全为黑色,可以将图像强制转换为numpy数组:

import numpy as np
B = np.array(base)
(B[0:250, 0:250]==0).all()
# True or False

您可以使用此测试获取所有具有

^{pr2}$

(请注意,您必须将x和y的顺序交换为numpy的行和列索引。)

相关问题 更多 >