直方图均衡化matlab但是不要使用histeq,自己编写循环计算
时间: 2024-10-14 09:09:31 浏览: 23
直方图均衡化是一种常见的图像增强技术,其目的是改善图像对比度,使其细节更容易识别。在MATLAB中,可以手动编写循环来实现直方图均衡化,避免直接使用`histeq`函数。这里是一个基本的步骤:
1. **读取图像并计算直方图**:
```matlab
img = imread('your_image.jpg'); % 替换为你要处理的图片路径
height = size(img, 1);
width = size(img, 2);
num_channels = size(img, 3);
% 如果是三通道图像,计算每个通道的直方图
if num_channels == 3
histSize = 256; % 直方图大小
channelHistograms = zeros(histSize, 3);
else
histSize = 256;
channelHistograms = zeros(histSize, 1);
end
for y = 1:height
for x = 1:width
channelValues = img(y, x, :); % 获取单个像素或通道值
% 更新每个通道的直方图
if num_channels == 3
channelHistograms(:, 1) = channelHistograms(:, 1) + histcounts(channelValues(1), 1:histSize);
channelHistograms(:, 2) = channelHistograms(:, 2) + histcounts(channelValues(2), 1:histSize);
channelHistograms(:, 3) = channelHistograms(:, 3) + histcounts(channelValues(3), 1:histSize);
else
channelHistograms(:, 1) = channelHistograms(:, 1) + histcounts(channelValues, 1:histSize);
end
end
end
```
2. **计算累计分布函数(CDF)**:
```matlab
cumulativeDist = cumsum(channelHistograms, 1);
```
3. **计算等概率分布**:
```matlab
equiDist = linspace(1, histSize, histSize);
```
4. **归一化像素**:
```matlab
equiImage = zeros(height, width, num_channels);
for y = 1:height
for x = 1:width
for c = 1:num_channels
if num_channels == 3
pixelValue = img(y, x, c);
eqPixelValue = interp1(equiDist(c), cumulativeDist(c), pixelValue, 'linear', 'extrap');
else
eqPixelValue = interp1(equiDist, cumulativeDist, img(y, x), 'linear', 'extrap');
end
equiImage(y, x, c) = round(eqPixelValue);
end
end
end
```
现在,`equiImage`就是经过了手工直方图均衡化的图像。
阅读全文