Why does dividing an np.array behave differently from dividing an array element directly

Question:

I’m trying to normalize an uint8 np.array by dividing it by 255.0.
When I divide the array by 255.0 the dtype of it’s element changes to float64.
When I only divide the element itself by 255.0, the elements dtype stays uint8.
Why does the division behave differently here?

In the example below, I was expecting two similar results:

Array1 = np.array([179],dtype="uint8")
Array2 = np.array([179],dtype="uint8")

Array1[0] = Array1[0] /255.0
Array2 = Array2 / 255.0

print(Array1[0].dtype)
print(Array2[0].dtype)

Results in:

uint8
float64
Asked By: user20448774

||

Answers:

Float division is always 64-bit float. When you do it for a single element, it will convert it back to the type of the array (int8 in your case). If do it for the whole array, it will change the type of the array to the result type.

You can can use python’s integer division (//). [However, it will result in pure zeros in your case (any 8-bit divided by 255 will be 0)]

Array1 = np.array([179],dtype="uint8")
Array2 = Array2 // 255
print(Array2[0].dtype) # uint8 

(or convert it back after float division Array2 = Array2.astype("uint8"))

Addition: If your aim is to do a float division element wise, then convert the array to float before the division: Array2 = Array2.astype("float64")

Answered By: tturbo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.