Saturday, 13 March 2021

opencv 12 adjust contrast

original image, contrast = 0

increased contrast to 5

#main.py
import numpy as np
import cv2

cap = cv2.VideoCapture("assets/Santa Barbara.mp4")
brightness = 50
contrast = 0

trackbars_img = np.uint8(np.full((50, 500, 3), 255))
cv2.imshow('trackbars', trackbars_img)

def brightness_change(x):
    global brightness
    brightness = x

def contrast_change(x):
    global contrast
    contrast = x

cv2.createTrackbar('Brightness', 'trackbars', 50, 100, brightness_change)
cv2.createTrackbar('Contrast', 'trackbars', 0, 10, contrast_change)

while True:
    ret, frame = cap.read()
    width = int(cap.get(3))
    height = int(cap.get(4))

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(hsv)

    brightness_adjuster = int((brightness - 50) / 50 * 255)
    #print(brightness_adjuster)

    v_int16 = np.int16(v) + brightness_adjuster
    v_int16[v_int16 > 255] = 255
    v_int16[v_int16 < 0] = 0
    #print(v_int16)

    v = np.uint8(v_int16)
    #print(v)
    final_hsv = cv2.merge((h, s, v))

    image = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)

    #cv2.imshow('frame', image)

    lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
    #cv2.imshow('lab', lab)

    l, a, b = cv2.split(lab)
    #cv2.imshow('l_channel', l)
    #cv2.imshow('a_channel', a)
    #cv2.imshow('b_channel', b)

    clahe = cv2.createCLAHE(clipLimit=0.01 + contrast, tileGridSize=(8, 8))
    cl = clahe.apply(l)
    #cv2.imshow('CLAHE output', cl)

    limg = cv2.merge((cl, a, b))
    #cv2.imshow('limg', limg)

    final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)

    cv2.imshow('frame', final)

    if cv2.waitKey(1) == ord('q'):
        break

    if cv2.waitKey(1) == ord('p'):
        # wait until any key is pressed
        cv2.waitKey(-1)

cap.release()
cv2.destroyAllWindows()

No comments:

Post a Comment