当前位置:首页 » 编程语言 » pillowpython27

pillowpython27

发布时间: 2023-07-19 16:49:37

① 如何在Windows下安装配置python接口的caffe

整了一晚上加一上午。网上关于python的记录较少,这里写一下。
这里的环境是WIN10+cuda v7.5 +cudnn v4 + opencv + pycharm+VS2013
使用的是GPU,我的GPU是titan16G+内存32G
首先是caffe的文件以及第三方库的编译,这里提供一个已经编译好的的连接,我就是从那里下好然后编译完毕的。
点击打开链接 happynear的
然后就是如何编译python接口。
1、首先先生成两个python文件,在src/caffe/proto/extract_proto.bat 里生成caffe_pb2.py 这个之后有用。
2、然后打开已经给好的caffe/buildVS2013,打开里面已经有的工程文件,正常的情况下应该是有7个工程,选中pycaffee单独作为要编译的项目。如图所示:

把pycaffe作为单启动。注意需要在release x64位下编译。
如果没有这个的话,就将这个文件夹里python文件夹中的项目加入即可。如果没有python项目,就自己建一个,将python文件夹里的cpp文件加入就可以了。
3、选择pycaffe的属性,将配置属性下的VC++目录中的包含目录和库目录填上你python所在的include和libs 再在C/C++的目录下的附加包含目录一项中添加
以我的python为例。D:/python27/Lib;D:/python/include/ 以及D:/Python27/Lib/site-packages/numpy/core/include 如果你安装了CUDNN这里可以在预处理器那里把USE_CUDNN加上,同时在LINKER的输入目录下的附加依赖库中加入cudnn的lib文件。

3、开始编译即可。这里要注意一定要和caffe、caffelib在一个项目里编译,否则会报错。
4、编译成功后会在caffe/python/caffe下生成_caffe.pyd 是打不开的
5、配置python环境:需要几个额外库
Cython>=0.19.2
numpy>=1.7.1
scipy>=0.13.2
scikit-image>=0.9.3
matplotlib>=1.3.1
ipython>=3.0.0
h5py>=2.2.0
leveldb>=0.191
networkx>=1.8.1
nose>=1.3.0
pandas>=0.12.0
python-dateutil>=1.4,<2
protobuf>=2.5.0
python-gflags>=2.0
pyyaml>=3.10
Pillow>=2.3.0
six>=1.1.0
其中numpy要装MKL版本的,不然scipy装上了BLAS不能用
leveldb没有windows版本的,不过我找到了可以使用的办法。见这个博客:
点击打开链接
如果有pip install 装不上的,可以上这个网站找 wheel文件安装就可以了
点击打开链接
6、最后把目录中python下的caffe文件夹复制到python27/Lib/site-packages就可以了。
测试的时候只需要在控制台下输入import caffe 看能载入就知道成功了:)

② ❤️【Python从入门到精通】(二十七)更进一步的了解Pillow吧!

本文是接上一篇 ❤️【Python从入门到精通】(二十六)用Python的PIL库(Pillow)处理图像真的得心应手❤️ 进一步介绍Pillow库的使用, 本文将重点介绍一些高级特性:比如如何利用Pillow画图形(圆形,正方形),介绍通过Pillow库给图片添加水印;同时对上一篇文章未介绍的常用知识点进行补充说明。希望对读者朋友们有所帮助。

上一篇文章已经介绍了Image模块,但是介绍的还不够全面,例如如何从网页中读取图片没有介绍到,如何裁剪图片都没有介绍到。

读取网页中的图片的基本实现方式是:首先利用requests库读取当前图片链接的内容,接着将内容转成二进制数据,在通过open方法将该二进制数据,最后通过save方法进行保存。

读取结果是:

通过crop方法可以从图片中裁剪出一个指定大小的区域。裁取的区域范围是 (left, upper, right, lower) 比如从某个宽高都是400的图片中裁剪一个是宽高都是100的正方形区域,只需要指定裁剪区域的坐标是: (0, 0, 100, 100)

有裁剪还有一个方法就是重新设置图片大小的方法 resize,比如将前面400 400的图片 修改成 300 200,只需要调用resize方法

通过 convert方法进行图片模式的转换

前面介绍的ImageDraw库,只是介绍了利用它来向图片写入文本,其实ImageDraw模块还有一个更有用的途径,就是可以通过它来画各种图形。

首先创建一个600*600的画布。然后再画布中画出一个正方形,画直线的方法是 line方法。
ImageDraw.line(xy, fill=None, width=0, joint=None)

在xy的坐标之间画一条直线
xy--> 在两个坐标点之间画一条直线,坐标点的传入方式是[(x, y), (x, y), ...]或者[x, y, x, y, ...]
fill--> 直线的颜色
width--> 直线的宽度

画一个边框宽度为2px,颜色为蓝色的,面积为400*400的正方形。

ImageDraw.arc(xy, start, end, fill=None, width=0)

