numpy.where() in Python

returns the indices of elements in an input array where the given condition is satisfied.

# Python program explaining 
# where() function 

import numpy as np 

np.where([[True, False], [True, True]], 
    [[1, 2], [3, 4]], [[5, 6], [7, 8]]) 
# Python program explaining 
# where() function 

import numpy as np 

# a is an array of integers. 
a = np.array([[1, 2, 3], [4, 5, 6]]) 

print(a) 

print ('Indices of elements <4') 

b = np.where(a<4) 
print(b) 

print("Elements which are <4") 
print(a[b]) 

References
https://www.geeksforgeeks.org/numpy-where-in-python/

Basic NumPy for working with OpenCV

Create an array from a list

my_list = [1, 2, 3]
my_array = np.array(my_list)

Create an array with arrange

my_array = np.arange(0, 10)
my_array2 = np.arange(0, 10, 2) # with step 2

Create an array with zeros

my_array = np.zeros((2, 3)) # default type if float
my_array2 = np.zeros((2, 3), np.int32) # with type int

Create an array with ones

my_array = np.ones((10, 8), np.int32)

Create an array from random

np.random.seed(101)
array1 = np.random.randint(0, 100, 10)
array2=np.random.randint(0,100,10)

Max, Min, Mean

np.random.seed(101)
array1 = np.random.randint(0, 100, 10)
print(array1.max())
print(array1.argmax()) # index of max value
print(array1.min())
print(array1.argmin()) # index of min value
print(array1.mean())

Indexing an array

matrix = np.arange(0, 100).reshape(10, 10)
print(matrix)

print(matrix[2,3])

row = 1
col = 4
print(matrix[row,col])

Manipulating an array

matrix = np.arange(0, 100).reshape(10, 10)
print(matrix)

matrix[0:3, 0:3] = 0
print(matrix)

Copying an array

matrix: np.ndarray = np.arange(0, 100).reshape(10, 10)
print(matrix)

matrix2 = matrix.copy()
matrix2[0:3, 0:3] = 0
print(matrix2)

Slicing an array

matrix = np.arange(0, 100).reshape(10, 10)

print(matrix[1, :])  # whole row 1
print(matrix[:, 1])  # whole col 1
print(matrix[1, 1:4])  # row 1 from col 1 to 4
print(matrix[1:4, 1])  # col 1 from row 1 to 4

new_matrix: np.ndarray = matrix[1, :]
print(new_matrix.reshape(5, 2))

Reshaping an array

np.random.seed(101)
array1 = np.random.randint(0, 100, 10)
print(array1)
print(array1.shape)

array2 = array1.reshape((2, 5))
print(array2)
print(array2.shape)

References
https://www.tutorialspoint.com/numpy/index.htm