Python 如何将水印放置在图像的中心位置?

Python 如何将水印放置在图像的中心位置?,python,image,automation,pillow,watermark,Python,Image,Automation,Pillow,Watermark,我有10k图像,所以我尝试使用枕头库将水印放在所有图像上,但水印位置总是会发生变化,如下图所示 我想把水印放在每幅图像的中心位置,水印与图像的距离不应该太大或太小,它应该适合每幅图像,所以你能告诉我怎么做吗 这是水印图像: 我正在使用以下代码: from PIL import Image import glob def watermark_with_transparency(input_image_path, output_image_path, watermark_image_pa

我有10k图像,所以我尝试使用枕头库将水印放在所有图像上,但水印位置总是会发生变化,如下图所示

我想把水印放在每幅图像的中心位置,水印与图像的距离不应该太大或太小,它应该适合每幅图像,所以你能告诉我怎么做吗

这是水印图像:

我正在使用以下代码:

from PIL import Image
import glob


def watermark_with_transparency(input_image_path, output_image_path, watermark_image_path, position):
    base_image = Image.open(input_image_path) #open base image
    watermark = Image.open(watermark_image_path) #open water mark
    width, height = base_image.size #getting size of image

    transparent = Image.new('RGBA', (width, height), (0,0,0,0))
    transparent.paste(base_image, (0,0))
    transparent.paste(watermark, position, mask=watermark)
    #transparent.show()
    transparent.convert('RGB').save(output_image_path)
    print 'Image Done..!'



for inputImage in glob.glob('images/*.jpg'):
    output = inputImage.replace('images\\','')
    outputImage = 'watermark images\\'+str(output)

    watermark_with_transparency(inputImage, outputImage, 'watermark.png', position=(0,0)) #function

我认为最好的选择是如下调整水印的大小:

base_image = Image.open(input_image_path) #open base image
watermark = Image.open(watermark_image_path) #open water mark
watermark = watermark.resize(base_image.size)

你通过的位置是0,0。如果希望它居中,则应通过将图像的宽度和高度除以2并从中减去水印的宽度和高度除以2来更新函数中的位置

X coordinate = width_of_image/2 - width_of_watermark/2

Y coordinate = height_of_image/2 - height_of_watermark/2

下面是一个示例代码:

width_of_watermark , height_of_watermark = watermark.size
position = ((width/2-width_of_watermark/2),(height/2-height_of_watermark/2))

您已获得
位置=(0,0)
。您需要计算图像的中心,并将水印的大小调整到与原始图像所需的纵横比。图像和水印图像的分辨率是多少?@vishes\u shell您能告诉我如何计算图像的中心吗?@FlyingTeller每个图像都有不同的分辨率,这是主要问题。我附加水印图像也。你可以去看看now@RashidAziz我敢打赌,如何将新图像放置在中心的另一个图像之上,有很多答案。用谷歌搜索,答案就会出现!:)但是如何将其放置在每个图像的中心位置?如果两个图像的大小相同,则不需要指定位置。因为水印位于水印图像的中心,如果不指定位置,它应该位于叠加图像的中心。有10k图像,所有图像的大小和分辨率都不相同,因此关于这个问题,我认为我们必须找到图像的中心点,而不是每次调整水印的大小,使其具有与图像相同的分辨率。这也使得每个图像中的水印大小相同