pythonnumpyintegerinteger-overflow

Numpy array from the image is not squaring right


I have this program that is supposed to select one color channel from an image, and square each element elementwise. However, it is not returning any results greater than the values in the first array? As if it is bounded? I have tried squaring it in numerous ways and it works fine for non-imported image datasets. Below is the code run on a Mac and the results:

import numpy as np

import cv2

im = cv2.imread("blue")

im22=im

im22[im22<100] = 0

blue=np.array(im22[:,:,2])

blue2=np.square(blue)

print("type is ",type(blue))

print("blue max", np.max(blue))

print("blue min",np.min(blue))

print("blue Squared max", np.max(blue2))

print("blue Squared min",np.min(blue2))

Results are:

blue max 255

blue min 0

blue Squared max 249

blue Squared min 0


Solution

  • According to Nin17 comment, I added the missing line :

    import numpy as np
    
    import cv2
    
    im = cv2.imread("blue")
    
    im22=im
    
    im22[im22<100] = 0
    
    blue=np.array(im22[:,:,2])
    
    blue = blue.astype(np.uint16)
    
    blue2=np.square(blue)
    
    print("type is ",type(blue))
    
    print("blue max", np.max(blue))
    
    print("blue min",np.min(blue))
    
    print("blue Squared max", np.max(blue2))
    
    print("blue Squared min",np.min(blue2))
    

    It worked on my setup

    ▶ more pyproject.toml
    [project]
    name = "python"
    version = "0.1.0"
    description = "Add your description here"
    readme = "README.md"
    requires-python = ">=3.12"
    dependencies = [
        "numpy>=2.3.0",
        "opencv-python>=4.11.0.86",
    ]