直方图与gamma校正 — OpenCV& Python

如题所述

第1个回答  2022-07-20
···
import cv2
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

img_path = 'C:/Users/WZChan/Desktop/'
img = cv2.imread(img_path + 'test_600x350_imwrite.jpg')

hist_b = cv2.calcHist([img], [0], None, [256], [0, 256])
hist_g = cv2.calcHist([img], [0], None, [256], [0, 256])
hist_r = cv2.calcHist([img], [0], None, [256], [0, 256])

def gamma_trans(img, gamma):
gamma_table = [np.power(x / 255.0, gamma)*255.0 for x in range(256)]
gamma_table = np.round(np.array(gamma_table)).astype(np.uint8)

img_corrected = gamma_trans(img, 0.5)
cv2.imwrite(img_path + 'gamma_corrected.jpg', img_corrected)

hist_b_corrected = cv2.calcHist([img_corrected], [0], None, [256], [0, 256])
hist_g_corrected = cv2.calcHist([img_corrected], [0], None, [256], [0, 256])
hist_r_corrected = cv2.calcHist([img_corrected], [0], None, [256], [0, 256])

fig = plt.figure()
pix_hists = [
[hist_b, hist_g, hist_r],
[hist_b_corrected, hist_g_corrected, hist_r_corrected]
]
pix_vals = range(256)

for sub_plt, pix_hists in zip([121, 122], pix_hists):
ax = fig.add_subplot(sub_plt, projection = '3d')
for c, z, channel_hist in zip(['b', 'g', 'r'], [20, 10, 0], pix_hists):
cs = [c] * 256
ax.bar(pix_vals, channel_hist, zs=z, zdir='y', color=cs, alpha=0.618, edgecolor='none', lw=0)
ax.set_xlabel('Pixel Value')
ax.set_xlim([0, 256])
ax.set_ylabel('Counts')
ax.set_zlabel('Channels')

plt.show()
···
相似回答