Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : overflow while subtraction

import cv2
image1 = cv2.imread('one.jpg', 0)
image2 = cv2.imread('two.jpg', 0)
diff   = image1 - image2

For the above code, for some values, overflow due to subtraction is taking place. For eg:

238 - 254 = 240

What can I do to prevent this overflow and instead get -16 as the answer?

like image 335
whatdoisay Avatar asked Dec 10 '25 08:12

whatdoisay


1 Answers

So here's the optimized answer after you have provided the cv2 module.

Your answer showed the issue:

>>> import cv2
>>> img = cv2.imread('myimage.jpg', 0)
>>> img.dtype
dtype('uint8')

This means, as you correctly stated, that it is an unsigned 8-bit integer, which can only take values from 0-255.

You can, however, automatically convert the array to a better dtype which is much more memory efficient than doing int(value). For example...

>>> img[0][0] 
0
>>> img[0][0] -= 1
>>> img[0][0]
255 # since it's uint8
>>> img[0][0] += 1
>>> img2 = img.astype('uint16')
>>> img2[0][0] -= 1
>>> img2[0][0]
65535 # since it's uint16

You an also convert to other types other than uint8, 16, 32, and 64. For example...

>>> img3 = img2.astype('int64') # signed int64
>>> img3[0][0] -= 7000000
>>> img3[0][0]
-6934465

In short, rather than using Python's built-in type conversion, you can manually specify the dtypes from uint8-64 and int8-64 (and maybe more) using NumPy's dtypes, by specifying the newarray = array.astype('type'), creating a compact and efficient array using the new dtype. You can also specificy other types, such as 'int', 'bool', 'object', etc., showing the versatility and utility of NumPy arrays.

To read more about the dtypes and how to use them, the link to the SciPy documentation is here.

like image 118
Alexander Huszagh Avatar answered Dec 11 '25 23:12

Alexander Huszagh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!