ffriend
ffriend

Reputation: 28492

How to fill a region with half-transparent color in Matplotlib?

Many papers on image segmentation provide examples where each segment is covered with half-transparent color mask:

enter image description here

If I have an image and a mask, can I achieve the same result in Matplotlib?

EDIT:

The mask in my case is defined as an array with the same width and height as an image filled with numbers from 0 to (num_segments+1), where 0 means "don't apply any color" and other numbers mean "cover this pixel with some distinct color". Yet, if another representation of a mask is more suitable, I can try to convert to it.

Here are a couple of complications that I found in this task so that it doesn't sound that trivial:

  1. Colored regions are not regular shapes like lines, squares or circles so functions like plot(..., 'o'), fill() or fill_between() don't work here. They are not even contours (or at least I don't see how to apply them here).
  2. Modifying alpha channel isn't the most popular thing in plots, so is rarely mentioned in Matplotlib's docs.

Upvotes: 1

Views: 7902

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339300

This can surely be done. The implementation would depend on how your mask looks like.

Here is an example

import matplotlib.pyplot as plt
import numpy as np

image = plt.imread("https://i.sstatic.net/9qe6z.png")

ar= np.zeros((image.shape[0],image.shape[1]) )
ar[100:300,50:150] = np.ones((200,100))
ar[:,322:] = np.zeros((image.shape[0],image.shape[1]-322) )*np.nan

fig,ax=plt.subplots()
ax.imshow(image)
ax.imshow(ar, alpha=0.5, cmap="RdBu")

plt.show()

enter image description here

Upvotes: 7

Related Questions