基于信息熵定义的场景复杂度应用小程序
输入图像:
代码:
import os
import math
import numpy as np
from PIL import Image
def PeopleNum():
img =Image.open('d:/python_project/1.jpg')
#divided it into four part
w,h= img.size
width=w/2
height=h/2
p1 = np.array(img.crop((0, 0, width, height)).convert('L'),'f').flatten()
p2 = np.array(img.crop((width, 0, 2*width, height)).convert('L'),'f').flatten()
p3 = np.array(img.crop((0, height, width, 2*height)).convert('L'),'f').flatten()
p4 = np.array(img.crop((width, height, 2*width, 2*height)).convert('L'),'f').flatten()
#compute complexity(three methods )
#method one
e1=calc_ent(p1)
e2=calc_ent(p2)
e3=calc_ent(p3)
e4=calc_ent(p4)
#output number of people
# print e1,e2,e3,e4
e=np.array([e1,e2,e3,e4])
print e[0],e[1],e[2]
p=maxnum(e)
return p
def maxnum(e):
n=e.mean()
p=0
if (e[0]>n):
p=p+1
if (e[1]>n):
p=p+1
if (e[2]>n):
p=p+1
if (e[3]>n):
p=p+1
return p
def calc_ent(x):
x_value_list = set([x[i] for i in range(x.shape[0])])
ent = 0.0
for x_value in x_value_list:
p = float(x[x == x_value].shape[0]) / x.shape[0]
logp = np.log2(p)
ent -= p * logp
return ent
a=PeopleNum()
print (a)
输出:
分析:
经过多张图片验证,这种方法不准确。有待改进。