本文主要是介绍图像处理:基于直方图矫正的图像色彩均衡,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
from itertools import chain
import cv2
import os
import numpy as np
import datetimeclass BrightnessBalance:def __init__(self):passdef arrayToHist(self,gray):'''计算灰度直方图,并归一化:param gray_path::return:'''w,h = gray.shapehist = list(chain.from_iterable(cv2.calcHist([gray],[0],None,[256],[0,256])))hist = np.array(hist)/(w*h)return histdef histMatch(self, gray1, gray2):'''gray2向gray1校准:param image_path1::param image_path2::return:'''if not os.path.exists(image1_path) or not os.path.exists(image2_path):print('image1_path or image2_path is not exist!')returngray2Array = np.array(gray2)hist1 = self.arrayToHist(gray1)hist2 = self.arrayToHist(gray2Array)tmp1 = 0.0tmp2 = 0.0h_acc1 = hist1.copy()h_acc2 = hist2.copy()for i in range(256):tmp1 += hist1[i]tmp2 += hist2[i]h_acc1[i] = tmp1h_acc2[i] = tmp2M = np.zeros(256)for i in range(256):idx = 0minv = 1for j in range(0,len(h_acc1)):if (np.fabs(h_acc1[j] - h_acc2[i]) < minv):minv = np.fabs(h_acc1[j] - h_acc2[i])idx = int(j)M[i] = idxresult = M[gray2Array]return resultdef colors_histMatch(self,image_path1,image_path2):if not os.path.exists(image1_path) or not os.path.exists(image2_path):print('image1_path or image2_path is not exist!')returnimg1 = cv2.imread(image1_path)img2 = cv2.imread(image2_path)result1_chaneel_b = self.histMatch(img1[:, :, 0], img2[:, :, 0])result1_chaneel_g = self.histMatch(img1[:, :, 1], img2[:, :, 1])result1_chaneel_r = self.histMatch(img1[:, :, 2], img2[:, :, 2])result = cv2.merge([result1_chaneel_b,result1_chaneel_g,result1_chaneel_r])return resultif __name__ == '__main__':image1_path = r"D:\CV_Data\n\current.jpg"image2_path = r"D:\CV_Data\n\history.jpg"starttime = datetime.datetime.now()BB = BrightnessBalance()img1 = cv2.imread(image1_path,0)img2 = cv2.imread(image2_path,0)histMatch = BB.histMatch(img1,img2)endtime = datetime.datetime.now()print(endtime - starttime)save_path = image2_path.replace('history.jpg', 'result1.jpg')cv2.imwrite(save_path, histMatch)
这篇关于图像处理:基于直方图矫正的图像色彩均衡的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!