简体   繁体   中英

regarding an operation on numpy array

I once saw the following code segment

th_seg = fr_seg < 20
fr_seg *= th_seg

In the above fr_seg is an array of shape (600,128,128). I am not clear what does the above code segment try to do?

It zeroes down all the elements that are greater or equal to 20.

fr_seg = np.array(range(15, 25))

# Create an array of booleans. 
# Each item is True if the corresponding item in fr_seg is smaller than 20.
th_seg = fr_seg < 20

# Multiply each item from the original array by 0 (False) / 1 (True)
fr_seg *= th_seg 

print(fr_seg)

Output:

array([15, 16, 17, 18, 19, 0, 0, 0, 0, 0])


You can simulate what it does in a 3D array using np.random.rand :

fr_seg = np.random.rand(600, 128, 128)
fr_seg = fr_seg * 10 + 15  # the range should be from 15 to 25

th_seg = fr_seg < 20
fr_seg *= th_seg

print(fr_seg)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM