Python numpy subtraction no negative numbers (4-6 gives 254)

NumesSanguis picture NumesSanguis · Oct 31, 2014 · Viewed 10.8k times · Source

I wish to subtract 2 gray human faces from each other to see the difference, but I encounter a problem that subtracting e.g. [4] - [6] gives [254] instead of [-2] (or difference: [2]).

print(type(face)) #<type 'numpy.ndarray'>
print(face.shape) #(270, 270)
print(type(nface)) #<type 'numpy.ndarray'>
print(nface.shape) #(270, 270)

#This is what I want to do:
sface = face - self.nface #or
sface = np.subtract(face, self.nface)

Both don't give negative numbers but instead subtract the rest after 0 from 255.

Output example of sface:

[[  8 255   8 ...,   0 252   3]
 [ 24  18  14 ..., 255 254 254]
 [ 12  12  12 ...,   0   2 254]
 ..., 
 [245 245 251 ..., 160 163 176]
 [249 249 252 ..., 157 163 172]
 [253 251 247 ..., 155 159 173]]

My question: How do I get sface to be an numpy.ndarray (270,270) with either negative values after subtracting or the difference between each point in face and nface? (So not numpy.setdiff1d, because this returns only 1 dimension instead of 270x270)

Working

From the answer of @ajcr I did the following (abs() for showing subtracted face):

face_16 = face.astype(np.int16)
nface_16 = nface.astype(np.int16)
sface_16 = np.subtract(face_16, nface_16)
sface_16 = abs(sface_16)
sface = sface_16.astype(np.int8)

Answer

Alex Riley picture Alex Riley · Oct 31, 2014

It sounds like the dtype of the array is uint8. All the numbers will be interpreted as integers in the range 0-255. Here, -2 is equal to 256 - 2, hence the subtraction results in 254.

You need to recast the arrays to a dtype which supports negative integers, e.g. int16 like this ...

face = face.astype(np.int16)

...and then subtract.