图像熵的计算

本文介绍了如何使用Python和相关库如numpy和skimage计算灰度图像和彩色图像的熵值,包括灰度图像的像素熵计算以及彩色图像通过RGB通道分别计算后取平均的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

灰度图像熵的计算

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

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()函数对数组进行处理,在前面一篇文章图像直方图的绘制_不可明说的吃人魔王的博客-优快云博客定义:直方图(英语:Histogram)是一种对数据分布情况的图形表示,是一种二维统计图表,它的两个坐标分别是统计样本和该样本对应的某个属性的度量,以长条图(bar)的形式具体表现。因为直方图的长度及宽度很适合用来表现数量上的变化,所以较容易解读差异小的数值。https://blog.youkuaiyun.com/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)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值