Calcule la entropía de la información, la información mutua promedio y la entropía relativa de dos imágenes A y B

Programa para calcular la entropía de la información, la información mutua promedio y la entropía relativa de dos imágenes A y B (dos tipos)

Consejos de programación: el entorno se selecciona automáticamente, las imágenes A y B se seleccionan automáticamente y la distribución de probabilidad se calcula de acuerdo con el histograma gris

1. Calcular la entropía de la información de dos imágenes A y B

d535d935e1304bf596910764e6c28dd1.png

import cv2
import numpy as np

img1 = cv2.imread("E:/1/1.png", cv2.IMREAD_GRAYSCALE)   #路径不可有中文
img2 = cv2.imread("E:/1/2.png", cv2.IMREAD_GRAYSCALE)
x = img1.reshape(1, -1)  #改变img1维数为1行
y = img2.reshape(1, -1)
size1 = x.shape[-1]   #读取X最后一维的长度
size2 = y.shape[-1]
#x为待统计的数组,统计的区间个数为256,(0, 255)是一个长度为2的元组,表示统计范围的最小值和最大值
#返回值为一个256个区间的直方图,每一条分别计数
px = np.histogram(x, 256, (0, 255))[0] / size1  #[0]:histogram返回两个参数取第一个
py = np.histogram(y, 256, (0, 255))[0] / size2
hx = - np.sum(px * np.log(px + 1e-8))
hy = - np.sum(py * np.log(py + 1e-8))

print(hx)
print(hy)

2. Calcule la información mutua promedio de dos imágenes A y B

44946adbccc94dfda17415e721a17d29.png 

import cv2
import numpy as np

def hxx(x, y):
    size = x.shape[-1]
    px = np.histogram(x, 256, (0, 255))[0] / size
    py = np.histogram(y, 256, (0, 255))[0] / size
    hx = - np.sum(px * np.log(px + 1e-8))
    hy = - np.sum(py * np.log(py + 1e-8))
    hxy = np.histogram2d(x, y, 256, [[0, 255], [0, 255]])[0]
    hxy /= (1.0 * size)
    hxy = - np.sum(hxy * np.log(hxy + 1e-8))
    r = hx + hy - hxy
    return r

img1 = cv2.imread("E:/1/1.png", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("E:/1/1.png", cv2.IMREAD_GRAYSCALE)
x = np.reshape(img1, -1)
y = np.reshape(img2, -1)
print(hxx(x, y))

3. Calcular la entropía relativa de dos imágenes A y B

b70efb1660d84f2686b7f3d6e9ec1613.png

import numpy as np
import scipy.stats
import cv2

img1 = cv2.imread("E:/1/1.png", cv2.IMREAD_GRAYSCALE)   #路径不可有中文
img2 = cv2.imread("E:/1/2.png", cv2.IMREAD_GRAYSCALE)
x = img1.reshape(1, -1)  #改变img1维数为1行
y = img2.reshape(1, -1)
size1 = x.shape[-1]   #读取X最后一维的长度
size2 = y.shape[-1]
#x为待统计的数组,统计的区间个数为256,(0, 255)是一个长度为2的元组,表示统计范围的最小值和最大值
#返回值为一个256个区间的直方图,每一条分别计数,最终得到一个概率分布直方图
px = np.histogram(x, 256, (0, 255))[0] / size1  #[0]:histogram返回两个参数取第一个
py = np.histogram(y, 256, (0, 255))[0] / size2

#图A相对于图B的相对熵
KL = 0.0
for i in range(256):
    KL += px[i] * np.log((px[i] +1e-8)/ (py[i]+1e-8))
print(KL)

#图B相对于图A的相对熵
KL = 0.0
for i in range(256):
    KL += py[i] * np.log((py[i] +1e-8)/ (px[i]+1e-8))
print(KL)

 

 

Supongo que te gusta

Origin blog.csdn.net/sinat_56310865/article/details/126265691
Recomendado
Clasificación