0
$\begingroup$

Im trying to brighten and dim an image using OpenCV with two approaches.

Approach 1: Used OpenCV's add and subtract functions to brigthen and dim the image.
Approach 2: Manually added/subtracted pixel values.

Both produced different results, with the OpenCV approach producing better results than the manual as you can see in the output image below. Why is this happening?.

Code:

img = cv2.imread('New_Zealand_Coast.jpg',cv2.IMREAD_COLOR)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Matrix for storing pixel alter values
mat = np.ones(img.shape, dtype='uint8') * 70

# Approach 1
img_brighter = cv2.add(img, mat)
img_dimmer = cv2.subtract(img, mat)

# Approach 2
img_brighter_manual = img + mat
img_dimmer_manual = img - mat

# Plot Approach 1
plt.figure(figsize=(20,6))
plt.subplot(131)
plt.imshow(img)
plt.title('Original 1')
plt.subplot(132)
plt.imshow(img_brighter)
plt.title('Brighter')
plt.subplot(133)
plt.imshow(img_dimmer)
plt.title('Dimmer')
plt.suptitle('Approach 1 : With CV Add/Subtract Function')

# Plot Approach 2
plt.figure(figsize=(20,6))
plt.subplot(131)
plt.imshow(img)
plt.title('Original 1')
plt.subplot(132)
plt.imshow(img_brighter_manual)
plt.title('Brighter')

plt.subplot(133)
plt.imshow(img_dimmer_manual)
plt.title('Dimmer')
plt.suptitle('Approach 2 : With manual Add/Subtract')

Output:
enter image description here

Original Image Array:

Original Image Array

Modified array from Approach 1:

enter image description here

Modified array from Approach 2:

enter image description here

As you can see, there is some difference in the elements of arrays produced by the two approaches.

Here is the original image used in the code, in case you want to test with it.
enter image description here

$\endgroup$

1 Answer 1

1
$\begingroup$

The issue is caused by the fact that the resulting value of the manual addition is larger than the maximum value it can store. The data type of the array is uint8, which can hold a maximum value of 255, whereas the resulting value of the addition (for the one shown in your screenshot) is 188 + 70 = 258. This will cause an overflow where the value will wrap around and start from zero, resulting in a value of 258 - 256 (256 because the range of values it can store is 0-255) = 2. A way to solve this problem is by performing an extra check that checks if the resulting value is lower than the original value, and if it is, set the output value to 255:

# Approach 2
img_brighter_manual = img + mat
# extra check on output values
img_brighter_manual[img_brighter_manual < img] = 255

The same approach can be applied when darkening the image (i.e. subtracting values), except for the other way around.

$\endgroup$
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.