Tag Archives: all

python/numpy tip: form an image mask based on compound logic

Here’s an example of an easy way to form a pixel-wise image mask based on a compound logical condition, using numpy’s where routine. In this example, img is your 2-d image array:

mask_logic = np.array([np.not_equal(img, badval).flatten(),
                       np.less_equal(img, thresh).flatten()])
img_mask = np.where(np.all(mask_logic, axis=0), np.ones(mask_logic.shape[1]),

Numpy’s all implements the “AND” condition; to do a logical “OR”, use the similar any routine.