histogram = imhist(gray_img);的完整函数
时间: 2024-05-27 16:11:47 浏览: 14
function [histogram] = imhist(gray_img)
% This function calculates the histogram of a gray-scale image
% Get the size of the image
[m,n] = size(gray_img);
% Initialize the histogram vector
histogram = zeros(256,1);
% Calculate the histogram
for i = 1:m
for j = 1:n
% Get the value of the pixel
pixel_value = gray_img(i,j);
% Increment the corresponding bin in the histogram
histogram(pixel_value+1) = histogram(pixel_value+1) + 1;
end
end
end
相关问题
不用均衡化函数实现matlab直方图均衡化
以下是一个不使用Matlab内置的直方图均衡化函数的实现代码:
```matlab
% 读入图像
img = imread('lena.jpg');
% 将图像转换为灰度图
gray_img = rgb2gray(img);
% 计算图像直方图
histogram = imhist(gray_img);
% 计算灰度级数量
num_pixels = numel(gray_img);
% 计算概率密度函数
pdf = histogram / num_pixels;
% 计算累计分布函数
cdf = cumsum(pdf);
% 将CDF映射到新的灰度级范围
new_gray_levels = round(cdf * 255);
% 对图像进行直方图均衡化
eq_img = uint8(new_gray_levels(gray_img + 1));
% 显示原始图像和直方图均衡化后的图像
subplot(1,2,1), imshow(gray_img), title('原始图像');
subplot(1,2,2), imshow(eq_img), title('直方图均衡化后的图像');
```
该代码首先读入图像并将其转换为灰度图像。然后计算灰度级数量和图像的直方图。根据直方图计算概率密度函数和累计分布函数,将累计分布函数映射到新的灰度级范围,并对图像进行直方图均衡化。最后,使用Matlab的subplot函数将原始图像和直方图均衡化后的图像显示在同一窗口中。
对图像进行哈夫曼编码matlab
哈夫曼编码是一种无损压缩算法,可以对图像进行压缩。在 Matlab 中,可以使用 `huffmandict` 和 `huffmanenco` 函数来进行哈夫曼编码。
首先,使用 `imread` 函数读取图像,并将图像转换为灰度图像:
```
img = imread('image.jpg');
gray_img = rgb2gray(img);
```
然后,使用 `imhist` 函数计算灰度图像的直方图,以及每个灰度级出现的概率:
```
histogram = imhist(gray_img);
prob = histogram / sum(histogram);
```
接下来,使用 `huffmandict` 函数生成哈夫曼编码字典:
```
dict = huffmandict([0:255], prob);
```
其中,`[0:255]` 表示灰度级的取值范围。
最后,使用 `huffmanenco` 函数对图像进行编码:
```
encoded = huffmanenco(gray_img(:), dict);
```
其中,`gray_img(:)` 表示将灰度图像展开为一维向量。
完整的代码如下:
```
img = imread('image.jpg');
gray_img = rgb2gray(img);
histogram = imhist(gray_img);
prob = histogram / sum(histogram);
dict = huffmandict([0:255], prob);
encoded = huffmanenco(gray_img(:), dict);
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)