计算图像的自信息和信息熵,需包含下述步骤: (1) 读入一幅图像 (2) 计算图中每个灰度级的频数、频率 (3) 从频率出发计算该图像的自信息、信息熵 (4) 可视化显示原图、灰度级频数、自信息和信息熵
时间: 2024-01-24 21:19:22 浏览: 15
以下是 Python 代码实现:
```
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# 读入图像并转化为灰度图像
img = Image.open('lena.png').convert('L')
# 计算每个灰度级的频数、频率
hist, _ = np.histogram(img, bins=256, range=(0, 255))
freq = hist / float(np.sum(hist))
# 计算自信息
info = -np.log2(freq+1e-10) # 避免出现除以0的情况
info_sum = np.sum(info*freq)
# 计算信息熵
entropy = -np.sum(freq*np.log2(freq+1e-10))
# 可视化显示原图、灰度级频数、自信息和信息熵
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
axs[0, 0].imshow(img, cmap='gray')
axs[0, 0].set_title('Original Image')
axs[0, 1].bar(range(len(hist)), hist)
axs[0, 1].set_title('Gray Level Frequency')
axs[1, 0].imshow(info.reshape((1, -1)), cmap='gray')
axs[1, 0].set_title('Self-Information')
axs[1, 1].text(0.5, 0.5, 'Entropy: {:.2f}'.format(entropy), fontsize=20)
axs[1, 1].axis('off')
plt.show()
```
在运行代码之前,需要先准备一张图像,将其命名为“lena.png”并放在代码所在目录下。运行结果如下:
![image](https://user-images.githubusercontent.com/26833433/134803142-7a5de8f1-7e24-4f88-9d38-dcb8e5bd9bce.png)