不善言辞,就不写关于信息熵的概念了,直接写方法:
说白了,算法的核心思想是最大化下列公式:
其中H0(q)和H1(q)定义如下:
p(i)是指灰度值为 i 的像素点在整个图片中所占的比重,p0(q)是指小于阈值的像素点在整个图片中所占的比重,p1(q)是指大于阈值的像素点在整个图片中所占的比重,然后我们要最大化上述公式,下面是该算法的python代码:
import numpy as np
from PIL import Image
import cv2
def loadImage():
im=Image.open("lena.png")
im=im.convert('L')
print(np.size(im))
data=im.getdata()
data=np.array(data)
data=np.reshape(data,(512,512))
return data
def max_entropy(image):
def calcu_entropy(hist,threshold):
sum_pixels=image.shape[0]*image.shape[1]
temp_hist=hist/sum_pixels;
sum1=0.
sum2=0.
for i in range(256):
if i<threshold:
sum1+=temp_hist[i]
else:
sum2+=temp_hist[i]
entropy1=0.
entropy2=0.
if (sum1==0)|(sum2==0):
return 0
for i in range(256):
if i<=threshold:
if temp_hist[i]!=0:
entropy1-=(temp_hist[i]/sum1)*np.log2(temp_hist[i]/sum1)
else:
if temp_hist[i]!=0:
entropy2-=(temp_hist[i]/sum2)*np.log2(temp_hist[i]/sum2)
entropy=entropy1+entropy2
return entropy
def max_Entropy(image):
max_ent=0.
max_index=0
hist=cv2.calcHist(image,[0],None,[256],[0,255])#计算灰度直方图 返回一维数组
for i in range(256):
entropy=calcu_entropy(hist,i)
if entropy>max_ent:
max_ent=entropy
max_index=i
ret,th=cv2.threshold(image,max_index,255,cv2.THRESH_BINARY)
print(th)
return th
img=max_Entropy(image)
return img
image=cv2.imread("lena.png")
image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)#图像灰度化
image=max_entropy(image)
cv2.imshow("image",image)
cv2.waitKey(0)