Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

python - How to fill image with repeated indices using the max value

I am using numpy array to create an image from a set of 3d points. The 3d points are projected to image coordinate and some of the points fall on the same indices (x, y) of the image. I just want to keep the point with maximum x value.

Let show it with an example:

idx = array(
       [[3, 3], [7, 3],[0, 1],[0, 6],[6, 9],[8, 1],[7, 3],[8, 3],[8, 4],[9, 5]]
)
x_val = array([
       [0.17166161],
       [0.80913063],
       [0.52597124],
       [0.27078974],
       [0.35230144],
       [0.66411425],
       [0.28035714],
       [0.76413514],
       [0.27064702],
       [0.54131715]]
)

im[idx[:, 1], idx[:, 0]] = x_val

The problem I am facing is with the line that is there are two indices [7, 3] with different x_val, [0.80913063, 0.28035714] from which i want to retain the maximum i.e., im[7, 3] = 0.80913063. How can I do this with numpy?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can first sort the x_val array in acsending order and then assign to im. If an index occurs multiple times the last assignment, which is the highest value, will set the final value.

import numpy as np

im = np.zeros((10,10))
idx = np.array(
       [[3, 3], [7, 3],[0, 1],[0, 6],[6, 9],[8, 1],[7, 3],[8, 3],[8, 4],[9, 5]]
)
x_val = np.array([
       [0.17166161],
       [0.80913063],
       [0.52597124],
       [0.27078974],
       [0.35230144],
       [0.66411425],
       [0.28035714],
       [0.76413514],
       [0.27064702],
       [0.54131715]]
)

order = x_val.argsort(0)[:,0]
im[idx[order][:, 1], idx[order][:, 0]] = x_val[order][:,0]

Result:

[[0.   0.   0.   0.   0.   0.   0.   0.   0.   0.  ]
 [0.53 0.   0.   0.   0.   0.   0.   0.   0.66 0.  ]
 [0.   0.   0.   0.   0.   0.   0.   0.   0.   0.  ]
 [0.   0.   0.   0.17 0.   0.   0.   0.81 0.76 0.  ]
 [0.   0.   0.   0.   0.   0.   0.   0.   0.27 0.  ]
 [0.   0.   0.   0.   0.   0.   0.   0.   0.   0.54]
 [0.27 0.   0.   0.   0.   0.   0.   0.   0.   0.  ]
 [0.   0.   0.   0.   0.   0.   0.   0.   0.   0.  ]
 [0.   0.   0.   0.   0.   0.   0.   0.   0.   0.  ]
 [0.   0.   0.   0.   0.   0.   0.35 0.   0.   0.  ]]

(I used the indexing order from your OP, i.e. idx[1], which is [7,3], will go into im[3,7] so that im[3, 7] == 0.80913063)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...