Manipulate pixels using the Numpy module

Compiler: PyCharm 2023.2.1 (Professional Edition)

Compilation environment: python3.11

Libraries: cv2, numpy

1. Create array with Numpy

1. Conventional array() method

out = numpy.array(object,dtype,copy,order,subok,ndmin)

parameter:

object: required parameter, type array_like, can have four types: array, any object that exposes the array interface, an object whose __array__ method returns an array, or any (nested) sequence. The function of np.array() is to convert object into an array according to certain requirements.

dtype: optional parameter, used to indicate the type of array elements. It allows you to change the data type of the array—the original integer or other type can be cast. If not given, the type will be determined to be the smallest type required to maintain the objects in the sequence. Note: This argument can only be used to upcast’ the array. For downcasting, use the .astype(t) method.

copy: optional parameter, type is bool value. If true (the default), the object is copied. Otherwise, a copy will only be returned in the following three situations: (1.if __array__ returns a copy; # (2.if obj is a nested sequence; (3.if a copy is needed to satisfy any of the other requirements ( dtype, order, etc.)

order: {K’, A’, C’, F’}. Specifies the memory layout of the array. C (row sequence)/F (column sequence)/A (original order) (default)/k (the order in which elements appear in memory)

subok: optional parameter, type is bool value. If True, the subclass will be passed, otherwise the returned array will be coerced to a base class array (default). In other words, True: Use the internal data type of object, # This means that the object can contain different types of data, such as integers, strings, etc. This approach provides greater flexibility, but can also lead to type errors and performance issues. False: Use the data type of the object array

ndmin: optional parameter, type int. Specifies the minimum number of dimensions the result array should have.

out: Returns the object output ndarray, an array object that meets the specified requirements.

eg:

n1 = np.array([1, 2, 3]) # Create a one-dimensional array

n2 = np.array([0.1, 0.2, 0.3]) # One-dimensional array containing decimals

n3 = np.array([[2, 3], [4, 5]]) # Two-dimensional array

n1 = np.array(n1, dtype=np.float_) # Force conversion to floating point array or n1 = np.array(n1, dtype=float)

n1 = np.array(n1, ndmin=3) # Three-dimensional array

2. Create an initialized array with specified dimensions and data type:

empty() method This method is used to create an uninitialized array with specified dimensions (shape) and data type (dtype).

out = numpy.empty(shape, dtype order)

parameter:

shape: a tuple representing the dimensions of the array (size and shape)

dtype: data type # order: There are two options: “C” and “F”

Note: np.empty does not give a truly random value. (empty() arrays don’t provide random floats after defining a normal NumPy array) So what does uninitialized or arbitrary mean? Understand that when you create an object (any object) you need to ask someone (someone can be a NumPy insider, Python, or your operating system) for the memory you need. So when you create an empty array, NumPy requests memory. The amount of memory for a NumPy array will be some overhead of the object, and a certain amount of memory containing the array values. That memory could contain anything. So “uninitialized value” means it just contains whatever is in memory. Everything happening here is just a coincidence. You create an array containing a float, then print it, and then it is destroyed again because you didn’t save a reference to it (although this is specific to CPython, other Python implementations may not free the memory immediately, They just release it eventually). Then create an empty array containing a float. The second array has the same amount of memory as the first memory just freed. This is where the coincidence comes in: so maybe something (NumPy, Python, or your operating system) decided to give the same memory location again.

eg: n4 = np.empty([2, 3])

3. Create an array filled with 0

numpy.zeros(shape, dtype=float, order)

parameter:

shape: The shape (dimensions) of the new array created.

dtype: data type to create a new array, optional parameters, default numpy.float64

order: optional parameter, C stands for row priority; F stands for column priority # Return value: an all-zero array of the given dimension.

eg: n5 = np.zeros((3, 3), np.uint8)

4. Create an array filled with 1

n6 = np.ones((3, 3), np.uint8) #

Note: When np.ones defines an image, if no type is defined, it will output a floating point number by default, print(n6)

5. Create a random array

np.random.randint() generates a random integer based on the range specified in the argument.

numpy.random.randint(low, high=None, size=None, dtype=int)

Parameters:

low: int The minimum value (inclusive) of the generated value. The default is 0 and can be omitted.

high: int The maximum value of the generated numeric value (exclusive!).

size: int or tuple of ints The size of the random number, the default is to return a single, enter 10 to return 10, enter (3,4) to return a 3*4 two-dimensional array. (optional).

dtype: The type of result you want to output. The default value is int. (Optional, generally not used).

print(“Randomly generate 10 integers from 1 to 3 and excluding 3:”, np.random.randint(1, 3, 10))

print(“size: The array size is empty and an integer is returned randomly: “, np.random.randint(5, 10))

print(“Randomly generate a two-dimensional array within 5:”, np.random.randint(5, size=(2, 5)))

Note: Omit the low parameter, and subsequent parameters must be declared eg: size=(), dtype=…etc.

2. Numpy operation array

1. Addition, subtraction, multiplication, division, power and comparison operations

n1 = np.array([1, 2])

n2 = np.array([3, 4])

print(“n1-n2=”, n1-n2)

print(“n1 + n2=”, n1 + n2)

print(“n1*n2=”, n1*n2)

print(“n1/n2=”, n1/n2)

print(“n1**n2=”, n1**n2)

print(“>=”, n1 >= n2) # The result of the comparison operation is a boolean array eg: [False False]

print(“==”, n1 == n2)

print(“<=", n1 <= n2)

print(“!=”, n1 != n2)

2. Copy operation

1) Deep copy

n2 = np.array(n1, copy=True) or n2 = np.array(n1) will also work. The optional parameter copy: is a bool value. Default value is: true

n3 = n1.copy()

Any changes made to the copy of the object are not reflected in the original object

2) Shallow copy, a shallow copy means constructing a new collection object and then filling it with references to the sub-objects found in the original. The copying process is not repeated, so no copies of the child objects themselves are created.

In the case of shallow copy, the reference of an object is copied in another object. This means that any changes made to the copy of the object will be reflected in the original object.

eg:

1. view() function to implement shallow copy.

2. Use the = operator to create a new variable that shares the original object reference.

3. Numpy numerical indexing and slicing

1. Indexing and slicing of one-dimensional arrays

n1 = np.array([1, 2, 3, 4, 5, 6])

print(n1[1]) # Standard Python syntax x[obj] syntax indexes the array

print(n1[0:5:2]) # Slice index [start:shop:step], left closed and right open interval!! step cannot be 0

print(n1[0:6]) # The default step size is 1, and its positive and negative values indicate the index direction.

print(n1[:5]) #Start index start, if not written and step>0, it will be 0

print(n1[0:]) # Terminate index stop. If not written and step>0, it is the last digit in the forward direction of the array.

print(n1[::-1]) #Start index start, if not written and step<0, is -1; end index stop, if not written and step<0, is the last digit of the reverse direction of the array

print(n1[-1:-5:-1]) # When reversing, step must be written

2. The indexing and slicing of two-dimensional arrays are similar to the indexing and slicing of one-dimensional arrays

4. Numpy creates images

1. Create a pure black image

image = np.zeros((100, 100), np.uint8) # The array element format is an unsigned 8-bit integer

2. Create a pure white image

image = np.ones((100, 200), np.uint8)*255 # or image[:, :] = 255 # Change the pure black image pixels to 255

3. Create black and white images

for i in range(0, 200, 20):

image[:, i:i + 10] = 0

4. Create a color image# Pure blue image# Pure green image# Pure red image

# The channel order of color images in opencv is B->G->R

image = np.zeros((100, 200, 3), np.uint8)

blue = image.copy() blue[:, :, 0] = 255

green = image.copy() green[:, :, 1] = 255

red = image.copy() red[:, :, 2] = 255

5. Create a random image #snowflake image # colorful dot image

snow = np.random.randint(256, size=(100, 200), dtype=np.uint8)

color = np.random.randint(256, size=(100, 200, 3), dtype=np.uint8)

5. Numpy stitching images

1. Horizontal concatenation of arrays:

array = numpy.hstack(tup) tup: the array tuple to be spliced, array: the new array generated by horizontally splicing the arrays in the parameter tuple

2. Vertical concatenation of arrays:

array = numpy.vstack(tup) tup: array tuple to be spliced, array: new array generated by vertically splicing the arrays in the parameter tuple

# Note: The two can be spliced into multiple arrays, but each array must be “the same shape”

eg:

a = np.array([1, 1, 1])

b = np.array([2, 2, 2])

c = np.array([3, 3, 3])

result_hstack = np.hstack((a, b, c)) r

esult_vstack = np.vstack((a, b, c))

# The image here is consistent with the array operation

6. Code

import numpy as np
import cv2
#Numpy creates array
# 1. Conventional array() method
#numpy.array(object,dtype,copy,order,subok,ndmin)
# object: required parameter, type array_like, can have four types: array, any object that exposes the array interface, an object whose __array__ method returns an array, or any (nested) sequence. The function of np.array() is to convert object into an array according to certain requirements.
# dtype: optional parameter, used to indicate the type of array elements. It allows you to change the data type of the array - the original integer or other type can be cast. If not given, the type will be determined to be the smallest type required to maintain the objects in the sequence.
# Note: This argument can only be used to upcast’ the array. For downcasting, use the .astype(t) method.
# copy: Optional parameter, type is bool value. If true (the default), the object is copied. Otherwise, a copy will only be returned in the following three situations: (1.if __array__ returns a copy;
# (2.if obj is a nested sequence; (3.if a copy is needed to satisfy any of the other requirements (dtype, order, etc.)
# order: {K’, A’, C’, F’}. Specifies the memory layout of the array. C (row sequence)/F (column sequence)/A (original order) (default)/k (the order in which elements appear in memory)
# subok: Optional parameter, type is bool value. If True, the subclass will be passed, otherwise the returned array will be coerced to a base class array (default). In other words, True: use the internal data type of object,
# This means that objects can contain different types of data, such as integers, strings, etc. This approach provides greater flexibility, but can also lead to type errors and performance issues. False: Use the data type of the object array
# ndmin: Optional parameter, type int. Specifies the minimum number of dimensions the result array should have.
# Return object
#out: Output ndarray, an array object that meets the specified requirements
n1 = np.array([1, 2, 3]) # Create a one-dimensional array
n2 = np.array([0.1, 0.2, 0.3]) # One-dimensional array containing decimals
n3 = np.array([[2, 3], [4, 5]]) # Two-dimensional array
print(n1, '\
', n2, '\
', n3)
n1 = np.array(n1, dtype=np.float_) # Force conversion to floating point array
# Or n1 = np.array(n1, dtype=float)
print(n1, '\
', n1.dtype, '\
', type(n1[0]))
n1 = np.array(n1, ndmin=3) # Three-dimensional array
print(n1)
# 2. Create an initialized array with specified dimensions and data type: empty() method
n4 = np.empty([2, 3])
#numpy.empty(shape, dtype order)
# This method is used to create an uninitialized array with specified dimensions (shape) and data type (dtype).
# Parameters:
# shape: a tuple representing the dimensions of the array (size and shape)
#dtype: data type
# order: There are two options: "C" and "F"
# Note: np.empty does not give a truly random value. (empty() arrays do not provide random floats after defining normal NumPy arrays)
# So what does uninitialized or arbitrary mean? Understand that when you create an object (any object), you need to ask someone (someone can be a NumPy insider, Python, or your operating system) for the memory you need.
# So when you create an empty array, NumPy requests memory. The amount of memory for a NumPy array will be some overhead of the object, and a certain amount of memory containing the array values. That memory could contain anything. So "uninitialized value" means it just contains whatever is in memory.
# Everything that happens here is just a coincidence. You create an array containing a float, then print it, and then it is destroyed again because you didn't save a reference to it (although this is specific to CPython, other Python implementations may not free the memory immediately, They just release it eventually).
# Then create an empty array containing a floating point number. The second array has the same amount of memory as the first memory just freed. This is where the coincidence comes in: so maybe something (NumPy, Python, or your operating system) decided to give the same memory location again.
print(n4)
# 3. Create an array filled with 0s
n5 = np.zeros((3, 3), np.uint8)
# numpy.zeros(shape, dtype=float, order)
#The meaning of each parameter:
# shape: The shape (dimension) of the new array created.
#dtype: Data type to create a new array, optional parameters, default numpy.float64
# order: optional parameter, C represents row priority; F represents column priority
# Return value: an all-zero array of the given dimension.
print(n5)
# 4. Create an array filled with 1’s
n6 = np.ones((3, 3), np.uint8)
# Note: When np.ones defines an image, if no type is defined, it will output a floating point number by default.
print(n6)
# 5. Create a random array
# np.random.randint() generates a random integer based on the range specified in the parameter.
# numpy.random.randint(low, high=None, size=None, dtype=int)
# Parameters
# low: int The minimum value of the generated value (inclusive), the default is 0 and can be omitted.
# high: int The maximum value of the generated value (exclusive!).
# size: int or tuple of ints The size of the random number, the default is to return a single, enter 10 to return 10, enter (3,4) to return a 3*4 two-dimensional array. (optional).
# dtype: The type of result you want to output. The default value is int. (Optional, generally not used).
print("Randomly generate 10 integers from 1 to 3 and excluding 3:", np.random.randint(1, 3, 10))
print("size: The array size is empty and an integer is returned randomly: ", np.random.randint(5, 10))
print("Randomly generate a two-dimensional array within 5:", np.random.randint(5, size=(2, 5)))
# Omit the low parameter, and subsequent parameters must be declared eg: size=(),dtype=...etc.
#Numpy operates on arrays
# 1. Addition, subtraction, multiplication, division, power and comparison operations
n1 = np.array([1, 2])
n2 = np.array([3, 4])
print("n1-n2=", n1-n2)
print("n1 + n2=", n1 + n2)
print("n1*n2=", n1*n2)
print("n1/n2=", n1/n2)
print("n1**n2=", n1**n2)
print(">=", n1 >= n2) # The result of the comparison operation is a boolean array
print("==", n1 == n2)
print("<=", n1 <= n2)
print("!=", n1 != n2)
# 2. Copy operation
n2 = np.array(n1, copy=True) # n2 = np.array(n1) The effect is also good, the optional parameter copy:, type is bool value. Default value is: true
print("==", n1 == n2)
n2[0] = 9
print("==", n1 == n2)
n3 = n1.copy()
print("==", n1 == n3)
n3[0] = 9
print("==", n1 == n3)
# The above two types of copy are deep copies. Any changes made to the copy of the object are not reflected in the original object.
# Shallow copy, a shallow copy means constructing a new collection object and then filling it with references to the sub-objects found in the original. The copying process is not repeated, so no copies of the child objects themselves are created.
# In the case of shallow copy, the reference of the object is copied in another object. This means that any changes made to the copy of the object will be reflected in the original object.
#eg: 1. view() function to implement shallow copy. 2. Use the = operator to create a new variable that shares the original object reference.
# Numpy numeric indexing and slicing
# 1. Indexing and slicing of one-dimensional arrays
n1 = np.array([1, 2, 3, 4, 5, 6])
print(n1[1]) # Standard Python syntax x[obj] syntax indexes the array
print(n1[0:5:2]) # Slice index [start:shop:step], left closed and right open interval!! step cannot be 0
print(n1[0:6]) # The default step size is 1, and its positive and negative values indicate the index direction.
print(n1[:5]) #Start index start, if not written and step>0, it will be 0
print(n1[0:]) # Terminate index stop. If not written and step>0, it is the last digit in the forward direction of the array.
print(n1[::-1]) #Start index start, if not written and step<0, is -1; end index stop, if not written and step<0, is the last digit of the reverse direction of the array
print(n1[-1:-5:-1]) # When reversing, step must be written
print(n1[:-5:-1])
print(n1[-2::-1])
# 2. Indexing and slicing of two-dimensional arrays
n1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(n1)
print(n1[0])
print(n1[-1])
print(n1[1, 2])
print(n1[-1, -2])
print(n1[0:2, 1:])
print(n1[0:3, 2])
print(n1[:, 2:3])
#Numpy creates image
# 1. Create a pure black image
image = np.zeros((100, 100), np.uint8) # The array element format is an unsigned 8-bit integer
cv2.imshow("black", image)
cv2.waitKey()
# 2. Create a pure white image
image = np.ones((100, 200), np.uint8)*255
# or image[:, :] = 255
# Change the pure black image pixels to 255
cv2.imshow("white", image)
cv2.waitKey()
# 3. Create a black and white image
for i in range(0, 200, 20):
    image[:, i:i + 10] = 0
