| 1 |
import cv2 as cv |
| 2 |
import numpy as np |
| 3 |
import argparse |
| 4 |
|
| 5 |
alpha = 1.0 |
| 6 |
alpha_max = 500 |
| 7 |
beta = 0 |
| 8 |
beta_max = 200 |
| 9 |
gamma = 1.0 |
| 10 |
gamma_max = 200 |
| 11 |
|
| 12 |
def basicLinearTransform(): |
| 13 |
res = cv.convertScaleAbs(img_original, alpha=alpha, beta=beta) |
| 14 |
img_corrected = cv.hconcat([img_original, res]) |
| 15 |
cv.imshow("Brightness and contrast adjustments", img_corrected) |
| 16 |
|
| 17 |
def gammaCorrection(): |
| 18 |
|
| 19 |
lookUpTable = np.empty((1,256), np.uint8) |
| 20 |
for i in range(256): |
| 21 |
lookUpTable[0,i] = np.clip(pow(i / 255.0, gamma) * 255.0, 0, 255) |
| 22 |
|
| 23 |
res = cv.LUT(img_original, lookUpTable) |
| 24 |
|
| 25 |
|
| 26 |
img_gamma_corrected = cv.hconcat([img_original, res]) |
| 27 |
cv.imshow("Gamma correction", img_gamma_corrected) |
| 28 |
|
| 29 |
def on_linear_transform_alpha_trackbar(val): |
| 30 |
global alpha |
| 31 |
alpha = val / 100 |
| 32 |
basicLinearTransform() |
| 33 |
|
| 34 |
def on_linear_transform_beta_trackbar(val): |
| 35 |
global beta |
| 36 |
beta = val - 100 |
| 37 |
basicLinearTransform() |
| 38 |
|
| 39 |
def on_gamma_correction_trackbar(val): |
| 40 |
global gamma |
| 41 |
gamma = val / 100 |
| 42 |
gammaCorrection() |
| 43 |
|
| 44 |
parser = argparse.ArgumentParser(description='Code for Changing the contrast and brightness of an image! tutorial.') |
| 45 |
parser.add_argument('--input', help='Path to input image.', default='..\Images\Jupiter.png') |
| 46 |
args = parser.parse_args() |
| 47 |
|
| 48 |
img_original = cv.imread(cv.samples.findFile(args.input)) |
| 49 |
if img_original is None: |
| 50 |
print('Could not open or find the image: ', args.input) |
| 51 |
exit(0) |
| 52 |
|
| 53 |
img_corrected = np.empty((img_original.shape[0], img_original.shape[1]*2, img_original.shape[2]), img_original.dtype) |
| 54 |
img_gamma_corrected = np.empty((img_original.shape[0], img_original.shape[1]*2, img_original.shape[2]), img_original.dtype) |
| 55 |
|
| 56 |
img_corrected = cv.hconcat([img_original, img_original]) |
| 57 |
img_gamma_corrected = cv.hconcat([img_original, img_original]) |
| 58 |
|
| 59 |
cv.namedWindow('Brightness and contrast adjustments') |
| 60 |
cv.namedWindow('Gamma correction') |
| 61 |
|
| 62 |
alpha_init = int(alpha *100) |
| 63 |
cv.createTrackbar('Alpha gain (contrast)', 'Brightness and contrast adjustments', alpha_init, alpha_max, on_linear_transform_alpha_trackbar) |
| 64 |
beta_init = beta + 100 |
| 65 |
cv.createTrackbar('Beta bias (brightness)', 'Brightness and contrast adjustments', beta_init, beta_max, on_linear_transform_beta_trackbar) |
| 66 |
gamma_init = int(gamma * 100) |
| 67 |
cv.createTrackbar('Gamma correction', 'Gamma correction', gamma_init, gamma_max, on_gamma_correction_trackbar) |
| 68 |
|
| 69 |
on_linear_transform_alpha_trackbar(alpha_init) |
| 70 |
on_gamma_correction_trackbar(gamma_init) |
| 71 |
|
| 72 |
cv.waitKey() |