how to change image illumination in opencv python
I know I am late, but I would suggest using gamma correction.
Now what is gamma correction?
I will make it clear in layman's terms:
- To display image on a screen, input voltage is needed.
- This voltage is output as light intensity.
- In perfect world, input voltage would be linear to output intensity.
- But the real screen output is close to an exponential curve, the exponent being gamma.
Since the computer screen applies a gamma value to the image on screen, the process of applying inverse gamma to counter this effect is called gamma correction.
Here is the code for the same using OpenCV 3.0.0 and python:
import cv2
import numpy as np
def adjust_gamma(image, gamma=1.0):
invGamma = 1.0 / gamma
table = np.array([((i / 255.0) ** invGamma) * 255
for i in np.arange(0, 256)]).astype("uint8")
return cv2.LUT(image, table)
x = 'C:/Users/524316/Desktop/stack/test.jpg' #location of the image
original = cv2.imread(x, 1)
cv2.imshow('original',original)
gamma = 0.5 # change the value here to get different result
adjusted = adjust_gamma(original, gamma=gamma)
cv2.putText(adjusted, "g={}".format(gamma), (10, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 3)
cv2.imshow("gammam image 1", adjusted)
cv2.waitKey(0)
cv2.destroyAllWindows()
Here is the original image:
Applying gamma of value 0.5 will yield:
Applying gamma of value 1.5 will yield:
Applying gamma of value 2.5 will yield:
Applying gamma of value 1.0 will yield the same image.
Code was borrowed from this link
A small remark to complement Jeru Luke's answer. Be sure that both arrays are of type np.uint8
. The cv.LUT
function name stands for "look-up-table". It means that each pixel from the image
is replaced with a value from the table
.
You could convert both arrays:
def adjust_gamma(image, gamma=1.0):
invGamma = 1.0 / gamma
table = np.array([
((i / 255.0) ** invGamma) * 255
for i in np.arange(0, 256)])
return cv2.LUT(image.astype(np.uint8), table.astype(np.uint8))
Or make sure that an image array is casted to the valid type before passing into adjust_gamma()
function. It is easy to convert the image into float
while applying various transformations and forget to restore valid type before adjusting gamma.
I think you can done this with opencv. Here is my suggestion
import cv2
import numpy as np
img1 = cv2.imread('abc.jpg')
a = np.double(img1)
b = a + 15
img2 = np.uint8(b)
cv2.imshow("frame",img1)
cv2.imshow("frame2",img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
Here i increased the brightness of image. If you use subtraction that will makes darker.