pythonnumpyopencvmathinteger-arithmetic

Python Overflow Warning in Scalar Add


I want to perfom a simple operation: b+g+r b,g,r variables are integrers and have value below 256. I get Overflow Warning and wrong results. The problem is that the operation is simple(result not above 765) and I shouldn't get Overflow Warnings

Here is my code:


import cv2 as cv
import numpy as np

imgname = 'r_hh_classic.png'

img = cv.imread(imgname)

h,w,_ = img.shape

for y in range(h):
    for x in range(w):
        b,g,r = img[y,x]
        print(b,g,r,b+g+r) #print var b, var g, var r, and b+g+r
        if b+g+r <= 382:
            img[y,x] = 255-img[y,x,0], 255-img[y,x,1], 255-img[y,x,2]

cv.imshow('',img)

Python Shell:

Warning (from warnings module):
  File "C:/Users/USER/AppData/Local/Programs/Python/Python310/!Saves/_images_/negate 2.py", line 14
    print(b,g,r,b+g+r)
RuntimeWarning: overflow encountered in scalar add
165 159 191 3

Warning (from warnings module):
  File "C:/Users/USER/AppData/Local/Programs/Python/Python310/!Saves/_images_/negate 2.py", line 15
    if b+g+r <= 382:
RuntimeWarning: overflow encountered in scalar add
165 159 191 3
165 159 191 3
164 157 191 0
162 156 191 253
161 155 190 250
161 155 190 250
161 154 190 249
160 154 189 247
160 154 189 247
160 152 189 245
159 151 188 242
159 151 188 242
157 151 188 240
157 151 188 240
156 149 186 235
155 148 185 232
154 148 185 231
154 148 185 231
154 146 185 229
152 145 185 226
152 145 185 226
152 145 185 226
152 145 184 225
151 143 183 221
150 143 184 221
150 143 184 221
149 142 182 217
149 142 182 217
149 140 181 214
148 140 181 213
146 139 181 210
146 138 181 209

first 3 numbers are b,g,r and 4th is b+g+r but you can see, its extremly wrong


Solution

  • I was trying to fit the result in unit8 when using dtype uint8 anything more than 255 overflows. To avoid overflow use cv2.add() (see docs.opencv.org/4.7.0/d0/d86/tutorial_py_image_arithmetics.html)

    Written as answer from coments

    Answered by: @Barmar , @stateMachine , @Severin Pappadeux (see coments)