在给定的区域范围内,从开始角到结束角之间绘制一条圆弧
xy--> 定义边界框的两个点,传入的格式是[ (x0, y0), (x1, y1)] 或者 [x0, y0, x1, y1] ,其中 x1>=x0,y1>=y0
start --> 起始角度,以度为单位,从3点钟开始顺时针增加
end--> 结束角度,以度为单位
fill--> 弧线的颜色
width-->弧线的宽度

这里就是画了一个半圆,如果结束角度是360度的话则就会画一个完整的圆。

画圆通过ImageDraw.ellipse(xy, fill=None, outline=None, width=1) 方法,该方法可以画出一个给定范围的圆

xy--> 定义边界框的两个点,传入的格式是[ (x0, y0), (x1, y1)] 或者 [x0, y0, x1, y1] ,其中 x1>=x0,y1>=y0
outline--> 轮廓的颜色
fill ---> 填充颜色
width--> 轮廓的宽度

ImageDraw.chord(xy, start, end, fill=None, outline=None, width=1) 方法用来画半圆,跟arc()方法不同的是它会用直线将起始点和结束点连接起来

xy--> 定义边界框的两个点,传入的格式是[ (x0, y0), (x1, y1)] 或者 [x0, y0, x1, y1] ,其中 x1>=x0,y1>=y0
outline--> 轮廓的颜色
fill ---> 填充颜色
width--> 轮廓的宽度

ImageDraw.pieslice(xy, start, end, fill=None, outline=None, width=1)
类似于arc()方法,不过他会在端点和圆点之间画直线
xy--> 定义边界框的两个点,传入的格式是[ (x0, y0), (x1, y1)] 或者 [x0, y0, x1, y1] ,其中 x1>=x0,y1>=y0
start --> 起始角度,以度为单位,从3点钟开始顺时针增加
end--> 结束角度,以度为单位
fill--> 弧线的颜色
width-->弧线的宽度

ImageDraw.rectangle(xy, fill=None, outline=None, width=1)
xy--> 在两个坐标点之间画一条直线,坐标点的传入方式是[(x, y), (x, y), ...]或者[x, y, x, y, ...]
outline--> 轮廓的颜色
fill--> 填充的颜色
width--> 轮廓线的宽度

ImageDraw.rounded_rectangle(xy, radius=0, fill=None, outline=None, width=1) 该方法可以画一个圆角矩形
xy--> 在两个坐标点之间画一条直线,坐标点的传入方式是[(x, y), (x, y), ...]或者[x, y, x, y, ...]
radius--> 角的半径
outline--> 轮廓的颜色
fill--> 填充的颜色
width--> 轮廓线的宽度

这里有个问题,就是画好的图形如何从Image中扣出来呢?

ImageEnhance模块主要是用于设置图片的颜色对比度亮度锐度等啥的,增强图像。

原始图像

ImageFilter模块主要用于对图像进行过滤,增强边缘,模糊处理,该模块的使用方式是 im.filter(ImageFilter) 。
其中ImageFilter按照需求传入指定的过滤值。

下面一个个试下效果

4.边缘增强

ImageGrab模块主要用于对屏幕进行截图,通过grab方法进行截取,如果不传入任何参数则表示全屏幕截图,否则是截取指定区域的图像。其中box格式是:(x1,x2,y1,y2)

利用Pillow库可以轻易的对图像增加水印
首先,用PIL的Image函数读取图片
接着,新建一张图(尺寸和原图一样)
然后,在新建的图象上用PIL的ImageDraw把字给画上去,字的颜色从原图处获取。

原图

添加文字后的效果图

本文详细介绍了Pillow库的使用,希望对读者朋友们有所帮助。

Pillow官方文档

需要获取源码的小伙伴可以关注下方的公众号,回复【python】

③ python 怎么安装pillow

1. 安装pip

[plain] view plain
sudo easy_install pip

pip 安装成功就可以直接安装pil或者pillow

2. 通过命令pip install pil

[plain] view plain
pip install Pil
Downloading/unpacking Pil
Could not find any downloads that satisfy the requirement Pil
Some externally hosted files were ignored (use --allow-external Pil to allow).
Cleaning up...
No distributions at all found for Pil
Storing debug log for failure in /Users/macbook/Library/Logs/pip.log

3. 所以就安装pillow

[plain] view plain
pip install --use-wheel Pillow
Downloading/unpacking Pillow
Downloading Pillow-2.4.0.zip (6.5MB): 5.0MB downloaded
Cleaning up...

弄了会别的回来发现还没有下载完,这叫一个慢呀,于是放弃
4. 通过Git下载源码地址https://github.com/python-imaging/Pillow

[plain] view plain
git clone https://github.com/python-imaging/Pillow.git

然后开始编译安装
4.1

[plain] view plain
python setup.py build_ext -i

编译完之后会提示运行测试例子,并且发现JPEG support not available

[plain] view plain
--------------------------------------------------------------------
version Pillow 2.4.0
platform darwin 2.7.5 (default, Aug 25 2013, 00:04:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)]
--------------------------------------------------------------------
--- TKINTER support available
*** JPEG support not available
*** OPENJPEG (JPEG2000) support not available
--- ZLIB (PNG/ZIP) support available
*** LIBTIFF support not available
--- FREETYPE2 support available
*** LITTLECMS2 support not available
*** WEBP support not available
*** WEBPMUX support not available
--------------------------------------------------------------------
To add a missing option, make sure you have the required
library, and set the corresponding ROOT variable in the
setup.py script.

