I have a sequence of images. I need to average brightness of these images.
First example (very slow):
img = cv2.imread(\'test.jpg\')
I know this shouldn't be so hard and there to adjust the brightness of an image. Also, there are already plenty of great answers. I would like to enhance the answer of @BillGrates, so it works on grayscale images and with decreasing the brightness: value = -255 creates a black image whereas value = 255 a white one.
def adjust_brightness(img, value):
num_channels = 1 if len(img.shape) < 3 else 1 if img.shape[-1] == 1 else 3
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) if num_channels == 1 else img
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
if value >= 0:
lim = 255 - value
v[v > lim] = 255
v[v <= lim] += value
else:
value = int(-value)
lim = 0 + value
v[v < lim] = 0
v[v >= lim] -= value
final_hsv = cv2.merge((h, s, v))
img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if num_channels == 1 else img
return img