cv2.imshow("black_white", image)
cv2.waitKey()
cv2.destroyAllWindows()
# 4. Create a color image # Pure blue image # Pure green image # Pure red image
# The channel order of color images in opencv is B->G->R
image = np.zeros((100, 200, 3), np.uint8)
blue = image.copy()
blue[:, :, 0] = 255
cv2.imshow("blue", blue)
cv2.waitKey()
green = image.copy()
green[:, :, 1] = 255
cv2.imshow("green", green)
cv2.waitKey()
red = image.copy()
red[:, :, 2] = 255
cv2.imshow("red", red)
cv2.waitKey()
cv2.destroyAllWindows()
# 5. Create a random image #snowflakeimage #colordotimage
snow = np.random.randint(256, size=(100, 200), dtype=np.uint8)
cv2.imshow("snow", snow)
cv2.waitKey()
color = np.random.randint(256, size=(100, 200, 3), dtype=np.uint8)
cv2.imshow("color", color)
cv2.waitKey()
cv2.destroyAllWindows()
# Numpy stitching images
# Horizontally splice arrays: array = numpy.hstack(tup) tup: array tuple to be spliced, array: new array generated by horizontally splicing the arrays in the parameter tuple
# Vertically splice arrays: array = numpy.vstack(tup) tup: array tuple to be spliced, array: new array generated by vertically splicing the arrays in the parameter tuple
# Note: The two can be spliced into multiple arrays, but each array must be "the same shape"
a = np.array([1, 1, 1])
b = np.array([2, 2, 2])
c = np.array([3, 3, 3])
result_hstack = np.hstack((a, b, c))
result_vstack = np.vstack((a, b, c))
print(result_hstack)
print(result_vstack)
# The image here is consistent with the array operation

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. OpenCV skill tree Home page Overview 23563 people are learning the system