To check the build, run the selftest.py script.

4.2 因为JPEG support not available,运行python selftest.py报告错误

[plain] view plain
1 tests of 57 failed.

于是只好卸载pillow

可以通过pip命令来卸载

[plain] view plain
pip uninstall pillow
sudo pip uninstall pillow
Password:
Uninstalling Pillow:
/Library/Python/2.7/site-packages/Pillow-2.4.0-py2.7-macosx-10.9-intel.egg
/usr/local/bin/pilconvert.py
/usr/local/bin/pildriver.py
/usr/local/bin/pilfile.py
/usr/local/bin/pilfont.py
/usr/local/bin/pilprint.py
Proceed (y/n)? y
Successfully uninstalled Pillow

成功之后需要安装libjpeg的支持

[plain] view plain
brew install libjpeg

安装成功之后重新编译pillow

[plain] view plain
--------------------------------------------------------------------
version Pillow 2.4.0
platform darwin 2.7.5 (default, Aug 25 2013, 00:04:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)]
--------------------------------------------------------------------
--- TKINTER support available
--- JPEG support available
*** OPENJPEG (JPEG2000) support not available
--- ZLIB (PNG/ZIP) support available
*** LIBTIFF support not available
--- FREETYPE2 support available
*** LITTLECMS2 support not available
*** WEBP support not available
*** WEBPMUX support not available
--------------------------------------------------------------------

[plain] view plain
python selftest.py

[plain] view plain
--------------------------------------------------------------------
Pillow 2.4.0 TEST SUMMARY
--------------------------------------------------------------------
Python moles loaded from /Users/macbook/yyang/app-devel-source/python/Pillow/PIL
Binary moles loaded from /Users/macbook/yyang/app-devel-source/python/Pillow/PIL
--------------------------------------------------------------------
--- PIL CORE support ok
--- TKINTER support ok
--- JPEG support ok
*** JPEG 2000 support not installed
--- ZLIB (PNG/ZIP) support ok
*** LIBTIFF support not installed
--- FREETYPE2 support ok
*** LITTLECMS2 support not installed
*** WEBP support not installed
--------------------------------------------------------------------
Running selftest:
--- 57 tests passed.

最后执行安装

[plain] view plain
sudo python setup.py install

④ python的pillow库怎么使用

Pillow是Python里的图像处理库(PIL:Python Image Library),提供了了广泛的文件格式支持,强大的图像处理能力,主要包括图像储存、图像显示、格式转换以及基本的图像处理操作等。

1)使用 Image 类
PIL最重要的类是 Image class, 你可以通过多种方法创建这个类的实例;你可以从文件加载图像,或者处理其他图像, 或者从 scratch 创建。

要从文件加载图像,可以使用open( )函数,在Image模块中:

