Python画图工具类库matplotlib

前言

关于matplotlib,先看看matplotlib github怎么说?
Matplotlib is a Python 2D plotting library which produces publication-quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shell (à la MATLAB or Mathematica), web application servers, and various graphical user interface toolkits.
翻译过来就是:Matplotlib是一个Python 2D绘图库,可以跨平台生成各种硬拷贝格式和交互式环境的出版品质量图。 Matplotlib可用于Python脚本,Python和IPython shell(àla MATLAB或Mathematica),Web应用程序服务器和各种图形用户界面工具包。
就是一个python自带的一个绘图工具库,这是其api地址: http://matplotlib.org/api/pyplot_api.html

基本使用

导入

import matplotlib.pyplot as plt

显示图像

分析:显示图片不外乎两个步骤,读取和显示。

读取(cv2)
img = cv2.imread(image_path)
显示
 plt.imshow(img)
 plt.show()

这里写图片描述
这是最简单的几行代码,当然我给出了一下源码:

############################################################################
# -*- coding:utf8 -*-                                                      #
# created by tengxing on 2017.5.19                                         #
# mail tengxing7452@163.com                                                #
# github github.com/tengxing                                               #
# description Matplot画图  显示图片                                          #
############################################################################

import matplotlib.pyplot as plt
import cv2
import os

image_path = "./data/008.jpg"


# 显示一张图片
def show(image_path):
    img = cv2.imread(image_path)
   # plt.figure(image_path[-7:])  # 创建图表,截取字符
    plt.imshow(img) #载入图片
    #plt.title(image_path[-7:-4])
    #plt.axis("off") # 关闭坐标
    plt.show() # 显示图片
    return
 show(image_path)

下面做一个测试显示一个文件夹下的所有文件:

# 显示文件夹下的图片
def showDir(dir):
    images = eachFile(dir)
    plt.figure(dir, figsize=(15, 15))
    for i, name in enumerate(images):
        # show(name)
        img = cv2.imread(name)
        plt.subplot(2, 2, i+1) # A grid of 2 rows x 2 columns
        plt.axis('off')
        plt.imshow(img)
        plt.title(name[-7:-4])
    plt.show()
    return


# 遍历指定目录
def eachFile(filepath):
    pathDir = os.listdir(filepath)
    result = []
    for allDir in pathDir:
        child = os.path.join('%s/%s' % (filepath, allDir))
        result.append(child)
    return result

这里写图片描述

基本图形

我经常使用matplotlib来显示图像,除了图像,还有很多的图像方法可以来绘制很多的图形。下面我将介绍使用matplotlib绘制 三角函数,饼状图,柱状图,离散图。这些其实都很简单,都是使用相对应的方法,加入图所需要的参数即可,和WEB前端类库D3.js思想一样。

def base_graph():
    # 1D data
    x = [1, 2, 3, 4, 5]
    y = [2.3, 3.4, 1.2, 6.6, 7.0]

    plt.figure("基础图形",figsize=(12, 6))

    plt.subplot(231)
    plt.plot(x, y)
    plt.title("plot")

    plt.subplot(232)
    plt.scatter(x, y)
    plt.title("scatter")

    plt.subplot(233)
    plt.pie(y)
    plt.title("pie")

    plt.subplot(234)
    plt.bar(x, y)
    plt.title("bar")

    plt.show()
base_graph()

效果如下:
这里写图片描述

绘制动态图

以上的图像都是静态的,如果实际情况是动态的呢?matplotlib下的animation模块(处理图像动态更新)解决了这个问题。原理就是:初始块和更新块按照时间加载即可。

初始块

创建动画发生时调用的函数

    def init():
        line.set_data([], [])
        line2.set_data([], [])
        return line, line2

更新块

每次心跳更新的函数 说明:下面会用到numpy,没有安装np的请执行如下命令安装

apt-get install python-numpy

关于np在github是这样介绍的:NumPy is the fundamental package needed for scientific computing with Python
非常强大的科学计算库,做图像处理,机器学习的朋友就不陌生了。

    def update(i):
        print i
        x = np.linspace(0, 2, 100) # 等差数列
        y = np.sin(2 * np.pi * (x - 0.01 * i))
        line.set_data(x, y)

FuncAnimation

通过一个函数将初始块,更新块连接起来就可以了。

    anim1 = animation.FuncAnimation(fig, update, init_func=init, frames=500, interval=10)

这里写图片描述

结束语

从上面的代码就可以看出来,函数式绘制是matplotlib的核心思想,就像D3.js类库,用起来非常方便。但是区别一下,这个虽然和matlab语法相像,就是不能说是MATLAB, 虽然matlab可以算作脚本语言,说到底还是软件,而matplotlib本质上还是构建对象来构建图像,函数式编程将构建对象的过程封装在函数中,从而让我们觉得很方便。
说到这里,突然想起文中提到的numpy,还是截图一张吧
这里写图片描述

代码托管github

参考

  • 2
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值