互信息

互信息

在做医学图像分割时需要用到互信息来计算两幅图像的相似度。之前写好了函数,在此备份。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
float MI_hhl(float ***Img1, float ***Img2, int Image_X_Size, int Image_Y_Size, int Image_Z_Size)
{
//绘制直方图
int Hist_Img1[256], Hist_Img2[256];
for (int t = 0; t < 256; t++)
{
Hist_Img1[t] = 0;
Hist_Img2[t] = 0;
}
for (int k = 0; k < Image_Z_Size; k++)
{
for (int i = 0; i < Image_X_Size; i++)
{
for (int j = 0; j<Image_Y_Size; j++)
{
Hist_Img1[(int)Img1[k][i][j]]++;
Hist_Img2[(int)Img2[k][i][j]]++;
}
}
}
//绘制两个图像的联合直方图
int Hist[256][256];
for (int i = 0; i < 256; i++)
{
for (int j = 0; j < 256; j++)
{
Hist[i][j] = 0;
}
}
for (int k = 0; k < Image_Z_Size; k++)
{
for (int i = 0; i < Image_X_Size; i++)
{
for (int j = 0; j<Image_Y_Size; j++)
{
Hist[(int)Img1[k][i][j]][(int)Img2[k][i][j]]++;
}
}
}

//计算单个概率
float P_Img1[256], P_Img2[256];
float all_number;
all_number = Image_X_Size * Image_Y_Size * Image_Z_Size;
for (int t = 0; t < 256; t++)
{
P_Img1[t] = (float)Hist_Img1[t] / all_number;
P_Img2[t] = (float)Hist_Img2[t] / all_number;
}

//计算联合概率
float P_Hist[256][256];
for (int i = 0; i < 256; i++)
{
for (int j = 0; j < 256; j++)
{
P_Hist[i][j] = (float)Hist[i][j] / all_number;
}
}

//计算两个图像的互信息
float Mut_INF = 0;
for (int i = 0; i < 256; i++)
{
for (int j = 0; j < 256; j++)
{
if (P_Hist[i][j] == 0 || P_Img1[i] == 0 || P_Img2[j] == 0)
{
continue;
}
Mut_INF += P_Hist[i][j] * log10(P_Hist[i][j] / (P_Img1[i] * P_Img2[j]));
}
}

return Mut_INF;
}