一、对比度检测
对比度通俗地讲就是亮暗的拉伸对比程度,指的是一幅图像中明暗区域最亮的白和最暗的黑之间不同亮度层级的测量,差异范围越大代表对比越大,差异范围越小代表对比越小。
对比度通常表现了图像画质的清晰程度。通过如下方法可以计算对比度
def calc_contrast(img):
'''
计算对比度
'''
img1 = np.array(img.convert('L'))
m, n = img1.shape
# 图片矩阵向外扩展一个像素
img1_ext = cv.copyMakeBorder(img1, 1,1,1,1, cv.BORDER_REPLICATE)
rows_ext, cols_ext = img1_ext.shape
b = 0.0
for i in range(1, rows_ext-1):
for j in range(1, cols_ext-1):
b += ((img1_ext[i,j]-img1_ext[i,j+1])**2 +
(img1_ext[i,j]-img1_ext[i,j-1])**2 +
(img1_ext[i,j]-img1_ext[i+1,j])**2 +
(img1_ext[i,j]-img1_ext[i-1,j])**2
)
cg = b/(4*(m-2)*(n-2)+3*(2*(m-2)+2*(n-2))+2*4)
return cg
二、对比度增强
1、直方图均衡化
直方图均衡化处理的“中心思想”是把原始图像的灰度直方图从比较集中的某个灰度区间变成在全部灰度范围内的均匀分布。
def image_histeq(pil_im):
'''
直方图均衡化
INPUT -> 单张图文件
OUTPUT -> 处理后的图文件
'''
# 计算图像的直方图
image_arr = image_to_array(pil_im)
imhist, bins = np.histogram(image_arr.flatten(), 256, normed=True)
cdf = imhist.cumsum() # 累计分布函数
cdf = 255*cdf/cdf[-1] # 归一化
# 使用累计分布函数的线性插值计算新的像素值
image_arr2 = np.interp(image_arr.flatten(), bins[:-1], cdf)
return array_to_image(image_arr2.reshape(image_arr.shape))
2、自适应直方图均衡化
自适应直方图均衡化(AHE)用来提升图像的对比度的一种计算机图像处理技术。和普通的直方图均衡算法不同,AHE算法通过计算图像的局部直方图,然后重新分布亮度来改变图像对比度。因此,该算法更适合于改进图像的局部对比度以及获得更多的图像细节。
#-*- coding:utf-8 -*-
import cv2 as cv
import numpy as np
import math
from PIL import Image
import matplotlib.pyplot as plt
def array_to_image(image_arr):
'''
数组还原为图片
INPUT -> 数组
OUTPUT -> 单张图文件
'''
if len(image_arr.shape) == 3: # 格式为(height(rows), weight(colums), 3)
r = Image.fromarray(np.uint8(image_arr[:,:,0]))
g = Image.fromarray(np.uint8(image_arr[:,:,1]))
b = Image.fromarray(np.uint8(image_arr[:,:,2]))
image = Image.merge("RGB", (r, g, b))
return image
elif len(image_arr.shape) == 2: # 格式为(height(rows), weight(colums))
return Image.fromarray(np.uint8(image_arr))
img_arr = np.array(Image.open('tools/33.jpg').convert('L'))
# 标准化
mri_max = np.amax(img_arr)
mri_min = np.amin(img_arr)
mri_img = ((img_arr-mri_min)/(img_arr-mri_min))*255
mri_img = img_arr.astype('uint8')
clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
img = clahe.apply(mri_img)
# 可视化
plt.imshow(array_to_image(img))
plt.show()
网友评论