Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Numpy slicing leads to changed value

I am currently working with some python code and one piece of code keeps ruining my day:

print(img.shape) # prints (4, 64, 64, 3)
scaled = np.array(img, copy=True)                                                           
test = np.array(img, copy=True) / 255                                                                                                                                                                   
scaled[:, :, :, :3] = scaled[:, :, :, :3] / 255.0                                                                                                          
print(np.all(scaled == test)) # prints false

My problem here is that the slice operation seems to change the value of the operation. As far as I understand it, scaled and test should be the same. Am I just missing something or where exactly lies my error?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

numpy is stricter about data types than Python. img is an integer datatype, so scaled is also an integer data type. test is created as a float data type. When you do the in-place division, it does a floating divide, then casts the result back to integer to store it in the array.

If you had printed out the two arrays, this would have been obvious.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading