首页
学习
活动
专区
工具
TVP
发布

Python图像处理基础

Python自带的模块不必matlab差,至于加入OpenCv ,更加专业的图像处理呢,那另说,从今天开始记录Python学习的点滴,哇咔咔!

配置:python3.5,annaconda3,spider3

素材:照片一张、数据一组

使用PIL默认属性绘图

fromPILimportImage

frompylabimport*

import numpy as np

x = np.linspace(-np.pi,np.pi,256,endpoint=True)

C,S = np.cos(x),np.sin(x)

plt.plot(x,C)

plt.plot(x,S)

show()

从PIL库,也就是Python Image Lirary库中导入绘图模块Image

从pylab模块中导入所有,*表示所有

numpy.linspace:在指定的间隔内返回均匀间隔的数字。返回num均匀分布的样本,在[start, stop]。这个区间的端点可以任意的被排除在外。第一个参数为序列的起始点,第二个参数为序列的结束点,第三个参数为步长,第四个参数意为:如果是True,则一定包括stop,如果为False,一定不会有stop。结果如下图所示:

上面的两行plot代码为绘制图像,当然还可以对绘制图像做更加具体的要求,比如:

plt.plot(x,C,color='red',linewidth=2.5,linestyle='-')

plt.plot(x,S,color='blue',linewidth=2.5,linestyle='-.')

其中,前两个参数为横纵坐标,后两个坐标为线宽,和线形

更多plot的操作,参考官方网站:http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot

除此之外,我们还可以对坐标轴的绘制进行设置,具体代码如下:

importnumpyasnp

importmatplotlib.pyplotasplt

x = np.linspace(-np.pi,np.pi,256,endpoint=True)

C,S = np.cos(x),np.sin(x)

plt.xlim(x.min() *1.1,x.max() *1.1)

plt.xticks([-np.pi,-np.pi /2,,np.pi /2,np.pi],

[r'$-\pi$',r'$-\pi/2$',r'$0$',r'$+\pi/2$',r'$+\pi$'])

plt.ylim(C.min() *1.1,C.max() *1.1)

plt.yticks([-1,,+1],

[r'$-1$',r'$0$',r'$+1$'])

plt.plot(x,C,color='red',linewidth=2.5,linestyle='-')

plt.plot(x,S,color='blue',linewidth=2.5,linestyle='-.')

plt.show()

其中,

plt.xlim两参数为x的取值范围,即x自变量的最小值的1.1倍和最大值的1.1倍

输出结果如下:

matplotlib中的有关LaTex的使用介绍:Latex的使用

链接:https://matplotlib.org/users/mathtext.html

在完成了坐标轴的设置后,还可以通过Matplotlib设置坐标轴位置,Spines 是连接轴刻度标记的线,而且标明了数据区域的边界。 他们可以被放置在任意位置。我们将要改变现状,因为我们想要spines 置于中间。因为有四个spine(上下左右),我们将要通过设置颜色(无)丢弃上面和右侧的部分。 进而我们移动下面和左边的线到坐标0(数据空间)。

用法为:

Spine(axes, spine_type, path, **kwargs)axes :包含spine的轴实例。spine_type :指定spine类型的字符串path :用于绘制spine的路径实例。

此外,还可以通过legend()方法添加图例。第一个参数loc,选项如下:

'best':,(onlyimplementedforaxeslegends)(自适应方式)

'upper right':1,

'upper left':2,

'lower left':3,

'lower right':4,

'right':5,

'center left':6,

'center right':7,

'lower center':8,

'upper center':9,

'center':10,

第二个参数,哎,还是看CSDN博客https://blog.csdn.net/helunqu2017/article/details/78641290

完整的代码为:

importnumpyasnp

importmatplotlib.pyplotasplt

ax = plt.subplot(111)

ax.spines['right'].set_color('none')

ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')

ax.spines['bottom'].set_position(('data',))

ax.yaxis.set_ticks_position('left')

ax.spines['left'].set_position(('data',))

x = np.linspace(-np.pi,np.pi,256,endpoint=True)

C,S = np.cos(x),np.sin(x)

plt.plot(x,C,color='red',linewidth=2.5,linestyle='-',label=r'$cos(t)$')

plt.plot(x,S,color='blue',linewidth=2.5,linestyle='-',label=r'$sin(t)$')

plt.legend(loc='upper left',frameon=False)

plt.xlim(x.min() *1.1,x.max() *1.1)

