python 图像处理入门
第一篇Python图片处理模块PIL(pillow)

第⼀篇Python图⽚处理模块PIL(pillow)本篇包含:⼀、Image类的属性:1、Format 2、Mode 3、Size 4、Palette 5、Info⼆、类的函数:1、New 2、Open 3、Blend 4、Composite 5、Eval 6、Frombuffer 7、Fromstring 8、Merge三、Image类的⽅法:1、Convert 2、Copy 3、Crop 4、Draft 5、Filter 6、Fromstring 7、Getbands 8、Getbbox 9、Getcolors10、Getdata 1 1、 Getextrema 12、Getpixel 13、Histogram 14、Load 15、Paste⼀、PIL的基本概念:PIL中所涉及的基本概念有如下⼏个:通道(bands)、模式(mode)、尺⼨(size)、坐标系统(coordinate system)、调⾊板(palette)、信息(info)和滤波器(filters)。
1、通道每张图⽚都是由⼀个或者多个数据通道构成。
PIL允许在单张图⽚中合成相同维数和深度的多个通道。
以RGB图像为例,每张图⽚都是由三个数据通道构成,分别为R、G和B通道。
⽽对于灰度图像,则只有⼀个通道。
对于⼀张图⽚的通道数量和名称,可以通过⽅法getbands()来获取。
⽅法getbands()是Image模块的⽅法,它会返回⼀个字符串元组(tuple)。
该元组将包括每⼀个通道的名称。
Python的元组与列表类似,不同之处在于元组的元素不能修改,元组使⽤⼩括号,列表使⽤⽅括号,元组创建很简单,只需要在括号中添加元素,并使⽤逗号隔开即可。
⽅法getbands()的使⽤如下:from PIL import Imageim = Image.open("xiao.png")print(im.getbands())输出:('R', 'G', 'B')2、模式图像的模式定义了图像的类型和像素的位宽。
Python Imaging Library中文手册、PIL中文手册、python图像处理

Python Imaging Library 中文手册这是PIL的官方手册,2005年5月6日发布。
这个版本涵盖PIL 1.1.5的全部内容。
本中文手册来自 啄木鸟社区你可以在PythonWare library找到改文档其它格式的版本以及先前的版本。
原版出处:/library/pil/handbook/第一部分:介绍•PIL 1.1.5 | 2005年5月5日| Fredrik Lundh概览介绍Python Imaging Library为Python解释器提供了图像处理的功能。
这个库提供了广泛的文件格式支持、高效的内部表示以及相当强大的图像处理功能。
这个图像处理库的核心被设计成为能够快速访问以几种基本像素类型表示的图像数据。
它为通用图像处理工具提供了一个坚实基础。
让我们来看一些这个库可能的用途:图像归档处理Python Imaging Library适合编写图像归档和批处理应用程序。
使用这个库可以创建缩略图、转换文件格式、打印图像等。
当前版本的库能够识别和读取很多的图像格式。
而能够输出的格式被特意限制于在交换和展示图像中最常用的格式上。
图像显示当前版本的库包含Tk的PhotoImage和 BitmapImage接口,也包含Windows的DIB接口(可以同PythonWin和其他基于Windows的界面工具包一起使用)。
还有一些其他的PIL支持提供了很多其他的GUI工具包。
为了调试方便,库中有一个 show方法,它把图像保存到磁盘中,并调用外部显示工具来显示它。
图像处理这个库提供了基本的图像处理功能,包括点操作、一些内建滤波核的滤波操作以及颜色空间变换操作。
这个库也支持图像的缩放、旋转及任何仿射(affine)变换。
库中包含一个histogram方法,可以从图像中提取某些统计特征。
用它可以实现自动的对比度增强以及全局统计分析功能。
入门导引使用Image 类Python Imaging Library中最重要的类是Image 类,它定义在与它同名的模块中。
Python图像处理库——PIL

