M.Brodie1221
M.Brodie1221

Reputation: 96

Adding and subtracting is not effecting all elements of a numpy array

I am attempting to do a normalization on an image set which involves, among other things, adding a constant to every value in the image.

Here is an example, using the image at the following url: https://helpx.adobe.com/content/dam/help/en/stock/how-to/visual-reverse-image-search/jcr_content/main-pars/image/visual-reverse-image-search-v2_intro.jpg

import numpy as np
import cv2

img = cv2.imread("imagepath.jpeg")

arraymin = np.min(img)
print(arraymin)

The value of arraymin is 0. I attempt to add to the entire array by, for example 10. I try this 3 different ways

img = img + 10
img += 10
img2 = np.add(img, 10)

This successfully adds 10 (total 30) to most values in the array, but when i call np.min on the array again, the minimum value is still 0

print(np.min(img))
print(np.min(img2))

I can verify that 0 is in the array by calling 0 in img which produces a True value.

Why do the 0 values not get changed by the addition of the value of 10 to the entire array?

Upvotes: 0

Views: 598

Answers (2)

Ha Bom
Ha Bom

Reputation: 2917

You can also use cv2.add to add 2 images and when the value exceed 255, it will be 255:

to_add = np.ones_like(img)*10
added = cv2.add(img, x)

Upvotes: 0

Seb
Seb

Reputation: 4586

The array you've created from this image file has a data type of uint8, with a maximum value of 255. When adding positive numbers to the array, some elements will roll over this value. In particular, any pixel's colour channel that had the value 246 will be 0 when you add 10 to it:

>>> np.array([246], dtype='uint8') + 10
array([0], dtype=uint8)

If you want to perform some arithmetic on the image, first convert it to a larger integer type or ideally float by calling:

>>> img = img.astype(float)

Upvotes: 3

Related Questions