Home > Enterprise >  How to update the elements of an array in a for loop
How to update the elements of an array in a for loop

Time:10-01

I have an array called img. I want to check for the elements in the array which are negative, and then add 65536 to those elements. But for some reason, the array is not getting updated and when I print it, the old negative values are still being shown.

img = I
imgx,imgy = img.shape

for i in range(0,imgy):
    for j in range(0,imgx):
        if (img[i,j] < 0):
            img[i,j] = img[i,j]   65536
            print(i,j,img[i,j])

I also tried this:

            img[i,j] =  = 65536

instead of this:

            img[i,j] = img[i,j]   65536

in the loop, but to no avail. When I print the indices and the elements after updating, in either case, this is what I'm getting:

i   j   img[i,j]
513 467 -31460
513 468 -31981
514 467 -30423
514 468 -31172
514 469 -32656
515 467 -31554
515 468 -31534
515 469 -32114

I'm sure I'm missing something very basic here, but I'm kinda new to Python, and any help would be greatly appreciated.

Thanks!

CodePudding user response:

if you pass any negative value to unsigned int , it will automatically roll over it to positive quantity. change your array type to unsigned int...

or

is it a thing in python such as unsigned int?????

CodePudding user response:

Your code may have failed if your array was of int16 type. Notice also that 65536 is just 2 ** 16, so if you add just this number to int16, nothing actually changes.

To quickly perform conditional addition, run:

img = np.where(img < 0, img   65536, img)

This time a new array is generate and saved back under img.

Since 65536 exceeds the limit of numbers which can be saved in an int16 (signed) variable, the type of the output array is int32.

To check my code, I created a source (smaller) array, of int16 type, as:

np.random.seed(0)
img = np.random.randint(-4000, 10000, (5, 5), dtype='int16')

getting:

array([[-1268,  -801,  6799,  2084,  5845],
       [ -736,  2177,  9123,  2734,   859],
       [ 3074, -1059,  2373,  5225,  7380],
       [ 3891,  4097,   373,  5561,  1874],
       [ 4806,  8293,  -885,  5291,  -284]], dtype=int16)

After I executed my code, img contained:

array([[64268, 64735,  6799,  2084,  5845],
       [64800,  2177,  9123,  2734,   859],
       [ 3074, 64477,  2373,  5225,  7380],
       [ 3891,  4097,   373,  5561,  1874],
       [ 4806,  8293, 64651,  5291, 65252]], dtype=int32)

So you can see that:

  • the output contains no negative values,
  • the array type has been changed to int32.
  • Related