pythonnumpyuint

How to force negative values to 0 in unsigned dtypes?


I want to substract one image from another one (both uint8 dtype) but if this operation leads to a negative number, it should return the max value of uint8 dtype (i.e : 255)

How can I force it to return 0?

Note: If possible i don't want to transform the images in int8 then np.clip the image.

import numpy as np  

img1 = np.zeros(1, dtype = np.uint8)  
img2 = np.ones(1, dtype = np.uint8)  
img = img1 - img2  
  
print(img1)  
print(img2)  
print(img)  

Solution

  • Since you're using uint8, all numbers will be in the range [0,255]. In such case, a negative 1 results in 255, -2 in 254 and so on. If casting to a signed dtype is not an option, you could use np.where to subtract based on a condition, for instance:

    img1 = np.arange(4, dtype=np.uint8)
    img2 = np.ones(4, dtype=np.uint8)
    
    np.where(img1>img2, img1-img2, 0)
    # array([0, 0, 1, 2], dtype=uint8)
    

    Which would otherwise produce:

    img1-img2
    # array([255,   0,   1,   2], dtype=uint8)