Python图像处理库——PIL PIL全称Python Image Library,是python官⽅的图像处理库,包含各种图像处理模块。
Pillow是PIL的⼀个派⽣分⽀,包含与PIL相同的功能,并且更灵活。
python3.0之后,PIL不再更新,pillow代替了它原有的地位。
Pillow的官⽅⽂档: 在调⽤pillow时,代码依然是写成PIL,模块导⼊⽅式如下:from PIL import Image,ImageFilter 下⾯介绍基本⽤法。
Image Image是pillow最基本的模块,包含⽤于保存图像对象的类。
图像导⼊、旋转、显⽰、保存from PIL import Imageimg = Image.open('1.jpg')img = img.rotate(45)img.show()img.save('r.jpg') 图像导⼊后保存为Image对象,该对象⾃带各种函数,包括图像处理操作、显⽰、保存等功能,⼤部分操作返回的依然是Image对象。
需要注意的是,open函数执⾏的时候并没有⽴即把图像像素数据导⼊,仅仅是对图像⽂件添加占⽤标记,直到图像真正需要⽤于计算时,才会把像素数据导⼊。
以上代码结果如下:Numpy.array与Image之间的转换Image到arrayimport numpy as npfrom PIL import Imageimg = Image.open('1.jpg')a = np.array(img)print(a.shape, a.dtype) 对于读取的图像,在Image对象中,图像默认以RGB模式保存,且各个像素值默认⽤ 8bit 的⽆符号整型来存,不论图像以什么类型保存。
因此转换为array后dtype是uint8,不像matplotlib,png是float32,⽽jpg是uint8。
其它图像模式看官⽅⽂档:array到Imageimport numpy as npfrom PIL import Imagea = np.random.random([256,256,3])*255a = np.array(a,dtype = np.uint8)img = Image.fromarray(a)img.show() array必须先将数据类型转换到uint8才能转换成Image,否则会出错,尽管⽂档中写着能有限地⽀持浮点类型。
PythonPIL库处理图片常用操作,图像识别数据增强的方法

