Indexing NumPy arrays with Booleans

Boolean indexing is a kind of fancy indexing therefor it works pretty much the same.

import scipy.misc 
import matplotlib.pyplot as plt
import numpy as np 

face = scipy.misc.face() 
xmax = face.shape[0] 
ymax = face.shape[1] 
face = face[:min(xmax,ymax),:min(xmax,ymax)]

def get_indices(size):
    arr = np.arange(size)
    return arr % 4 == 0

face1 = face.copy()
xindices = get_indices(face.shape[0])
yindices = get_indices(face.shape[1])
face1[xindices, yindices] = 0
plt.subplot(211)
plt.imshow(face1)
face2 = face.copy()
face2[(face > face.max()/4) & (face < 3 * face.max()/4)] = 0
plt.subplot(212)
plt.imshow(face2)
plt.show()

#out
Indexing NumPy arrays with Booleans

Explanation:

  • Image with dots on the diagonal – We choose modulo 4 points on the diagonal of the picture (not sure if it can be seen in the image above):
    def get_indices(size):
    	arr = np.arange(size)
    	return arr % 4 == 0
  • We use this selection and plot the points:
    face1 = face.copy()
    xindices = get_indices(face.shape[0])
    yindices = get_indices(face.shape[1])
    face1[xindices, yindices] = 0	
    plt.subplot(211)
    plt.imshow(face1)
  • Set to 0 based on value – Select array values between one quarter and three quarters of the maximum value and set them to 0:
    face2[(face > face.max()/4) & (face < 3 * face.max()/4)] = 0

Leave a Reply