[python]view plain

  • >>>fromPILimportImage

  • >>>im=Image.open("E:/photoshop/1.jpg")

  • 加载成功后,将返回一个Image对象,可以通过使用示例属性查看文件内容:

    [python]view plain

  • >>>print(im.format,im.size,im.mode)

  • ('JPEG',(600,351),'RGB')

  • >>>

  • format这个属性标识了图像来源。如果图像不是从文件读取它的值就是None。size属性是一个二元tuple,包含width和height(宽度和高度,单位都是px)。mode属性定义了图像bands的数量和名称,以及像素类型和深度。常见的modes 有 “L” (luminance) 表示灰度图像, “RGB” 表示真彩色图像, and “CMYK” 表示出版图像。
    如果文件打开错误,返回IOError错误。
    只要你有了 Image 类的实例,你就可以通过类的方法处理图像。比如,下列方法可以显示图像:

    [python]view plain

  • im.show()

  • 2)读写图像
    PIL 模块支持大量图片格式。使用在 Image 模块的 open() 函数从磁盘读取文件。你不需要知道文件格式就能打开它,这个库能够根据文件内容自动确定文件格式。要保存文件,使用 Image 类的 save() 方法。保存文件的时候文件名变得重要了。除非你指定格式,否则这个库将会以文件名的扩展名作为格式保存。

    加载文件,并转化为png格式:

    [python]view plain

  • "PythonImageLibraryTest"

  • fromPILimportImage

  • importos

  • importsys

  • forinfileinsys.argv[1:]:

  • f,e=os.path.splitext(infile)

  • outfile=f+".png"

  • ifinfile!=outfile:

  • try:

  • Image.open(infile).save(outfile)

  • exceptIOError:

  • print("Cannotconvert",infile)

  • save() 方法的第二个参数可以指定文件格式。
    3)创建缩略图

    缩略图是网络开发或图像软件预览常用的一种基本技术,使用Python的Pillow图像库可以很方便的建立缩略图,如下:

    [python]view plain

  • #createthumbnail

  • size=(128,128)

  • forinfileinglob.glob("E:/photoshop/*.jpg"):

  • f,ext=os.path.splitext(infile)

  • img=Image.open(infile)

  • img.thumbnail(size,Image.ANTIALIAS)

  • img.save(f+".thumbnail","JPEG")

  • 上段代码对photoshop下的jpg图像文件全部创建缩略图,并保存,glob模块是一种智能化的文件名匹配技术,在批图像处理中经常会用到。
    注意:Pillow库不会直接解码或者加载图像栅格数据。当你打开一个文件,只会读取文件头信息用来确定格式,颜色模式,大小等等,文件的剩余部分不会主动处理。这意味着打开一个图像文件的操作十分快速,跟图片大小和压缩方式无关。

    4)图像的剪切、粘贴与合并操作

    Image 类包含的方法允许你操作图像部分选区,PIL.Image.Image.crop 方法获取图像的一个子矩形选区,如:

    [python]view plain

  • #crop,pasteandmerge

  • im=Image.open("E:/photoshop/lena.jpg")

  • box=(100,100,300,300)

  • region=im.crop(box)

  • 矩形选区有一个4元元组定义,分别表示左、上、右、下的坐标。这个库以左上角为坐标原点,单位是px,所以上诉代码复制了一个 200x200 pixels 的矩形选区。这个选区现在可以被处理并且粘贴到原图。

    [python]view plain

  • region=region.transpose(Image.ROTATE_180)

  • im.paste(region,box)

  • 当你粘贴矩形选区的时候必须保证尺寸一致。此外,矩形选区不能在图像外。然而你不必保证矩形选区和原图的颜色模式一致,因为矩形选区会被自动转换颜色。

    5)分离和合并颜色通道

    对于多通道图像,有时候在处理时希望能够分别对每个通道处理,处理完成后重新合成多通道,在Pillow中,很简单,如下:

    [python]view plain

  • r,g,b=im.split()

  • im=Image.merge("RGB",(r,g,b))

  • 对于split( )函数,如果是单通道的,则返回其本身,否则,返回各个通道。
    6)几何变换

    对图像进行几何变换是一种基本处理,在Pillow中包括resize( )和rotate( ),如用法如下:

    [python]view plain

  • out=im.resize((128,128))

  • out=im.rotate(45)#degreeconter-clockwise

  • 其中,resize( )函数的参数是一个新图像大小的元祖,而rotate( )则需要输入顺时针的旋转角度。在Pillow中,对于一些常见的旋转作了专门的定义:

    [python]view plain

  • out=im.transpose(Image.FLIP_LEFT_RIGHT)

  • out=im.transpose(Image.FLIP_TOP_BOTTOM)

  • out=im.transpose(Image.ROTATE_90)

  • out=im.transpose(Image.ROTATE_180)

  • out=im.transpose(Image.ROTATE_270)

  • 7)颜色空间变换

    在处理图像时,根据需要进行颜色空间的转换,如将彩色转换为灰度:

    [python]view plain

  • cmyk=im.convert("CMYK")

  • gray=im.convert("L")

  • 8)图像滤波

    图像滤波在ImageFilter 模块中,在该模块中,预先定义了很多增强滤波器,可以通过filter( )函数使用,预定义滤波器包括:

    BLUR、CONTOUR、DETAIL、EDGE_ENHANCE、EDGE_ENHANCE_MORE、EMBOSS、FIND_EDGES、SMOOTH、SMOOTH_MORE、SHARPEN。其中BLUR就是均值滤波,CONTOUR找轮廓,FIND_EDGES边缘检测,使用该模块时,需先导入,使用方法如下:

    [python]view plain

  • fromPILimportImageFilter

  • imgF=Image.open("E:/photoshop/lena.jpg")

  • outF=imgF.filter(ImageFilter.DETAIL)

  • conF=imgF.filter(ImageFilter.CONTOUR)

  • edgeF=imgF.filter(ImageFilter.FIND_EDGES)

  • imgF.show()

  • outF.show()

  • conF.show()

  • edgeF.show()

  • 除此以外,ImageFilter模块还包括一些扩展性强的滤波器:

  • classPIL.ImageFilter.GaussianBlur(radius=2)

  • Gaussian blur filter.

    参数:

    radius– Blur radius.
  • classPIL.ImageFilter.UnsharpMask(radius=2,percent=150,threshold=3)

  • Unsharp mask filter.

    See Wikipedia’s entry ondigital unsharp maskingfor an explanation of the parameters.

  • classPIL.ImageFilter.Kernel(size,kernel,scale=None,offset=0)

  • Create a convolution kernel. The current version only supports 3x3 and 5x5 integer and floating point kernels.

    In the current version, kernels can only be applied to “L” and “RGB” images.

    参数:

  • size– Kernel size, given as (width, height). In the current version, this must be (3,3) or (5,5).

  • kernel– A sequence containing kernel weights.

  • scale– Scale factor. If given, the result for each pixel is divided by this value. the default is the sum of the kernel weights.

  • offset– Offset. If given, this value is added to the result, after it has been divided by the scale factor.

  • classPIL.ImageFilter.RankFilter(size,rank)

  • Create a rank filter. The rank filter sorts all pixels in a window of the given size, and returns therank‘th value.

    参数:

  • size– The kernel size, in pixels.

  • rank– What pixel value to pick. Use 0 for a min filter,size*size/2for a median filter,size*size-1for a max filter, etc.

  • classPIL.ImageFilter.MedianFilter(size=3)

  • Create a median filter. Picks the median pixel value in a window with the given size.

    参数:

    size– The kernel size, in pixels.
  • classPIL.ImageFilter.MinFilter(size=3)

  • Create a min filter. Picks the lowest pixel value in a window with the given size.

    参数:

    size– The kernel size, in pixels.
  • classPIL.ImageFilter.MaxFilter(size=3)

  • Create a max filter. Picks the largest pixel value in a window with the given size.

    参数:

    size– The kernel size, in pixels.
  • classPIL.ImageFilter.ModeFilter(size=3)

  • Create a mode filter. Picks the most frequent pixel value in a box with the given size. Pixel values that occur only once or twice are ignored; if no pixel value occurs more than twice, the original pixel value is preserved.

    参数:

    size– The kernel size, in pixels.

    更多详细内容可以参考:PIL/ImageFilter

  • 9)图像增强

    图像增强也是图像预处理中的一个基本技术,Pillow中的图像增强函数主要在ImageEnhance模块下,通过该模块可以调节图像的颜色、对比度和饱和度和锐化等:

    [python]view plain

  • fromPILimportImageEnhance

  • imgE=Image.open("E:/photoshop/lena.jpg")

  • imgEH=ImageEnhance.Contrast(imgE)

  • imgEH.enhance(1.3).show("30%morecontrast")

  • 图像增强:

  • classPIL.ImageEnhance.Color(image)

  • Adjust image color balance.

    This class can be used to adjust the colour balance of an image, in a manner similar to the controls on a colour TV set. An enhancement factor of 0.0 gives a black and white image. A factor of 1.0 gives the original image.

  • classPIL.ImageEnhance.Contrast(image)

  • Adjust image contrast.

    This class can be used to control the contrast of an image, similar to the contrast control on a TV set. An enhancement factor of 0.0 gives a solid grey image. A factor of 1.0 gives the original image.

  • classPIL.ImageEnhance.Brightness(image)

  • Adjust image brightness.

    This class can be used to control the brighntess of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image.

  • classPIL.ImageEnhance.Sharpness(image)

  • Adjust image sharpness.

    This class can be used to adjust the sharpness of an image. An enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image.

  • 图像增强的详细内容可以参考:PIL/ImageEnhance

    除了以上介绍的内容外,Pillow还有很多强大的功能:

    PIL.Image.alpha_composite(im1,im2)

    PIL.Image.blend(im1,im2,alpha)

    PIL.Image.composite(image1,image2,mask)
    PIL.Image.eval(image,*args)

    PIL.Image.fromarray(obj,mode=None)

    PIL.Image.frombuffer(mode,size,data,decoder_name='raw',*args)

