matlab CLAHE代码
时间: 2023-07-10 15:32:47 浏览: 158
clahe matlab代码
5星 · 资源好评率100%
下面是一个基于Matlab的CLAHE(对比度受限的自适应直方图均衡化)代码示例:
```matlab
function output = clahe(input, clipLimit, tileSize)
% CLAHE (Contrast Limited Adaptive Histogram Equalization)
% input: 输入图像
% clipLimit: 对比度限制因子
% tileSize: 均衡化时划分的块大小
% output: 均衡化后的输出图像
% 处理输入参数
if nargin < 2
clipLimit = 0.01;
end
if nargin < 3
tileSize = [8 8];
end
% 将输入图像转换为灰度图像
if size(input, 3) == 3
input = rgb2gray(input);
end
% 计算图像的行数和列数
[height, width] = size(input);
% 计算每个块的大小
numTilesX = ceil(width / tileSize(2));
numTilesY = ceil(height / tileSize(1));
tileWidth = floor(width / numTilesX);
tileHeight = floor(height / numTilesY);
% 计算每个块的直方图
histograms = zeros(256, numTilesX * numTilesY);
for i = 1:numTilesY
for j = 1:numTilesX
x = (j - 1) * tileWidth + 1;
y = (i - 1) * tileHeight + 1;
tile = input(y:min(y+tileHeight-1, height), x:min(x+tileWidth-1, width));
tileHist = imhist(tile);
histograms(:, (i-1)*numTilesX+j) = tileHist;
end
end
% 计算裁剪限制
clipLimit = round(clipLimit * tileWidth * tileHeight);
% 对每个块进行均衡化
output = zeros(height, width);
for i = 1:numTilesY
for j = 1:numTilesX
x = (j - 1) * tileWidth + 1;
y = (i - 1) * tileHeight + 1;
tile = input(y:min(y+tileHeight-1, height), x:min(x+tileWidth-1, width));
tileHist = histograms(:, (i-1)*numTilesX+j);
tileHist(tileHist > clipLimit) = clipLimit;
tileHist = tileHist / sum(tileHist);
tileHist = cumsum(tileHist);
tileHist = round(tileHist * 255);
tileHist = max(tileHist, 1);
tileEq = tileHist(double(tile) + 1);
output(y:min(y+tileHeight-1, height), x:min(x+tileWidth-1, width)) = tileEq;
end
end
% 将输出图像转换为uint8格式
output = uint8(output);
end
```
这个函数实现了CLAHE算法,它将输入图像分成多个小块,对每个小块进行直方图均衡化,然后将块重新组合成输出图像。CLAHE算法还引入了对比度限制因子,用于控制块内像素的对比度,避免过度增强噪声。
阅读全文