20170619图像处理start

from PIL import Image
#读取图像,并用 .convert('L')将图像转换为灰度图像
pil_im = Image.open('zqlj.jpg').convert('L')
pil_im

import os
for infile in filelist:
    outfile = os.path.splitext(infile)[0]+".jpg"
    if infile != outfile:
        try:
            Image.open(infile).save(outfile)
        except IOError:
            print "cannot convert",infile
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

 in ()
      1 import os
----> 2 for infile in filelist:
      3     outfile = os.path.splitext(infile)[0]+".jpg"
      4     if infile != outfile:
      5         try:


NameError: name 'filelist' is not defined
def get_imlist(path):
    """ 返回目录中所有 JPG 图像的文件名列表 """
    """文件路径不能出现中文"""
    return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')]
get_imlist('e:')
['e:zqlj.jpg']
pil_im.thumbnail((128,128))
pil_im

这里写图片描述

pil_im = Image.open('zqlj.jpg')
pil_im

box = (100,100,400,400)
region = pil_im.crop(box)
region = region.transpose(Image.ROTATE_180)
pil_im.paste(region,box)
pil_im

out = pil_im.rotate(45)
out

from PIL import Image
from pylab import *

# 读取图像到数组中
im = array(Image.open('zqlj.jpg'))

#绘制图像
imshow(im)

#一些点
x = [100,100,400,400]
y = [200,500,200,500]

#使用红色星状标记绘制点
plot(x,y,'r*')

#绘制连接前两个点的线
plot(x[:2],y[:2])

#添加标题,显示绘制的图像
title('Plotting: "zqlj.jpg')
#使坐标轴不显示
axis('off')
show()

20170619图像处理start_第1张图片

from PIL import Image
from pylab import *

#读取图像到数组中
im = array(Image.open('zqlj.jpg').convert('L'))

#新建一个图像
figure()
#不使用颜色信息
gray()
#在原点的左上角显示轮廓图像
contour(im,origin='image')
axis('equal')
axis('off')
(0.5, 1279.5, 0.5, 852.5)
#绘制灰度直方图
figure()
hist(im.flatten(),128)
show()

20170619图像处理start_第2张图片

20170619图像处理start_第3张图片

#交互式标注
from PIL import Image
from pylab import *

im = array(Image.open('zqlj.jpg'))
imshow(im)
print 'Please click 3 points'
x = ginput(3)
print 'you clicked:',x
show()
Please click 3 points


F:\anaconda\lib\site-packages\matplotlib\figure.py:402: UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure
  "matplotlib is currently using a non-GUI backend, "



---------------------------------------------------------------------------

NotImplementedError                       Traceback (most recent call last)

 in ()
      6 imshow(im)
      7 print 'Please click 3 points'
----> 8 x = ginput(3)
      9 print 'you clicked:',x
     10 show()


F:\anaconda\lib\site-packages\matplotlib\pyplot.pyc in ginput(*args, **kwargs)
    710     If *timeout* is negative, does not timeout.
    711     """
--> 712     return gcf().ginput(*args, **kwargs)
    713 
    714 


F:\anaconda\lib\site-packages\matplotlib\figure.pyc in ginput(self, n, timeout, show_clicks, mouse_add, mouse_pop, mouse_stop)
   1667                                                   mouse_stop=mouse_stop)
   1668         return blocking_mouse_input(n=n, timeout=timeout,
-> 1669                                     show_clicks=show_clicks)
   1670 
   1671     def waitforbuttonpress(self, timeout=-1):


F:\anaconda\lib\site-packages\matplotlib\blocking_input.pyc in __call__(self, n, timeout, show_clicks)
    292         self.clicks = []
    293         self.marks = []
--> 294         BlockingInput.__call__(self, n=n, timeout=timeout)
    295 
    296         return self.clicks


F:\anaconda\lib\site-packages\matplotlib\blocking_input.pyc in __call__(self, n, timeout)
    115         try:
    116             # Start event loop
--> 117             self.fig.canvas.start_event_loop(timeout=timeout)
    118         finally:  # Run even on exception like ctrl-c
    119             # Disconnect the callbacks


F:\anaconda\lib\site-packages\matplotlib\backend_bases.pyc in start_event_loop(self, timeout)
   2412         This is implemented only for backends with GUIs.
   2413         """
-> 2414         raise NotImplementedError
   2415 
   2416     def stop_event_loop(self):


NotImplementedError: 
from PIL import Image
from numpy import *

im = array(Image.open('zqlj.jpg').convert('L'))

im2 = 255 - im #对图像进行反相处理

im3 = (100.0/255) * im +100 #将图像像素值变换到100...200区间

im4 = (255.0) * (im / 255.0)**2 #对图像像素值求平方后的图像

print int(im.min()),int(im.max())
figure()
imshow(im2)
figure()
imshow(im3)
figure()
imshow(im4)
show()
0 255

20170619图像处理start_第4张图片

20170619图像处理start_第5张图片

20170619图像处理start_第6张图片

pil_im3 = Image.fromarray(uint8(im3))
pil_im3

20170619图像处理start_第7张图片

def imresize(im,sz):
    """使用PIL对象重新定义图像数组的大小"""
    pil_im = Image.fromarray(uint8(im))

    return array(pil_im.resize(sz))
def isteq(im,nbr_bins=256):
    '''对一幅灰度图像进行直方图均衡化'''

    #计算图像的直方图
    imhist,bins = histogram(im.flatten(),nbr_bins,normed=True)
    cdf = imhist.cumsum() # cumulative distribution function
    cdf = 255*cdf / cdf[-1] #归一化

    #使用累积分布函数的线性插值,计算新的像素值
    im2 =interp(im.flatten(),bins[:-1],cdf)

    return im2.reshape(im.shape),cdf
#图像平均
def compute_average(imlist):
    '''计算图像列表的平均图像'''

    #打开第一幅图像,将其存储在浮点型数组中
    averageim = array(Image.open(imlist[0]),'f')

    for imname in imlist[1:]:
        try:
            averageim += array(Image.open(imname))
        except:
            print imname + '...skipped'
    averageim /= len(imlist)

    # 返回uint8类型的平均图像
    return array(averageim,'uint8')

你可能感兴趣的:(python图像处理)