⑤ 怎么样在Python编程中使用Pillow来处理图像

安装
刚接触Pillow的朋友先来看一下Pillow的安装方法,在这里我们以Mac OS环境为例: (1)、使用 pip 安装 Python 库。pip 是 Python 的包管理工具,安装后就可以直接在命令行一站式地安装/管理各种库了(pip 文档)。

$ wget http://pypi.python.org/packages/source/p/pip/pip-0.7.2.tar.gz$ tar xzf pip-0.7.2.tar.gz$ cd pip-0.7.2$ python setup.py install

(2)、使用 pip 下载获取 Pillow:

$ pip install pillow

(3)、安装过程中命令行出现错误提示:”error: command ‘clang' failed with exit status
1”。上网查阅,发现需要通过 Xcode 更新 Command Line Tool。于是打开
Xcode->Preferences->Downloads-Components选项卡。咦?竟然没了 Command Line
Tools。再查,发现 Xcode 5 以上现在需要用命令行安装:

$ xcode-select —install

系统会弹出安装命令行工具的提示,点击安装即可。
此时再 pip install pillow,就安装成功了。
pip freeze 命令查看已经安装的 Python 包,Pillow 已经乖乖躺那儿了。
好了,下面开始进入教程~
Image类
Pillow中最重要的类就是Image,该类存在于同名的模块中。可以通过以下几种方式实例化:从文件中读取图片,处理其他图片得到,或者直接创建一个图片。
使用Image模块中的open函数打开一张图片:

>>> from PIL import Image>>> im = Image.open("lena.ppm")

如果打开成功,返回一个Image对象,可以通过对象属性检查文件内容

>>> from __future__ import print_function>>> print(im.format, im.size, im.mode)

PPM (512, 512) RGB

format属性定义了图像的格式,如果图像不是从文件打开的,那么该属性值为None;size属性是一个tuple,表示图像的宽和高(单位为像素);mode属性为表示图像的模式,常用的模式为:L为灰度图,RGB为真彩色,CMYK为pre-press图像。
如果文件不能打开,则抛出IOError异常。
当有一个Image对象时,可以用Image类的各个方法进行处理和操作图像,例如显示图片:

