Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify each element of a numpy multidimentional array conditionally?

Tags:

python

numpy

I converted an image into a gray scale numpy array using opencv:

im_g=cv2.imread("smallgray.png",0)
print(im_g)

[[187 158 104 121 143]
 [198 125 255 255 147]
 [209 134 255  97 182]]

I want to darken the image for those values that are higher than 200 for example, being 255 white and 0 black. If I do this I get the correct result:

im_g[im_g>200] = 150
print(im_g)

[[187 158 104 121 143]
 [198 125 150 150 147]
 [150 134 150  97 182]]

But my question is, if I don't want to use a constant (like 150 in the example) and instead perform some calculation on the current element, how do I refer to that element??

Thanks in advance

like image 976
Juan Avatar asked Jan 21 '26 02:01

Juan


1 Answers

You can easily vectorize your operation using where:

im_g = np.where(im_g < 150, im_g, np.random.randint(1, 40, size=im_g.shape))
like image 101
Nils Werner Avatar answered Jan 22 '26 17:01

Nils Werner