Get startedGet started for free

Segmenting image with a mask

With the binary mask ready, you can use it to segment the object, that is the cat, out of the image.

To do so, you will need to load the original image and transform it to a tensor. Next, you will create the object tensor by masking the original image. Finally, you will display the result.

transforms from torchvision have been imported, and the binary_mask you created in the previous exercise is available to you.

This exercise is part of the course

Deep Learning for Images with PyTorch

View Course

Exercise instructions

  • Create image_tensor by applying the ToTensor() transform, defined as transform, to the raw image.
  • Segment the image by masking the image_tensor with the binary_mask, assigning the result to object_tensor.
  • Apply the already defined to_pil_image transform to the object_tensor in order to display it.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Load image and transform to tensor
image = Image.open("images/Egyptian_Mau_123.jpg")
transform = transforms.Compose([transforms.ToTensor()])
image_tensor = ____

# Segment object out of the image
object_tensor = ____

# Convert segmented object to image and display
to_pil_image = ____
object_image = to_pil_image(object_tensor)
plt.imshow(object_image)
plt.show()
Edit and Run Code