>>> im.show()

ps:标准版本的show()方法不是很有效率,因为它先将图像保存为一个临时文件,然后使用xv进行显示。如果没有安装xv,该函数甚至不能工作。但是该方法非常便于debug和test。(windows中应该调用默认图片查看器打开)
读写图片
Pillow库支持相当多的图片格式。直接使用Image模块中的open()函数读取图片,而不必先处理图片的格式,Pillow库自动根据文件决定格式。
Image模块中的save()函数可以保存图片,除非你指定文件格式,那么文件名中的扩展名用来指定文件格式。
图片转成jpg格式

from __future__ import print_functionimport os, sysfrom PIL import Imagefor infile in sys.argv[1:]: f, e = os.path.splitext(infile) outfile = f + ".jpg" if infile != outfile: try: Image.open(infile).save(outfile) except IOError: print("cannot convert", infile)

save函数的第二个参数可以用来指定图片格式,如果文件名中没有给出一个标准的图像格式,那么第二个参数是必须的。
创建缩略图

from __future__ import print_functionimport os, sysfrom PIL import Imagesize = (128, 128)for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + ".thumbnail" if infile != outfile: try: im = Image.open(infile) im.thumbnail(size) im.save(outfile, "JPEG") except IOError: print("cannot create thumbnail for", infile)

必须指出的是除非必须,Pillow不会解码或raster数据。当你打开一个文件,Pillow通过文件头确定文件格式,大小,mode等数据,余下数据直到需要时才处理。
这意味着打开文件非常快,与文件大小和压缩格式无关。下面的程序用来快速确定图片属性:
确定图片属性

from __future__ import print_functionimport sysfrom PIL import Imagefor infile in sys.argv[1:]: try: with Image.open(infile) as im: print(infile, im.format, "%dx%d" % im.size, im.mode) except IOError: pass

裁剪、粘贴、与合并图片
Image类包含还多操作图片区域的方法。如crop()方法可以从图片中提取一个子矩形
从图片中复制子图像

box = im.() #直接复制图像box = (100, 100, 400, 400)region = im.crop(box)

区域由4-tuple决定,该tuple中信息为(left, upper, right, lower)。 Pillow左边系统的原点(0,0)为图片的左上角。坐标中的数字单位为像素点,所以上例中截取的图片大小为300*300像素^2。
处理子图,粘贴回原图

region = region.transpose(Image.ROTATE_180)im.paste(region, box)

将子图paste回原图时,子图的region必须和给定box的region吻合。该region不能超过原图。而原图和region的mode不需要匹配,Pillow会自动处理。
另一个例子

Rolling an imagedef roll(image, delta): "Roll an image sideways" image = image.() #复制图像 xsize, ysize = image.size delta = delta % xsize if delta == 0: return image part1 = image.crop((0, 0, delta, ysize)) part2 = image.crop((delta, 0, xsize, ysize)) image.paste(part2, (0, 0, xsize-delta, ysize)) image.paste(part1, (xsize-delta, 0, xsize, ysize)) return image

分离和合并通道

r, g, b = im.split()im = Image.merge("RGB", (b, g, r))

对于单通道图片,split()返回图像本身。为了处理单通道图片,必须先将图片转成RGB。
几何变换
Image类有resize()、rotate()和transpose()、transform()方法进行几何变换。
简单几何变换

out = im.resize((128, 128))out = im.rotate(45) # 顺时针角度表示

置换图像

out = im.transpose(Image.FLIP_LEFT_RIGHT)out = im.transpose(Image.FLIP_TOP_BOTTOM)out = im.transpose(Image.ROTATE_90)out = im.transpose(Image.ROTATE_180)out = im.transpose(Image.ROTATE_270)

transpose()和象的rotate()没有性能差别。
更通用的图像变换方法可以使用transform()
模式转换
convert()方法
模式转换

im = Image.open('lena.ppm').convert('L')

图像增强
Filter ImageFilter模块包含很多预定义的增强filters,通过filter()方法使用
应用filters

from PIL import ImageFilterout = im.filter(ImageFilter.DETAIL)

像素点处理
point()方法通过一个函数或者查询表对图像中的像素点进行处理(例如对比度操作)。
像素点变换

# multiply each pixel by 1.2out = im.point(lambda i: i * 1.2)

上述方法可以利用简单的表达式进行图像处理,通过组合point()和paste()还能选择性地处理图片的某一区域。
处理单独通道

# split the image into indivial bandssource = im.split()R, G, B = 0, 1, 2# select regions where red is less than 100mask = source[R].point(lambda i: i < 100 and 255)# process the green bandout = source[G].point(lambda i: i * 0.7)# paste the processed band back, but only where red was < 100source[G].paste(out, None, mask)# build a new multiband imageim = Image.merge(im.mode, source)

注意到创建mask的语句:

mask = source[R].point(lambda i: i < 100 and 255)

该句可以用下句表示

imout = im.point(lambda i: expression and 255)

