Make a composite image using a mask image

Here, we control the combination of two images using the function Image.composite(image_1, image_2, mask_image).

Getting ready

Use the images 100_canary.png, 100_cockcrow.png, and 100_sun_1.png from the folder /constr/pics1. The 100_ in the titles is a reminder that the images are 100 x 100 pixels in size and we will see the format, size, and type of each image printed onto the console.

How to do it...

With the three identical size and mode images in place, execute the following code.

# image_composite_1.py
# >>>>>>>>>>>>>>>>>
import Image
im_1 = Image.open("/constr/pics1/100_canary.png") # mode is RGBA
im_2 = Image.open("/constr/pics1/100_cockcrow.png") # mode is RGB
im_3 = Image.open("/constr/pics1/100_sun_1.png")
# Check on mode, size and format first for compatibility.
print "im_1 format:", im_1.format, ";size:", im_1.size, "; mode:", im_1.mode
print "im_2 format:", im_2.format, ";size:", im_2.size, "; mode:", im_2.mode
print "im_3 format:", im_3.format, ";size:", im_3.size, "; mode:", im_3.mode
im_2 = im_2.convert("RGBA")
im_3 = im_3.convert("L")
im_4 = Image.composite(im_1, im_2, im_3)
im_4.show()

How it works...

From format information, we will see that the mode of the first image is RGBA while the second is RGB. Therefore, it is necessary to first convert the second image to RGBA.

The mask image has to be of the form 1, L, or RGBA and of the same size. In this recipe, we have converted it to mode L which is a 256 value gray-scale image. The value of each pixel in the mask is used to multiply the source images. If the value of a particular pixel in a certain location was 56, then image_1 would be multiplied by 256 56 =200 and image_2 would be multiplied by 56.

There's more...

There are other effects like Image.eval(function, Image) where each pixel is multiplied by the function and we can convert the function to some complicated algebraic expression. If the image has multiple bands, then the function is applied to each band.

Another effect is the Image.merge(mode, bandList) which creates a multi-band image from multiple single-band images of equal size. We specify the desired mode of the new image. The bandList specifier is a sequence of single-band image components to be combined.

See also

Using the image operations shown previously in combinations, there are an endless number of effects that can be achieved. We would be delving into the world of image and signal processing which can get extremely complex and sophisticated. Certain effects have become fairly standard and can be seen in the list of filtering options available in image-processing applications like GIMP and Photoshop.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.18.101