PythonPIL库处理图⽚常⽤操作,图像识别数据增强的⽅法在博客训练神经⽹络的时候,做了数据增强,对图⽚的处理采⽤的是PIL(Python Image Library), PIL是Python常⽤的图像处理库.下⾯对PIL中常⽤到的操作进⾏整理:1. 改变图⽚的⼤⼩from PIL import Image, ImageFont, ImageDrawdef image_resize(image, save, size=(100, 100)):""":param image: 原图⽚:param save: 保存地址:param size: ⼤⼩:return:"""image = Image.open(image) # 读取图⽚image.convert("RGB")re_sized = image.resize(size, Image.BILINEAR) # 双线性法re_sized.save(save) # 保存图⽚return re_sized2. 对图⽚进⾏旋转:from PIL import Image, ImageFont, ImageDrawimport matplotlib.pyplot as pltdef image_rotate(image_path, save_path, angle):"""对图像进⾏⼀定⾓度的旋转:param image_path: 图像路径:param save_path: 保存路径:param angle: 旋转⾓度:return:"""image = Image.open(image_path)image_rotated = image.rotate(angle, Image.BICUBIC)image_rotated.save(save_path)return image_rotated3. 对图⽚进⾏左右反转:from PIL import Image, ImageFont, ImageDrawimport matplotlib.pyplot as pltdef image_flip(image_path, save_path):"""图图象进⾏左右反转:param image_path::param save_path::return:"""image = Image.open(image_path)image_transpose = image.transpose(Image.FLIP_LEFT_RIGHT) # Image.FLIP_TOP_BOTTOM 上下反转image_transpose.save(save_path)return image_transpose4. 对图像进⾏裁剪:from PIL import Image, ImageFont, ImageDrawimport matplotlib.pyplot as pltdef image_crop(image_path, save_path, crop_region):"""对图像进⾏裁剪:param image_path::param save_path::param crop_region: 裁剪的区域 crop_window=(x_min, y_min, x_max, y_max):return:"""image = Image.open(image_path)image_crop = image.crop(crop_region) # (width_min, height_min, width_max, height_max) 图像的原点是在左上⾓ image_crop.save(save_path)return image_crop5. 在图⽚上添加⽂字from PIL import Image, ImageFont, ImageDrawimport matplotlib.pyplot as pltdef image_title(image_path, save_path, font_pos, font_size, text):"""对图像添加⽂字:param image_path::param save_path::param font_pos: ⽂字位置(x, y):param font_size: ⽂字⼤⼩:param text: ⽂字内容:return:"""image = Image.open(image_path)font = ImageFont.truetype(font=r"C:\Windows\Fonts\Times New Roman\times.ttf", size=font_size)draw = ImageDraw.Draw(image)draw.text(xy=font_pos, text=text, fill=(255, 0, 0), font=font)image.save(save_path)return image除以上之外,数据增强的⽅法还有对图像颜⾊进⾏抖动,和对图像进⾏⾼斯噪声处理1. 颜⾊抖动:from PIL import Image, ImageFont, ImageDraw, ImageEnhanceimport matplotlib.pyplot as pltimport numpy as npdef image_color(image_path, save_path):"""对图像进⾏颜⾊抖动:param image_path::param save_path::return:"""image = Image.open(image_path)print(type(image))random_factor = np.random.randint(low=0, high=31) / 10.0 # 随机的扰动因⼦color_image = ImageEnhance.Color(image).enhance(random_factor) # 调整图像的饱和度random_factor = np.random.randint(low=10, high=21) / 10.0bright_image = ImageEnhance.Brightness(color_image).enhance(random_factor) # 调整图像的亮度 random_factor = np.random.randint(low=10, high=21) / 10.0contrast_image = ImageEnhance.Contrast(bright_image).enhance(random_factor) # 调整图像的对⽐度 random_factor = np.random.randint(low=0, high=31) / 10.0sharp_image = ImageEnhance.Sharpness(contrast_image).enhance(random_factor) # 调整图像的锐度 sharp_image.save(save_path)return sharp_image2.⾼斯噪声处理:from PIL import Image, ImageFont, ImageDraw, ImageEnhanceimport matplotlib.pyplot as pltimport numpy as npimport randomdef image_gauss(image_path, save_path, mean, stddev):"""对图像进⾏颜⾊抖动:param image_path::param save_path::return:"""def gaussNoisy(pixel_array, mean, stddev):"""对图像的单个通道进⾏⾼斯噪声处理:param pixel_array::param mean: 均值:param stddev: ⽅差:return:"""for x in pixel_array:x += random.gauss(mean, stddev)return pixel_array# 对图像进⾏数据转换image = Image.open(image_path)image.convert("RGB")img = np.asarray(image) # 将PIL中的数据格式转化为arrayimg.flags.writeable = True # 将数组改为读写模式width, height = img.shape[: 2]img_r = img[:, :, 0].flatten()img_g = img[:, :, 1].flatten()img_b = img[:, :, 2].flatten()img_r_new = gaussNoisy(pixel_array=img_r, mean=mean, stddev=stddev)img_g_new = gaussNoisy(pixel_array=img_g, mean=mean, stddev=stddev)img_b_new = gaussNoisy(pixel_array=img_b, mean=mean, stddev=stddev)img[:, :, 0] = img_r_new.reshape([width, height])img[:, :, 1] = img_g_new.reshape([width, height])img[:, :, 2] = img_b_new.reshape([width, height])image_new = Image.fromarray(np.uint8(img)) # 将array中的数据格式转化为PIL中的数据格式 image_new.save(save_path)return image_new。
python中image的用法

python中image的用法Python中的image模块提供了许多功能强大的图像处理工具,使得开发人员可以轻松地加载、处理和保存图像。
在这篇文章中,我们将一步一步地探索python 中image模块的用法。
第一步,我们需要安装image模块。
在Python中,我们可以使用pip来安装image模块。
打开命令行终端,并输入以下命令:pythonpip install image这将自动下载和安装image模块。
第二步,我们可以加载图像文件。
在Python中,我们可以使用image模块的open()函数来加载图像文件。
以下是一个加载图像文件的示例代码:pythonfrom PIL import Image# 加载图像文件image = Image.open("image.jpg")在这个例子中,我们加载了名为"image.jpg"的图像文件,并将它保存在一个变量中。
第三步,我们可以对图像进行一些基本的操作。
image模块提供了许多内置的方法和函数,使得图像处理变得简单和灵活。
以下是一些常用的图像处理操作的示例:pythonfrom PIL import Image# 加载图像文件image = Image.open("image.jpg")# 获取图像的大小width, height = image.size# 调整图像尺寸resized_image = image.resize((width 2, height 2))# 旋转图像rotated_image = image.rotate(90)# 翻转图像flipped_image = image.transpose(Image.FLIP_LEFT_RIGHT)# 显示图像image.show()# 保存图像resized_image.save("resized_image.jpg")在这个例子中,我们通过使用resize()方法调整图像的尺寸,使用rotate()方法旋转图像,使用transpose()方法翻转图像。
Python图像处理库PIL的ImageEnhance模块使用介绍