如果expression为假则返回expression的值为0(因为and语句已经可以得出结果了),否则返回255。(mask参数用法:当为0时,保留当前值,255为使用paste进来的值,中间则用于transparency效果)
高级图片增强
对其他高级图片增强,应该使用ImageEnhance模块 。一旦有一个Image对象,应用ImageEnhance对象就能快速地进行设置。 可以使用以下方法调整对比度、亮度、色平衡和锐利度。
图像增强

from PIL import ImageEnhanceenh = ImageEnhance.Contrast(im)enh.enhance(1.3).show("30% more contrast")

动态图
Pillow支持一些动态图片的格式如FLI/FLC,GIF和其他一些处于实验阶段的格式。TIFF文件同样可以包含数帧图像。
当读取动态图时,PIL自动读取动态图的第一帧,可以使用seek和tell方法读取不同郑

from PIL import Imageim = Image.open("animation.gif")im.seek(1) # skip to the second frametry: while 1: im.seek(im.tell()+1) # do something to imexcept EOFError: pass # end of sequence

当读取到最后一帧时,Pillow抛出EOFError异常。
当前版本只允许seek到下一郑为了倒回之前,必须重新打开文件。
或者可以使用下述迭代器类
动态图迭代器类

class ImageSequence: def __init__(self, im): self.im = im def __getitem__(self, ix): try: if ix: self.im.seek(ix) return self.im except EOFError: raise IndexError # end of sequencefor frame in ImageSequence(im): # ...do something to frame...Postscript Printing

Pillow允许通过Postscript Printer在图片上添加images、text、graphics。

Drawing Postscriptfrom PIL import Imagefrom PIL import PSDrawim = Image.open("lena.ppm")title = "lena"box = (1*72, 2*72, 7*72, 10*72) # in pointsps = PSDraw.PSDraw() # default is sys.stdoutps.begin_document(title)# draw the image (75 dpi)ps.image(box, im, 75)ps.rectangle(box)# draw centered titleps.setfont("HelveticaNarrow-Bold", 36)w, h, b = ps.textsize(title)ps.text((4*72-w/2, 1*72-h), title)ps.end_document()

更多读取图片方法
之前说到Image模块的open()函数已经足够日常使用。该函数的参数也可以是一个文件对象。
从string中读取

import StringIOim = Image.open(StringIO.StringIO(buffer))

从tar文件中读取

from PIL import TarIOfp = TarIO.TarIO("Imaging.tar", "Imaging/test/lena.ppm")im = Image.open(fp)

草稿模式
draft()方法允许在不读取文件内容的情况下尽可能(可能不会完全等于给定的参数)地将图片转成给定模式和大小,这在生成缩略图的时候非常有效(速度要求比质量高的场合)。
draft模式

from __future__ import print_functionim = Image.open(file)print("original =", im.mode, im.size)im.draft("L", (100, 100))print("draft =", im.mode, im.size)

⑥ 求助.python使用matplotlib出错

为了避免各种问题,请使用最新的2.7.13安装文件

1、先设置好环境变量
在path变量中设置好以下路径:
C:\Python27\Scripts
C:\Python27

2、大部分报错问题都是因为库与库之间存在依赖关系
matplotlib依赖dateutil和pyparsing,如果Python里面没有安装dateutil和pyparsing,那么后续使用matplotlib的时候很可能会遇到依赖问题。所以需要安装dateutil。
进入下面网址,找到matplotlib,可以看到所需要的各种包的描述。
http://www.lfd.uci.e/~gohlke/pythonlibs/#python-dateutil
http://www.lfd.uci.e/~gohlke/pythonlibs/#pyparsing
Matplotlib, a 2D plotting library.
Requires numpy, dateutil, pytz, pyparsing, cycler, setuptools, and optionally pillow, pycairo, tornado, wxpython, pyside, pyqt4, ghostscript, miktex, ffmpeg, mencoder, avconv, or imagemagick.
所以上面这些包肯定是都需要有的,如果没有遇到问题,可能是因为代码中没有引用这些包而已;或者已经安装了。

2.1、使用easy_install.exe来安装所需要依赖的包
现在dateutil使用easy_install命令来安装,(easy_install会自己从网络上需要最新的合适的包来安装,所以不需要你自己去寻找和下载)
只需要输入 easy_install python-dateutil 命令就可以。
如果找不到easy_install 命令,要么是你的环境变量没有设置好,请参考1。要么是你的python包太老,没有预装easy_install,那就参考3,先安装easy_install

3、安装easy_install.exe, 手动下载安装包到本地安装
https://pypi.python.org/pypi/setuptools
找到ez_setup.py文件,下载到本地E:\iso\VisualStudio2010\ (我是下载到这里,你自己就随意吧)
在cmd窗口下面,输入:
Python E:\iso\VisualStudio2010\ez_setup.py
成功后,C:\Python27\Scripts\目录下会多了easy_install.exe

4、使用easy_install.exe安装dateutil和pyparsing。。
反正根据提示,缺啥就用easy_install安装啥,这个easy_install是按照关键字来搜索安装包的。
easy_install python-dateutil
easy_install pyparsing
easy_install pip

