1. 计算图像的自信息和信息熵,需包含下述步骤:<br> (1) 读入一幅图像<br> (2) 计算图中每个灰度级的频数、频率<br> (3) 从频率出发计算该图像的自信息、信息熵<br> (4) 可视化显示原图、灰度级频数、自信息和信息熵<br> 2. 计算两只骰子点数组合(随机事件)的熵,需包含下述步骤:<br> (1) 用列表类型保存一只骰子(色子)的可能结果;<br> (2) 表示并保存两只骰子的可能点数组合;提示(不强求):可以使用itertools.product()函数产生两个列表的笛卡尔积。<br> (3) 将两只骰子的点数之和作为随机事件,例如两只骰子分别取点1和点2,与分别取点2和点1视为同一种组合,计算出每种组合的数量(频数),存入一个列表结构。<br> (4) 由每种组合的频数,计算该组合的频率(概率)。<br> (5) 计算两只骰子点数和的概率分布的熵。<br>
时间: 2023-12-14 17:36:55 浏览: 107
1. 计算图像的自信息和信息熵
```python
import numpy as np
import matplotlib.pyplot as plt
# 读取图像并转为灰度图
img = np.array(plt.imread('image.jpg'))[:,:,0]
# 计算灰度级频数和频率
hist, _ = np.histogram(img, bins=256, range=(0, 255))
freq = hist / float(img.size)
# 计算自信息和信息熵
self_info = -np.log2(freq)
entropy = np.sum(-freq * np.log2(freq))
# 可视化显示
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 10))
axes[0, 0].imshow(img, cmap='gray')
axes[0, 0].set_title('Original Image')
axes[0, 1].bar(range(256), hist)
axes[0, 1].set_title('Gray Level Histogram')
axes[1, 0].plot(range(256), self_info)
axes[1, 0].set_title('Self Information')
axes[1, 1].text(0.5, 0.5, 'Entropy: {:.2f}'.format(entropy), fontsize=20, ha='center')
axes[1, 1].axis('off')
plt.show()
```
2. 计算两只骰子点数组合(随机事件)的熵
```python
import itertools
# 用列表类型保存一只骰子(色子)的可能结果
dice = list(range(1, 7))
# 表示并保存两只骰子的可能点数组合
combinations = list(itertools.product(dice, dice))
# 将两只骰子的点数之和作为随机事件,并计算每种组合的频数
freqs = np.zeros(11)
for c in combinations:
freqs[sum(c)-2] += 1
# 计算每种组合的频率(概率)
probs = freqs / float(len(combinations))
# 计算熵
entropy = -np.sum(probs * np.log2(probs))
print('Entropy: {:.2f}'.format(entropy))
```
阅读全文
相关推荐
















