2017-09-21 10:38:50 guduruyu 阅读数 7918
  • Python+OpenCV3.3图像处理视频教程

    Python+OpenCV3.3图像处理视频培训课程:该教程基于Python3.6+OpenCV新版本3.3.0详细讲述Python OpenCV图像处理部分内容,包括opencv人脸识别、人脸检测、数字验证码识别等内容。是Python开发者学习图像知识与应用开发佳实践课程。

    5435 人正在学习 去看看 贾志刚

灰度直方图在数据统计分析、图像处理中有着比较广泛的应用,下面就介绍一下如何使用python来绘制灰度直方图。


下面直接看代码:

import matplotlib.pyplot as plt
import numpy as np


random_state = np.random.RandomState(19680801)
X = random_state.randn(10000)

fig, ax = plt.subplots()
ax.hist(X, bins=25, normed=True, color = 'yellow')
x = np.linspace(-5, 5, 1000)
ax.plot(x, 1 / np.sqrt(2*np.pi) * np.exp(-(x**2)/2), linewidth=4)
plt.show()


代码解读:

首先是使用random类生成数目为10000的伪随机数,接着使用pyplot模块中的subplots接口创建一个绘制对象,使用hist()成员函数开始绘制灰度直方图,第一个参数是随机数序列,bins指定直方的个数,normed指定是否进行归一化,而color指定直方图的颜色。

下面绘制的一个高斯函数曲线是为了证明这个伪随机序列是符合高斯正态分布的。


绘制结果如下:



2017.09.21

2017-09-21 11:45:44 guduruyu 阅读数 50808
  • Python+OpenCV3.3图像处理视频教程

    Python+OpenCV3.3图像处理视频培训课程:该教程基于Python3.6+OpenCV新版本3.3.0详细讲述Python OpenCV图像处理部分内容,包括opencv人脸识别、人脸检测、数字验证码识别等内容。是Python开发者学习图像知识与应用开发佳实践课程。

    5435 人正在学习 去看看 贾志刚

3D图形在数据分析、数据建模、图形和图像处理等领域中都有着广泛的应用,下面将给大家介绍一下如何使用python进行3D图形的绘制,包括3D散点、3D表面、3D轮廓、3D直线(曲线)以及3D文字等的绘制。


准备工作:

python中绘制3D图形,依旧使用常用的绘图模块matplotlib,但需要安装mpl_toolkits工具包,安装方法如下:windows命令行进入到python安装目录下的Scripts文件夹下,执行: pip install --upgrade matplotlib即可;linux环境下直接执行该命令。

安装好这个模块后,即可调用mpl_tookits下的mplot3d类进行3D图形的绘制。

下面以实例进行说明。


1、3D表面形状的绘制

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Make data
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))

# Plot the surface
ax.plot_surface(x, y, z, color='b')

plt.show()

这段代码是绘制一个3D的椭球表面,结果如下:



2、3D直线(曲线)的绘制

import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()

plt.show()

这段代码用于绘制一个螺旋状3D曲线,结果如下:



3、绘制3D轮廓

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm

fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)

ax.set_xlabel('X')
ax.set_xlim(-40, 40)
ax.set_ylabel('Y')
ax.set_ylim(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim(-100, 100)

plt.show()

绘制结果如下:



4、绘制3D直方图

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y = np.random.rand(2, 100) * 4
hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]])

# Construct arrays for the anchor positions of the 16 bars.
# Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos,
# ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid
# with indexing='ij'.
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25)
xpos = xpos.flatten('F')
ypos = ypos.flatten('F')
zpos = np.zeros_like(xpos)

# Construct arrays with the dimensions for the 16 bars.
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = hist.flatten()

ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')

plt.show()

绘制结果如下:


5、绘制3D网状线

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Grab some test data.
X, Y, Z = axes3d.get_test_data(0.05)

# Plot a basic wireframe.
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

plt.show()

绘制结果如下:



6、绘制3D三角面片图

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np


n_radii = 8
n_angles = 36

# Make radii and angles spaces (radius r=0 omitted to eliminate duplication).
radii = np.linspace(0.125, 1.0, n_radii)
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)

# Repeat all angles for each radius.
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)

# Convert polar (radii, angles) coords to cartesian (x, y) coords.
# (0, 0) is manually added at this stage,  so there will be no duplicate
# points in the (x, y) plane.
x = np.append(0, (radii*np.cos(angles)).flatten())
y = np.append(0, (radii*np.sin(angles)).flatten())

# Compute z to make the pringle surface.
z = np.sin(-x*y)

fig = plt.figure()
ax = fig.gca(projection='3d')

ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True)

plt.show()

绘制结果如下:



7、绘制3D散点图

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np


