37,719
社区成员
发帖
与我相关
我的任务
分享
from PIL import Image
im = Image.open('maize.jpg')
im = im.convert('L')
width, height = im.size
# img_pix;图像像素数
img_pix=width*height
pix = im.load()
#直方图hist
hist=im.histogram()
#img_gray;图像灰度和
img_gray=0;
for i in range(256):
img_gray +=i*hist[i];
# img_avg_gray;图像平均灰度
img_avg_gray=img_gray/img_pix;
front_pix=0;# front_pix;前景像素数
front_sum_gray=0;# front_sum_gray;前景灰度和
temp=0;
Th=0;
for t in range(256):
front_pix +=hist[t];
front_pix_per=front_pix/img_pix;# front_pix_per;前景像素占比
bg_pix=img_pix-front_pix;# bg_pix;背景像素数
bg_pix_per=bg_pix/img_pix;# bg_pix_per;背景像素占比
if front_pix == 0:
continue;
if bg_pix==0:
break;
front_sum_gray +=hist[t]*t;
front_avg_gray=front_sum_gray/front_pix;# front_ave_gray;前景像素平均灰度
bg_sum_gray=img_gray-front_sum_gray;# bg_sum_gray;背景像素灰度和
bg_avg_gray = bg_sum_gray/bg_pix;# bg_avg_gray;背景像素平均灰度
g=front_pix_per*bg_pix_per*(front_avg_gray-bg_avg_gray)*(front_avg_gray-bg_avg_gray)
# g;类间方差
# g = front_pix_per * (front_avg_gray - img_avg_gray)*(front_avg_gray - img_avg_gray)+
# bg_pix_per* (bg_avg_gray - img_avg_gray)*(bg_avg_gray - img_avg_gray)
if g >=temp:
temp = g;
Th = t;
for w in range(width):
for h in range(height):
if pix[w,h]>Th:
pix[w,h]=255;
if pix[w,h]<=Th:
pix[w,h]=0;
im.show();