Python图像处理库PIL的ImageEnhance模块使⽤介绍ImageEnhance模块提供了⼀些⽤于图像增强的类。
⼀、ImageEnhance模块的接⼝所有的增强类都实现了⼀个通⽤的接⼝,包括⼀个⽅法:enhancer.enhance(factor) ⇒ image该⽅法返回⼀个增强过的图像。
变量factor是⼀个浮点数,控制图像的增强程度。
变量factor为1将返回原始图像的拷贝;factor值越⼩,颜⾊越少(亮度,对⽐度等),更多的价值。
对变量facotr没有限制。
⼆、ImageEnhance模块的Color类颜⾊增强类⽤于调整图像的颜⾊均衡,在某种程度上类似控制彩⾊电视机。
该类实现的增强接⼝如下:ImageEnhance.Color(image) ⇒ Color enhancer instance创建⼀个增强对象,以调整图像的颜⾊。
增强因⼦为0.0将产⽣⿊⽩图像;为1.0将给出原始图像。
ImageEnhance.Color类的实例:>>> from PIL import Image, ImageEnhance>>> im02 =Image.open("D:\\Code\\Python\\test\\img\\test02.jpg")>>> im_1 = ImageEnhance.Color(im02).enhance(0.1)>>> im_5 = ImageEnhance.Color(im02).enhance(0.5)>>> im_8 =ImageEnhance.Color(im02).enhance(0.8)>>> im_20 = ImageEnhance.Color(im02).enhance(2.0)从前⾯的介绍,我们可以得知函数enhance()的参数factor决定着图像的颜⾊饱和度情况。
python图像处理库PIL介绍

python 图像处理库 PIL 介绍 1. 简介。
? ? 图像处理是一门应用非常广的技术,而拥有非常丰富第三方扩展库的 Python 当然不会 错过这一门盛宴。
PIL (Python Imaging Library)是 Python 中最常用的图像处理库,目前版 本为 1.1.7,我们可以?在这里?下载学习和查找资料。
? ? Image 类是 PIL 库中一个非常重要的类,通过这个类来创建实例可以有直接载入图像文 件,读取处理过的图像和通过抓取的方法得到的图像这三种方法。
2. 使用。
? ? 导入 Image 模块。
然后通过 Image 类中的 open 方法即可载入一个图像文件。
如果载 入文件失败,则会引起一个 IOError ;若无返回错误,则 open 函数返回一个 Image 对象。
现在,我们可以通过一些对象属性来检查文件内容,即: 1 >>> import Image 2 ?>>> im = Image.open("j.jpg") 3 ?>>> print im.format, im.size, im.mode 4 JPEG (440, 330) RGB ? ? 这里有三个属性,我们逐一了解。
? ? ? ? format : 识别图像的源格式,如果该文件不是从文件中读取的,则被置为 None 值。
? ? ? ? size : 返回的一个元组,有两个元素,其值为象素意义上的宽和高。
? ? ? ? mode : RGB(true color image),此外还有,L(luminance),CMTK(pre-press image)。
? ? 现在,我们可以使用一些在 Image 类中定义的方法来操作已读取的图像实例。
比如, 显示最新载入的图像: 1 >>>im.show() 2 ?>>>输出原图: 3. 函数概貌。
数字图像处理—基于Python 第12讲 图像复原-复原算法