plt.xticks([-np.pi,-np.pi /2,,np.pi /2,np.pi],

[r'$-\pi$',r'$-\pi/2$',r'$0$',r'$+\pi/2$',r'$+\pi$'])

plt.ylim(C.min() *1.1,C.max() *1.1)

plt.yticks([-1,,+1],

[r'$-1$',r'$0$',r'$+1$'])

plt.show()

输出图像为:

绘制点和线

绘制图片:LPW.jpg

fromPILimportImage

frompylabimport*

im = array(Image.open("LPW.jpg"))

imshow(im)

x = [100,400,600,800]

y = [100,200,1000,1200]

plot(x[:2],y[:2],'b*')

lot(x,y,linewidth=3.5)

show()

很好理解,用矩阵显示图片,并且右上角为原点,在坐标中展示图片,

plot(x[:2],y[:2],'b*')x/y参数为2表示在坐标系中显示前两个坐标,b*蓝色小星星,再一次plot显示3.5线宽显示。

注意,我们取x[:2]意为取x列表元素的第零个和第一个,不包含第二个元素,y列表同理,需要注意的是,x,与y列表的取值数量应该一致,否则,系统会报错。而当我们用plot()方法将各个点相连时,程序会自动将所有的x与y的对应点相连,此时,若x与y列表元素数量不一致,系统同样会报错。

效果如下:

绘图时有很多选项可以控制图像的颜色和样式:

plot(x,y)#默认为蓝色实线

plot(x,y,’r*’)#红色星状标记

plot(x,y,’go-’)#带有圆圈标记的绿线

plot(x,y,’ks-’)#带有正方形标记的黑色点线

颜色标注:

‘b’#蓝色

‘g’#绿色

‘r’#红色

‘c’#青色

‘m’#品红

‘y’#黄色

‘k’#黑色

‘w’#白色

线型格式命令:

‘-’#实线

‘--’#虚线

‘:’#点线

绘制标记格式命令:

‘.’#点

‘o’#圆圈

‘s’#正方形

‘*’#星形

‘+’#加号

‘x’#叉号

图像轮廓和灰度直方图

因为绘制轮廓需要对每个坐标[x,y]的像素值施加一个相同的阈值,所以首先需要将图像灰度化

完整代码如下:

fromPILimportImage

frompylabimport*

image = array(Image.open('LPW.jpg').convert('L'))

figure()# 新建一个图像

gray()# 不使用颜色信息

contour(image,origin='image')

axis('equal')

plt.show()

显示图像如图所示:

这样就成功生成了一张图片的轮廓了。

其中,

contour()本应用于设置等高线,用法为:

contour(Z) :绘制矩阵Z的等高线

contour(Z,n) :设置等高线的根数(画出来有n根等高线)

contour(Z,v) :v是元素随下标单调递增的一维向量,用来设置等高线的值。即在固定的几个值的位置设置等高线。

其中的origin可以传入’upper’,’lower’,’None’,以及’image’等参数用于固定图像的位置。

axis('equal')表示x轴和y轴的单位长度相同。

axis([xmin xmax ymin ymax]): [ ]中分别给出x轴和y轴的最大值、最小值。( sets scaling for the x- and y-axes on the current plot.)

axis([xmin xmax ymin ymax zmin zmax]):[ ]中分别给出x轴、y轴、z轴的最大值、最小值。(sets the scaling for the x-, y- and z-axes on the current 3-D plot)

axis equal 或axis(‘equal’) :表示x轴和y轴的单位长度相同。(sets the aspect ratio so that equal tick mark increments on the x-,y- and z-axis are equal in size)

axis square 或 axis(‘square’): 显示的坐标系呈正方形。(makes the current axis box square in size.)

axis off 或 axis(‘off’) :关闭所有坐标轴线、刻度标记和标签。(turns off all axis labeling, tick marks and background)

axis auto:基于x、y和z的最大值和最小值来自动设置坐标轴的范围。用户可以只限定某一个坐标轴,如:axis 'auto x'用来限定x轴的范围;axis 'auto yz'用来限定y轴和z轴的范围。(returns the axis scaling to its default, automatic mode where,for each dimension, 'nice' limits are chosen based on the extents of all line, surface, patch, and image children.)

axis manual:将坐标轴的范围锁定为当前范围。如果打开了hold on命令,则后续的图形都使用同样的坐标范围。该函数设置XLimMode、YLimMode和ZLimMode属性为manual值。(freezes the scaling at the current limits, so that if HOLD is turned on, subsequent plots will use the same limits.)

axis tight:设置坐标轴的范围为数据的范围。(sets the axis limits to the range of the data.)

axis fill:设置坐标轴的范围以及PlotBoxAspectRatio属性。坐标轴将填充整个矩形局域。只有PlotBoxAspectRatioMode或DataAspectRatioMode属性值为 manual时,该方法才起作用。(sets the axis limits and PlotBoxAspectRatio so that the axis fills the position rectangle.)

axis ij:将坐标系的原点设置到左上角。i轴为垂直轴,正方向为从上到下。j轴为水平轴,正方向为从左到右。(puts MATLAB into its "matrix" axes mode. The coordinate system origin is at the upper left corner. The i axis is vertical and is numbered from top to bottom. The j axis is horizontal and is numbered from left to right.)

axis xy:在默认的笛卡尔坐标系中绘制图形,坐标系的原点在左下角。x轴为水平坐标轴,正方向为从左到右;y轴为垂直坐标轴,正方向为从下到上。(puts MATLAB into its default "Cartesian" axes mode. The coordinate system origin is at the lower left corner. The x axis is horizontal and is numbered from left to right. The y axis is vertical and is numbered from bottom to top.)

axis on:关闭所有坐标轴线、刻度标记和标签。( turns axis labeling, tick marks and background back on)

axis image:功能与axis equal相同。只不过坐标轴的边框紧贴在数据的四轴。多用来显示图片。(is the same as AXIS EQUAL except that the plot box fits tightly around the data.)

axis normal:自动调节坐标轴的纵横比,从而是图形随窗口的形状而改变.(restores the current axis box to full size and removes any restrictions on the scaling of the units.This undoes the effects of AXIS SQUARE and AXIS EQUAL)

v=axis:返回一个行向量,向量中的元素包含x、y和z轴的刻度因子。v具有四个或六个元素,这取决于当前坐标轴是二维的还是三维的。返回值是当前坐标轴的XLim、YLim和ZLim属性的值。(returns a row vector containing the scaling for the current plot. If the current view is 2-D, V has four components; if it is 3-D, V has six components.)

axis Vis3D:锁定坐标轴的纵横比.(freezes aspect ratio properties to enable rotation of 3-D objects and overrides stretch-to-fill.)

图像的直方图用来表征该图像的像素值分布情况,用一定数目的小区间(bin)来表征像素值的范围,每个小区间会得到落入该小区域间表示范围的像素数目,该灰度图像的直方图可以使用hist()函数绘制,完整代码如下:

fromPILimportImage

frompylabimport*

fig = plt.figure(figsize=(15,15))

image = array(Image.open('LPW.jpg').convert('L'))

plt.subplot(2,1,1)

plt.imshow(image,cmap=cm.gray)

plt.axis("off")

plt.subplot(2,1,2)

plt.hist(image.flatten(),256)# flatten可以将矩阵转化成一维序列

plt.show()

其中,

imshow()函数格式为:

(X,cmap=None)

X: 要绘制的图像或数组。

cmap: 颜色图谱(colormap), 默认绘制为RGB(A)颜色空间。

其它可选的颜色图谱如下列表:

用的比较多的有gray,jet等,如:

subplot:

下, 一个 对象可以包含多个子图(), 可以使用 快速绘制, 其调用形式如下 :

图表的整个绘图区域被分成 行和 列

然后按照从左到右,从上到下的顺序对每个子区域进行编号,左上的子区域的编号为1

参数指定创建的 对象所在的区域

如果 , 那整个绘制图表样式为 的图片区域, 用坐标表示为

这时, 当 时, 表示的坐标为(1, 3), 即第一行第三列的子图

如果 , 和 这三个数都小于 的话, 可以把它们缩写为一个整数, 例如 和 是相同的.

在 指定的区域中创建一个轴对象. 如果新创建的轴和之前创建的轴重叠的话,之前的轴将被删除.

显示图像如图所示:

hist()函数的第二个参数指定小区间的数目,需要注意的是,因为hist()只接受一维数组作为输入,所以我们在绘制图像直方图之前,必须先对图像进行平压处理,flatten()方法将任意数组按照行优先准则转换成一维数组。

plt.subplot()意为创建子图像。其中括号内传入了三个参数,第一个表示Y轴方向的子图个数,第二个表示X轴方向的子图个数,第三个则表示当前要画图的焦点。

参考文献:

python计算机视觉编程:http://yongyuan.name/pcvwithpython/

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180404G1Z8IW00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券