计算图像的自信息和信息熵,需包含下述步骤:<br> (1) 读入一幅图像<br> (2) 计算图中每个灰度级的频数、频率<br> (3) 从频率出发计算该图像的自信息、信息熵<br> (4) 可视化显示原图、灰度级频数、自信息和信息熵<br>将以上要求用Python代码做出来
时间: 2023-12-14 10:37:16 浏览: 29
下面是Python代码实现:
```python
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# 读入一幅图像
img = Image.open('lena.png').convert('L')
img.show()
# 计算图中每个灰度级的频数、频率
hist, _ = np.histogram(img, bins=256, range=(0, 255))
freq = hist / np.sum(hist)
# 从频率出发计算该图像的自信息、信息熵
self_information = - np.log2(freq)
entropy = - np.sum(freq * np.log2(freq))
# 可视化显示原图、灰度级频数、自信息和信息熵
fig, axs = plt.subplots(2, 2)
axs[0, 0].imshow(img, cmap='gray')
axs[0, 0].set_title('Original Image')
axs[0, 1].plot(hist)
axs[0, 1].set_title('Histogram')
axs[1, 0].plot(self_information)
axs[1, 0].set_title('Self-Information')
axs[1, 1].text(0.5, 0.5, f'Entropy: {entropy:.2f}', ha='center', va='center', fontsize=20)
axs[1, 1].axis('off')
plt.show()
```
在运行代码之前,需要将一幅灰度图像命名为`lena.png`并与代码放在同一目录下。运行后会显示出原图、灰度级频数、自信息和信息熵四个图像。