9
估计点扩散函数
如果退化函数已知,则图像复原将变得较 为简单
估计psf 函数的基本方法有: – 观察法 – 实验法 – 建模法
10
估计点扩散函数
–观察法
取一个信号强、噪声小的子图像g (x,y) ,然后用一系列的 滤波器处理这个子图像,得到较好的效果图像f (x,y). 那么, 退化函数可以通过H (u,v)= G (u,v)/ F (u,v)得到
第5章 图像复原
图像复原算法
2
回顾
什么是图像复原 针对噪声的复原
− 噪声模型 − 空域滤波去噪方法 − 频域去噪方法
针对模糊等退化的复原
− 线性移不变退化模型 − 无约束图像复原 − 有约束图像复原
针对畸变的图像复原
− 几何变换 − 灰度插值 − 几何校正
3
本课内容
线性移不变退化模型 估计点扩散函数 图像复原算法
g(x, y)
T 0
f
x x0(t), y
y0(t)
dt
– x 0 (t) 和 y 0 (t) 随时间变化的移动距离 –T 是按下快门的时长
14
估计点扩散函数
G(u, v) g(x, y)e j2 (uxvy)dxdy
T 0
f
(x x0(t),
y
y0 (t))dte j2 (uxvy)dxdy
18
本课内容
线性移不变退化模型 估计点扩散函数 图像复原算法
无约束还原: − 逆滤波(Inverse filter) − 伪逆滤波(Pseudo inverse filtering) 有约束还原 − 维纳滤波(Wiener filter) − 受限最小二乘滤波(Constrained least
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Data types – numbers (2)
Assignments and conversions:
>>> a=3.0+4.0j >>> float(a) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: can't convert complex to float; use abs(z) >>> a.real 3.0 >>> a.imag 4.0 >>> abs(a) 5.0 # sqrt(a.real**2 + a.imag**2)
Mac OS X
Install the MacPorts package manager () and use this to get all necessary packages.
Windows
Python-(x,y) (/p/pythonxy) contains all necessary packages in binary form and an installer.
Why another language? Why Python?
Interactive: no code/compile/test-cycle! A lot of currently needed and easy accessible functionality compared with traditional scripting languages! Platform independent and freely available! Large user base and good documentation! Forces compactness and readability of programs by syntax! Some say: can be learned in 10 minutes...
Data types – numbers (1)
Python supports integer, floating point and complex valued numbers by default:
>>> 2+2 4 >>> # This is a comment ... 2+2 4 >>> # Integer division returns the floor: ... 7/3 2 >>> 7.0 / 2 3.5 >>> 1.0j * 1.0j (-1+0j) # but this works...
Introducing Python
The following introduction is based on the official „Python-Tutorial“
/tutorial/index.html
Python
„Python is an easy to learn, powerful programming language. [...] Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.“
Goals for today...
Draw interest to another programming language, namely: Python Motivation of an interactive Workflow („Spielwiese“) „Easy access” into practical image processing tasks using NumPy, SciPy, matplotlib and spyder Finally: Give you the ability to solve the exercises of this course
Conditionals – if
Divide cases in if/then/else manner:
>>> x = int(raw_input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... ... ... ... ... else: ... ... More print 'More' x = 0 print 'Negative changed to zero' print 'Zero' print 'Single'
The first program (2)
Counting Fibonacci series (with a colon after the print)
>>> # Fibonacci series: ... # the sum of two elements defines the next ... a, b = 0, 1 >>> while b < 10: ... ... ... 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 print b, a, b = b, a+b
matplotlib
spyder IDE
/p/spyderlib
Installing Python and packages
Linux
All of the prerequisites should be installable by means of the package manager of the distribution of your choice.
Special variables
Example: last result „_“ (only in interactive mode):
>>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625 >>> round(_, 2) 113.06
Outline
Introduction Presenting the Python programming language Image processing with NumPy and SciPy Visualization with matplotlib and the spyder IDE Summary
1. Example:
> python Python 2.7 (#1, Feb 28 2010, 00:02:06) Type "help", "copyright", "credits" or "license" for more information. >>> the_world_is_flat = True >>> if the_world_is_flat: ... ... Be careful not to fall off! print "Be careful not to fall off!"
Getting in touch with Python (2.X)
All of this tutorial will use the interactive mode:
Start the interpreter: python Or, an advanced interpreter: ipython
Data types – lists
Lists may contain different types of entries at once! First element has index: 0, last element: length-1.
>>> a = ['spam', 'eggs', 100, 1234] >>> a ['spam', 'eggs', 100, 1234] >>> a[0] 'spam' >>> a[-2] 100 >>> a[1:-1] ['eggs', 100] >>> a[:2] + ['bacon', 2*2] ['spam', 'eggs', 'bacon', 4]
Image Processing with Python
An introduction to the use of Python, NumPy, SciPy and matplotlib for image processing tasks