0

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?

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh this worked perfectly! Thank you, your answer makes perfect sense.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.