4.1、如果不用easy_install.exe安装,也可以使用pip通过本地安装或者网络安装
使用pip安装 的命令是: pip install numpy
如果要手动把包下载到本地再安装,请参考6

5、把路径如:C:\Python27\Lib\site-packages\scipy\lib中的six.py six.pyc six.pyo三个文件拷贝到C:\Python27\Lib\site-packages目录下。

6、使用下载到本地的whl来安装各种包
在下面页面下载所对应的32bit或者64bit,区分python2.7还是python3的
http://www.lfd.uci.e/~gohlke/pythonlibs/#numpy
numpy-1.11.1+mkl-cp27-cp27m-win_amd64.whl
pandas-0.18.1-cp27-cp27m-win_amd64.whl
scipy-0.17.1-cp27-cp27m-win_amd64.whl
matplotlib-1.5.2-cp27-cp27m-win_amd64.whl
把上面这些需要的whl放到python的scripts目录下,然后用下面的命令来安装即可
c:\Python27-x64\Scripts>
pip install pandas-0.18.1-cp27-cp27m-win_amd64.whl

⑦ python如何安装pil库

PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。
由于PIL仅支持到Python 2.7,加上年久失修,于是一群志愿者在PIL的基础上创建了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了许多新特性,因此,我们可以直接安装使用Pillow。
安装Python时已经把pip3也备好了,可以直接使用pip3安装PIL
命令行:pip3 install pillow
注意:
1.PIL安装包名字的pillow
2.使用pip3命令时,是要在pip3.exe所在路径下才能执行。一般pip3.exe是在python安装目录下的Script文件夹中。
更多Python相关技术文章,请访问Python教程栏目进行学习!以上就是小编分享的关于python如何安装pil库的详细内容希望对大家有所帮助,更多有关python教程请关注环球青藤其它相关文章!

⑧ 怎么安装python模块,如何安装python模块,常用安装方式

.
直接
下载的模块文件中已经有了模块的文件,有些模块只有一个文件,比如较早版本的BeautifulSoup,有些是一个文件夹,比如新版本BeautifulSoup就是一个叫做bs4的文件夹。

把这些文件直接到你的python路径下的/Lib/site-packages文件夹中,比如C:/Python27/Lib/site-packages。之后就可以在程序里直接引用了:
import BeautifulSoup
或者
from bs4 import BeautifulSoup

这是根据你放置的文件位置不同而决定的。

网上有人说直接放在Lib文件夹中就可以了。的确这样也行,但Lib文件夹中都是自带的模块,看一下就会发现我们用过的random、re等模块的代码文件。而外部模块一般放在site-packages文件夹中。

2.
setup.py
很多模块里都附带了setup.py文件,有同学直接双击了,然后发现没有用。

它的使用方法是从命令行去到setup.py所在的路径下,运行
python setup.py install

仔细看一下安装时输出的信息可以发现,在线学习这个命令做的事情其实也就是帮你把模块的代码到site-packages文件夹。

3.
setuptools
使用setuptools可以直接根据模块名称来自动下载安装,不需要自己再去寻找模块的安装文件。不过在使用之前,你得先安装setuptools自身。

windows平台的32位python,可以直接下载setuptools的exe文件安装。(去搜索setuptools windows可以找到,我也上传了一份在论坛本帖后面)

Linux用户可以从包管理器中安装,比如ubuntu:
apt-get install python-setuptools

windows平台64位python得用ez_setup.py进行安装(文件我也上传了)。这种方式也适用于所有平台。

在ez_setup.py所在文件夹下运行:
python ez_setup.py

setuptools会被安装在python路径\Scripts下。之后,你可以把这个路径添加到环境变量path中,也可以直接从命令行进入到Scripts文件夹下,执行easy_install,看看是否安装成功了。

之后,你就可以直接用它来安装你想要的模块,比如PIL:
easy_install PIL

视频教程程序就会帮你自动下载安装到site-packages里。

最后,介绍几个不错的模块,供大家参考使用。
PIL - 图形处理
PyXML - 解析和处理XML文件
MySQLdb - 连接MySQL数据库
Tkinter - 图形界面接口,python自带
smtplib - 发送电子邮件
ftplib - ftp编程
PyMedia - 多媒体操作
PyOpenGL - OpenGL接口
BeautifulSoup - HTML/XML的解析器

热点内容
千叶加密平台 发布:2025-02-08 03:16:12 浏览:257
il脚本 发布:2025-02-08 03:08:49 浏览:315
我的世界介绍神奇宝贝服务器 发布:2025-02-08 03:02:52 浏览:748
咪咕音乐linux 发布:2025-02-08 02:53:04 浏览:410
我的世界手机版大陆练习服务器 发布:2025-02-08 02:50:43 浏览:213
php的特点与优势 发布:2025-02-08 02:43:16 浏览:718
微信公众号怎么上传pdf 发布:2025-02-08 02:42:41 浏览:349
安卓如何查看通话总时长 发布:2025-02-08 02:27:49 浏览:579
快速dct算法 发布:2025-02-08 02:19:04 浏览:623
淘宝交易密码如何改 发布:2025-02-08 02:17:32 浏览:775