python implements the image batch adding watermark! How about pilot!

Posted by mgs019 on Fri, 29 Nov 2019 09:11:10 +0100

You can set whether to add watermarks when writing articles. However, some pictures may want to add watermarks, some do not want to add watermarks, what should we do?

Configuration environment

python3 + pillow

pip3 install pillow

Import into storage

from PIL import Image, ImageSequence
import os
import random

Effect preview:

usage method:

  1. Add watermark image logo.png in the same directory as the script
  2. Create directory input and place the image to be watermarked
  3. Create directory output execution script addlogo.py
  4. The result output is in the output folder

Realization principle

Watermark image collection:

First, read the pixel information and size information of the watermark image. Remove the pixels with 0 transparency and modify the transparency pixel information.

img_logo = Image.open("logo.png")
img_logo_width, img_logo_height = img_logo.size
img_logo_pixels = dict()
for w in range(img_logo_width):
    for h in range(img_logo_height):
        c = img_logo.getpixel((w,h))
        if c!=(0, 0, 0, 0):
            img_logo_pixels[(w, h)] = c[:3]+(125,)

Mix colors:

Color mixing is adopted for each pixel. c1 is the pixel information of the source image (r,g,b,a), c2 is the pixel information of the logo image. The hybrid algorithm is as follows:

def blendPixel(c1,c2):
    a1=256-c2[3]
    a2=c2[3]-(a1*c2[3])/256.0
    a=a1+a2
    c=(int((a1*c1[0] + a2*c2[0])/a), int((a1*c1[1] + a2*c2[1])/a), int((a1*c1[2] + a2*c2[2])/a),int(a))
    return c

To process a source Image object:

A random position starts to process pixels. The specific code is as follows.

def dealOneImage(image,offX=None,offY=None):
    w, h = image.size
    offX = offX if offX else random.random();
    offY = offY if offY else random.random();
    #If the image size is smaller than the watermark image, no watermark is added
    if w>=img_logo_width and h>=img_logo_height:
        top = int((w - img_logo_width)*offX)
        left = int((h - img_logo_height)*offY)
        for p, c in img_logo_pixels.items():
            p_x = (p[0]+top)
            p_y = (p[1]+left)
            image_c = image.getpixel((p_x,p_y))
            if(isinstance(image_c, tuple) and len(image_c)>2):
                image.putpixel((p_x, p_y), blendPixel(image_c,c))
    return image;

To process a single file:

For the gif file, first split it into a picture, add watermark to the picture, and then synthesize gif. For other formats of picture files, you can add several more watermarks. Finally, the output is saved to the output folder.

def dealOneFile(filePath):
    img_orign = Image.open(filePath)
    _,file_type = os.path.splitext(filePath)
    basename = os.path.basename(filePath)
    if file_type == '.gif':
        sequence = [];
        offX=random.random()
        offY=random.random()
        for f in ImageSequence.Iterator(img_orign):
            if len(sequence) % 2 == 0:
                offX=random.random()
                offY=random.random()
            sequence.append(dealOneImage(f.convert(),offX,offY))
        sequence[0].save(f'./output/{basename}', save_all=True, append_images=sequence[1:])
    else:
        image_out = (dealOneImage(img_orign))
        for x in range(1):
            image_out = (dealOneImage(image_out))
        image_out.save(f'./output/{basename}')

Processing Directory:

Make a filter for the files in the current directory, and only select the files in the picture format.

def dealSrc(srcDir):
    picFiles = [os.path.join(srcDir,fn) for fn in os.listdir(srcDir) if fn.endswith(('.gif', '.jpg', '.png','.jpeg'))]
    for filePath in picFiles:
        dealOneFile(filePath)

Summary

Adding watermark is mainly implemented by using the pilot Library in Python 3. First, read the logo image information, then add the mixed pixel information in a random location, and finally save it.

Among them, the processing of gif file is to split the frame, add watermark, and finally combine into a gif. This can only correspond to a relatively small gif file processing, if there is a better way to welcome message exchange and sharing!

This article is only for personal learning and communication. Please do not use it for other purposes!

Reference material

Topics: Python