def randrange(n, vmin, vmax):
    '''
    Helper function to make an array of random numbers having shape (n, )
    with each number distributed Uniform(vmin, vmax).
    '''
    return (vmax - vmin)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

n = 100

# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, c=c, marker=m)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

绘制结果如下:



8、绘制3D文字

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt


fig = plt.figure()
ax = fig.gca(projection='3d')

# Demo 1: zdir
zdirs = (None, 'x', 'y', 'z', (1, 1, 0), (1, 1, 1))
xs = (1, 4, 4, 9, 4, 1)
ys = (2, 5, 8, 10, 1, 2)
zs = (10, 3, 8, 9, 1, 8)

for zdir, x, y, z in zip(zdirs, xs, ys, zs):
    label = '(%d, %d, %d), dir=%s' % (x, y, z, zdir)
    ax.text(x, y, z, label, zdir)

# Demo 2: color
ax.text(9, 0, 0, "red", color='red')

# Demo 3: text2D
# Placement 0, 0 would be the bottom left, 1, 1 would be the top right.
ax.text2D(0.05, 0.95, "2D Text", transform=ax.transAxes)

# Tweaking display region and labels
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_zlim(0, 10)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')

plt.show()

绘制结果如下:



9、3D条状图

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
    xs = np.arange(20)
    ys = np.random.rand(20)

    # You can provide either a single color or an array. To demonstrate this,
    # the first bar of each set will be colored cyan.
    cs = [c] * len(xs)
    cs[0] = 'c'
    ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.show()

绘制结果如下:




2017.09.21

2017-05-04 16:30:54 u012150360 阅读数 1975
  • Python+OpenCV3.3图像处理视频教程

    Python+OpenCV3.3图像处理视频培训课程:该教程基于Python3.6+OpenCV新版本3.3.0详细讲述Python OpenCV图像处理部分内容,包括opencv人脸识别、人脸检测、数字验证码识别等内容。是Python开发者学习图像知识与应用开发佳实践课程。

    5435 人正在学习 去看看 贾志刚

图像的打开:

import cv2

filename = "/home/vickyleexy/PycharmProjects/33.jpg"
img = cv2.imread(filename)
print type(img),img.shape,img.dtype
cv2.namedWindow("xiamu")
cv2.imshow("xiamu",img)
cv2.waitKey(0)
cv2.destroyAllWindows() #销毁窗口

使用opencv打开图像时报错:
error: /io/opencv/modules/highgui/src/window.cpp:565: error: (-2) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function cvNamedWindow

但检查发现gtk什么的已经安装了……
解决方法:
sudo apt-get install python-opencv
同时卸载之前安装的opencv-python
sudo pip uninstall opencv-python

opencv安装:
http://www.samontab.com/web/2014/06/installing-opencv-2-4-9-in-ubuntu-14-04-lts/

2017-03-27 15:19:19 biboshouyu 阅读数 1102
  • Python+OpenCV3.3图像处理视频教程

    Python+OpenCV3.3图像处理视频培训课程:该教程基于Python3.6+OpenCV新版本3.3.0详细讲述Python OpenCV图像处理部分内容,包括opencv人脸识别、人脸检测、数字验证码识别等内容。是Python开发者学习图像知识与应用开发佳实践课程。

    5435 人正在学习 去看看 贾志刚

图像处理库python skimage


skimage是和scipy、numpy可以完美结合的,PIL和numpy等结合不好。

from skimage import data
import matplotlib.pyplot as plt
 
camera = data.camera()
# 将图像前面10行的值赋为0
camera[:10] = 0
# 寻找图像中像素值小于87的像素点
mask = camera < 87
# 将找到的点赋值为255
camera[mask] = 255
# 建立索引
inds_x = np.arange(len(camera))
inds_y = (4 * inds_x) % len(camera)
# 对应索引的像素赋值为0
camera[inds_x, inds_y] = 0
 
# 获取图像的行数(高),列数(宽)
l_x, l_y = camera.shape[0], camera.shape[1]
# 建立网格坐标索引
X, Y = np.ogrid[:l_x, :l_y]
# 生成圆形的网格坐标
outer_disk_mask = (X - l_x / 2)**2 + (Y - l_y / 2)**2 > (l_x / 2)**2
# 对网格坐标赋0
camera[outer_disk_mask] = 0
 
# 建立figure的尺寸比例
plt.figure(figsize=(4, 4))
# 显示图像
plt.imshow(camera, cmap='gray', interpolation='nearest')
# 关掉图像的坐标
plt.axis('off')
plt.show()</code>

初识python图像处理

阅读数 4281

Python图像处理基础

阅读数 1199

没有更多推荐了,返回首页