如何计算PNG图像中红色和绿色像素的估计联合概率分布?

3 投票
2 回答
6351 浏览
提问于 2025-04-17 11:03

我有一张png格式的图片,这张图片只有红色和绿色两个颜色通道。我把蓝色通道去掉了,是为了方便计算。我需要计算这些像素的估计联合概率分布。我发现了一个函数:numpy.random.multivariate_normal(mean, cov[, size]),这个函数是用来计算已知分布的。但是我需要的是估计的分布。有没有什么建议呢?非常感谢!
Areej

2 个回答

0

使用scipy这个库,你可以把很多种分布模型应用到数据上。下面是一个例子,假设你是从一个.png或.jpg等文件中加载你的图片:

from PIL import Image
import numpy
import scipy.stats as ss

im = numpy.array(Image.open("myfile.png")
red = im[:,:,0]
green = im[:,:,1]

from matplotlib import pyplot
pyplot.hist(red.ravel())
pyplot.hist(green.ravel())

# if your data follow a normal distribution
print "red mean: %g  sigma: %g" % ss.norm.fit(red.ravel())
print "green mean: %g  sigma: %g" % ss.norm.fit(green.ravel())

如果你想用不同的分布模型,只需把上面代码中的norm替换成你想要的其他模型,具体可以参考这个链接:http://docs.scipy.org/doc/scipy/reference/stats.html

5

把数据分成一组直方图是很简单的。

#2d histogram gives you the counts, in each cell
(H,redEdges,greedEdges) = numpy.histogram2d(
    red.ravel(),green.ravel(),
    bins=nbins
)

#divide by the total to get the probability of 
#each cell -> the joint distribution
Prg = H/H.sum()

#sum over the `green` axis to get the `red` marginal (nx1)
Pr = H2d.sum(1)[:,numpy.newaxis]
#sum over the `red` axis to get the `green` marginal (1xn) 
Pg = H2d.sum(0)[numpy.newaxis,:]

接下来,计算互信息就变得简单了:

#calculate information contribution of each bin
dIrg = Prg*numpy.log(Prg/(Pr*Pg))
#filter nans and sum
Irg = dIrg[~numpy.isnan(dIrg)].mean()

撰写回答