Create watermark from black and white image using python

Viewed 33

I’m very new to using python and image manipulation.

I have an image that I want to place over another image. The image is black and white and I only want the black part to be placed. I want to remove the white part.

enter image description here

I essentially want to create a watermark that I can place anywhere on an image. Here is an example image on which I want to put the watermark.

enter image description here

This blog post talks about making a watermark on an image. But I don’t want the entire image, just the black part of my watermark.

Thanks for any help.

1 Answers

You can use PIL (or cv2 with numpy) to make it.

Because you have black and white image so you can duplicate it, reverse it and put it as alpha channel to get transparency in place of white pixels.

Next you can resize it to expected size (I use size of second image) and you can paste it on second image in selected place (I use (0,0)) and it will put without transparent pixels. Images doesn't have to be the same size.

You can use other function to make other modification and get different effect. Some of functions may need to use images with the same size.

Doc: Pillow.Image

from PIL import Image, ImageChops

import PIL
print(PIL.__version__)

# --- load ---

img1 = Image.open('Z9yFZ.jpg')
img2 = Image.open('Uh4LU.jpg')

# --- alpha channel ---

R,G,B = img1.split()
gray  = img1.convert('L')
alpha = ImageChops.invert(gray)

img1 = Image.merge('RGBA', [R,G,B,alpha])

# --- resize ---

img1.thumbnail(img2.size)

# --- merge ---

img2.paste(img1, (0,0), img1) # second `img1` as `mask`

img2.show()

# --- save ---

img2.save('result.jpg')

Result:

enter image description here


EDIT:

I never test it but module Wand (which uses ImageMagick) has function watermark


EDIT:

I created code like this:

from wand.image import Image
from wand.display import display
from wand.color import Color

import wand
print(wand.version.VERSION)
print(wand.version.MAGICK_VERSION)

# --- load ---

img1 = Image(filename='Z9yFZ.jpg')  # has to use `filename=`
img2 = Image(filename='Uh4LU.jpg')  # has to use `filename=`

# --- alpha channel ---

#img1.alpha_channel = 'background'

#color = Color('#FFFFFF')  # white
color = Color('white')    # white
#color = Color('#000000')  # black
#color = Color('black')    # black
#color = img1.background_color
ten_percent = int(65535*0.1)  # remove similar colors (65535 = 2^16-1)

img1.transparent_color(color, alpha=0.0, fuzz=ten_percent)

# --- resize ---

w, h = img2.size
img1.transform(resize=f"{w}x{h}>")

# --- merge ---

img2.watermark(img1, left=0, top=0, transparency=0.5)  # transparent, looks good even without `fuzz=ten_percent` 
#img2.composite(img1, left=0, top=0)                    # not transparent, looks better with `fuzz=ten_percent`

display(img2)

# --- save ---

img2.save(filename='result.jpg')  # has to use `filename=`

enter image description here

Related