RuntimeWarning: overflow encountered in ubyte_Scalars pixel addition and subtraction overflow exception

When using Python to process an image, it may involve the addition and subtraction between the pixel values of two images. Here, it should be noted that the pixel value of the image is of ubyte type, and the data range of ubyte type is 0-255. If the operation results in a negative value or exceeds 255, an exception will be thrown. Let’s take a look at an example of the exception

from PIL import Image
import numpy as np
image1 = np.array("1.jpg"))                   
image2 = np.array("2.jpg"))                  
# Exception statement
temp = image1[1, 1] - image2[1, 1] # Overflow if this is a negative value

# The correct way to write
temp = int(image1[1, 1]) - int(image2[1, 1]) # force to integer and then calculate without overflowing

The above code is the exception runtimewarning: overflow accounted in ubyte_ Scalars of the reasons and solutions, I hope to help friends who encounter this problem.


Read More: