Home > Blockchain >  Set specifict value to a range of values in a numpy array
Set specifict value to a range of values in a numpy array

Time:01-04

I am trying to set the values in an array (image), the goal is that all values with 0 are set to a certain range, and where there is another value different from 0 are adjusted to another range, I have a solution but it is very slow and I would like to optimize it, is the following:

list_heatmap = [[np.random.randint(20, 120) if i == 0 else np.random.randint(160, 250)
                 for i in row]
                 for row in binary_image]
range_image = np.array(list_heatmap).astype('uint8')

Also, I have tried np.where(), however, when I try to set the value it only applies one of the selected range, i.e. it changes all 0's to 100.

I leave an example with a 1D array as an example of what I am trying.

input = [0,0,0,1,1,0,1]

output = [20,100,75,180,195,37,207]

CodePudding user response:

You can create an array of random numbers the same size as your input to use in np.where:

import numpy as np

arr = np.array([0,0,0,1,1,0,1])

rand_if_true = np.random.randint(20, 120, size=arr.shape)
rand_if_false = np.random.randint(160, 250, size=arr.shape)

out = np.where(arr == 0, rand_if_true, rand_if_false)

out:

array([100,  95,  35, 227, 247,  63, 242])
  • Related