python 图像直方图

最近要搞图像处理,要做直方图,老师用MFC弄了一大坨代码看着真心蛋疼。。。正好这一段在学python,就拿来用了,非常方便强大,核心代码就几行~

用了三个模块,PIL,numpy和matplotlib

第一行加一句这个,基本完美解决中文字体问题

#-*- coding: utf-8 -*-

 

代码:

 1 #-*- coding: utf-8 -*-
 2 import PIL.Image as Image
 3 import numpy as np
 4 import matplotlib.pyplot as pl
 5 import matplotlib.image as mpimg
 6 from matplotlib.font_manager import FontProperties
 7 import win32ui
 8 font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=12)
 9 dlg = win32ui.CreateFileDialog(1) 
10 dlg.SetOFNInitialDir('H:\desk\Py_Study\新建文件夹')
11 dlg.DoModal()
12  
13 filename = dlg.GetPathName()  
14 o_img = Image.open(filename)
15 img1 = o_img.convert('RGB')
16 a = np.asarray(img1)   #转存成RGB‘数组’
17 ax1 = pl.subplot(321)  #划分成5块
18 ax2 = pl.subplot(322) 
19 ax3 = pl.subplot(323)
20 ax4 = pl.subplot(324)
21 ax5 = pl.subplot(313)
22 
23 pl.sca(ax1)
24 pl.xlabel(u'蓝色', fontproperties = font)
25 pl.hist(a[:,:,0].flatten(),bins = 256, histtype = "step", color = 'blue')  # blue
26 pl.sca(ax2)
27 pl.xlabel(u'绿色', fontproperties = font)
28 pl.hist(a[:,:,1].flatten(),bins = 256, histtype = "step", color = 'green')  # green
29 pl.sca(ax3)
30 pl.xlabel(u'红色', fontproperties = font)
31 pl.hist(a[:,:,2].flatten(),bins = 256, histtype = "step", color = 'red')  # red
32 pl.sca(ax4)
33 pl.xlabel(u'灰度', fontproperties = font)
34 pl.hist(a[:,:,2].flatten() * 0.299 + a[:,:,1].flatten() * 0.587 + a[:,:,0].flatten() * 0.114 ,bins=256, histtype="step", color = 'gray')
35 pl.sca(ax5)
36 pl.imshow(o_img)
37 pl.show() 

效果:

posted @ 2013-05-31 23:52  XDruid  阅读(1236)  评论(0编辑  收藏  举报