Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Image Segmentation

00:00 Image Segmentation Using Thresholding. You can use a sequence of erosions and dilations on the threshold image you obtained earlier on to remove parts of the mask that don’t represent the cat and fill in any gaps in the region containing the cat.

00:15 Once you’ve experimented with erosion and dilation, you’ll be able to use a trial-and-error process to find the best combination of them to achieve the ideal mask. In a new REPL session, import Image and ImageFilter from Pillow, set the filename, and then load the image from disk.

00:47 Next, import the erode() and dilate() functions, and then perform twelve cycles of erosion.

01:04 The eroded image no longer contains white pixels representing the background. However, the mask is smaller than the overall outline of the cat and has holes and gaps in it. You can perform dilations to fill the gaps.

01:25 Fifty-eight cycles of dilation filled in all the holes in the mask to give the image seen on-screen. However, this mask is too big, so you can finish the process with a series of erosions.

01:44 This results in a mask you can use to segment the image of the cat. However, it would be good to avoid the sharp edges of a binary mask by blurring it. First, you’ll have to convert it from a binary image into a grayscale one.

02:01 The image is filtered with .BoxBlur() with a radius of 20,

02:14 and you can see the mask on-screen. This mask now looks like a cat. Finally, you are ready to extract the image of the cat from its background. But first, you’ll need to load the original cat image once more

02:38 and then crop it as you did earlier in the course. Next, you create a blank image with the same size as img_cat. You create a new Image object from img_cat by using .point() and setting all the values to zero. Next, you use the composite() function in PIL.Image to create an image made up from both img_cat and blank using cat_mask to determine which parts of each image are used. Finally, you show the composite image.

03:19 Save the cropped cat image and the mask for future use. They’ll be needed in the next section of the course, where you’ll see how to superimpose images.

Become a Member to join the conversation.