灰度图像熵的计算

首先导入图片并将图片转换为数组格式

import numpy as np
from matplotlib import pyplot as plt
from skimage import io

img = io.imread('846f089b1733d5227094e5cc68f1ffb1_.png', as_gray=True)
img_array = np.array(img)

之后使用histogram()函数对数组进行处理,在前面一篇文章图像直方图的绘制_不可明说的吃人魔王的博客-CSDN博客定义:直方图(英语:Histogram)是一种对数据分布情况的图形表示,是一种二维统计图表,它的两个坐标分别是统计样本和该样本对应的某个属性的度量,以长条图(bar)的形式具体表现。因为直方图的长度及宽度很适合用来表现数量上的变化,所以较容易解读差异小的数值。https://blog.csdn.net/proaskwar/article/details/132165425提过,np.histogram()函数会生成两个数组,这里不需要用到bin_edges的值,因此用np.histogramp[0]将灰度对应的像素值提取至hist。通过hist计算处probability的值(即下方公式中的p(a)),最后代入公式计算即可。这里使用到一个1e-7用于减小误差等

hist = np.histogram(img_array, bins=256)[0]
probability = hist / float(img_array.size)
entropy = -np.sum(probability * np.log2(probability + 1e-7))
print("灰度图片的像素熵为:", entropy)

 彩色图像熵值计算

彩色图片熵值计算时要分别对红绿蓝(RGB)进行计算,最后求平均。因此定义一个对一种颜色进行熵值计算的函数,原理与上方基本相同:

def calculate_entropy(channel):
    hist = np.histogram(channel, bins=256)[0]
    probability = hist / float(channel.size)
    entropy = -np.sum(probability * np.log2(probability + 1e-7))
    return entropy

其中channel代表图像的RGB颜色,通过以下方式对颜色进行提取:

red_channel = img_array[:, :, 0]
green_channel = img_array[:, :, 1]
blue_channel = img_array[:, :, 2]

接下来求RGB颜色分别对应的熵值:

red_entropy = calculate_entropy(red_channel)
green_entropy = calculate_entropy(green_channel)
blue_entropy = calculate_entropy(blue_channel)

完整代码如下:

# 计算彩色图片的熵,需要分别对RGB分别进行计算,最后合并或求平均
import numpy as np
from matplotlib import pyplot as plt
from skimage import io

img = io.imread('846f089b1733d5227094e5cc68f1ffb1_.png')
img_array = np.array(img)


def calculate_entropy(channel):
    hist = np.histogram(channel, bins=256)[0]
    probability = hist / float(channel.size)
    entropy = -np.sum(probability * np.log2(probability + 1e-7))
    return entropy


red_channel = img_array[:, :, 0]
green_channel = img_array[:, :, 1]
blue_channel = img_array[:, :, 2]

red_entropy = calculate_entropy(red_channel)
green_entropy = calculate_entropy(green_channel)
blue_entropy = calculate_entropy(blue_channel)

total_entropy = (red_entropy + green_entropy + blue_entropy) / 3

print("彩色图像的像素熵:", total_entropy)

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