No products in the cart.
After searching for hours for this code, below is Python code for automatically optimizing image contrast and brightness. The code then auto sharpens the image with conservative settings. I applied this to an ESRGAN output in Google Colab. Enjoy!
#@title SHARPEN, AUTO BRIGHTNESS AND CONTRAST, .WEBP VIA CV2
from tqdm import tqdm
import os
import glob
import cv2
import numpy as np
from matplotlib import pyplot as plt
rootdir = "/content/drive/My Drive/Colab-ESRGAN/output/" #@param
extention = '.webp' #@param [".webp", ".jpg"] {allow-input: false}
files = glob.glob(rootdir + '/**/*.png', recursive=True)
# Automatic brightness and contrast optimization with optional histogram clipping
def automatic_brightness_and_contrast(image, clip_hist_percent=1):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Calculate grayscale histogram
hist = cv2.calcHist([gray],[0],None,[256],[0,256])
hist_size = len(hist)
# Calculate cumulative distribution from the histogram
accumulator = []
accumulator.append(float(hist[0]))
for index in range(1, hist_size):
accumulator.append(accumulator[index -1] + float(hist[index]))
# Locate points to clip
maximum = accumulator[-1]
clip_hist_percent *= (maximum/100.0)
clip_hist_percent /= 2.0
# Locate left cut
minimum_gray = 0
while accumulator[minimum_gray] < clip_hist_percent:
minimum_gray += 1
# Locate right cut
maximum_gray = hist_size -1
while accumulator[maximum_gray] >= (maximum - clip_hist_percent):
maximum_gray -= 1
# Calculate alpha and beta values
alpha = 255 / (maximum_gray - minimum_gray)
beta = -minimum_gray * alpha
'''
# Calculate new histogram with desired range and show histogram
new_hist = cv2.calcHist([gray],[0],None,[256],[minimum_gray,maximum_gray])
plt.plot(hist)
plt.plot(new_hist)
plt.xlim([0,256])
plt.show()
'''
auto_result = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)
return (auto_result, alpha, beta)
#sharpening_kernel = np.array([[-1, -1, -1], [-1, 9.2, -1], [-1, -1, -1]])
sharpening_kernel = np.array([[0, -1, 0], [-1, 5.3, -1], [0, -1, 0]])
for file in tqdm(files):
image = cv2.imread(file)
auto_result, alpha, beta = automatic_brightness_and_contrast(image)
image_sharp = cv2.filter2D(src=auto_result, ddepth=-1, kernel=sharpening_kernel)
cv2.imwrite(os.path.join(rootdir, os.path.splitext(os.path.basename(file))[0] + extention), image_sharp)
os.remove(file)