百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python 绘图以及文件的基本操作(python3绘图)

off999 2024-09-26 16:07 13 浏览 0 评论


Python 绘图以及文件的基本操作

https://pypi.org/

Python Package Index (PyPI)

Python 绘图库 Matplotlib CMD 以管理员身份运行

pip install -U pip setuptoolspip install matplotlib

import numpy as np from matplotlib import pyplot as plt x = np.arange(1,11) y = 2 * x + 5 plt.title("Matplotlib demo") plt.xlabel("x axis caption") plt.ylabel("y axis caption") plt.plot(x,y) plt.show()

https://matplotlib.org/

https://matplotlib.org/tutorials/index.html#introductory

import matplotlib.pyplot as pltimport numpy as npx = np.linspace(0, 2, 100)

plt.plot(x, x, label='linear')plt.plot(x, x**2, label='quadratic')plt.plot(x, x**3, label='cubic')

plt.xlabel('x label')plt.ylabel('y label')

plt.title("Simple Plot")

plt.legend()

plt.show()

https://matplotlib.org/tutorials/introductory/usage.html#sphx-glr-tutorials-introductory-usage-py


numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

增加中文的支持:#coding=utf-8

#coding=utf-8import matplotlib.pyplot as pltplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签plt.rcParams['axes.unicode_minus']=False #用来正常显示负号import numpy as npx = np.linspace(-2, 2, 200)

plt.plot(x, x, label='y=x')plt.plot(x, x**2, label='y=x^2')plt.plot(x, x**3, label='y=x^3')

plt.xlabel('x 轴')plt.ylabel('y 轴')

plt.title("简单绘图")

plt.legend()

plt.show()

np.arange()函数返回一个有终点和起点的固定步长的排列,如[1,2,3,4,5],起点是 1,终点是 5,步长为1。参数个数情况: np.arange()函数分为一个参数,两个参数,三个参数三种情况1)一个参数时,参数值为终点,起点取默认值 0,步长取默认值 1。2)两个参数时,第一个参数为起点,第二个参数为终点,步长取默认值 1。3)三个参数时,第一个参数为起点,第二个参数为终点,第三个参数为步长。其中步长支持小数

#coding=utf-8import matplotlib.pyplot as pltimport matplotlib.pyplot as plt1plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签plt.rcParams['axes.unicode_minus']=False #用来正常显示负号import numpy as npx = np.linspace(-2, 2, 200)y=np.sin(x)plt.plot(x, x, label='y=x')plt.plot(x, x**2, label='y=x^2')plt.plot(x, x**3, label='y=x^3')

plt.xlabel('x 轴')plt.ylabel('y 轴')

plt.title("简单绘图")


plt.legend()plt1.plot(x,y)

plt.show()plt1.show()

python 可视化库 matplotlib 的显示模式默认为阻塞(block)模式 plt.show() 之后不会执行

plt.ion()这个函数,使matplotlib的显示模式转换为交互(interactive)模式 plt.show() 之后继续执行

plt.ioff()关闭交互模式plt.ion()打开交互模式

import matplotlib.pyplot as pltplt.ion()plt.plot([1.6, 2.7])plt.plot([3, 2])

# 创建一个画布plt.figure()# 在 figure 下线plt.plot(x, y1, "-o") #实线plt.plot(x, y2, "--o") #虚线plt.plot(x, y3, "-.o") #虚点线plt.plot(x, y4, ":o") # 点线# 展现画布plt.show()

plt.plot(x, y1, "-.") # 点plt.plot(x, y2, "-,") # 像素点plt.plot(x, y3, "-o") # 圆点

'^' 上三角点'v' 下三角点'<' 左三角点'>' 右三角点

plt.plot(x, y1, "-^")plt.plot(x, y2, "-v")plt.plot(x, y3, "-<")plt.plot(x, y4, "→")

'1' 下三叉点'2' 上三叉点'3' 左三叉点


'4' 右三叉点

plt.plot(x, y1, "-1")plt.plot(x, y2, "-2")plt.plot(x, y3, "-3")plt.plot(x, y4, "-4")

's' 正方点'p' 五角点'*' 星形点'h' 六边形 1'H' 六边形 2

plt.plot(x, y1, "-s")plt.plot(x, y2, "-p")plt.plot(x, y3, "-*")plt.plot(x, y4, "-h")plt.plot(x, y5, "-H")

'+' 加号点'x' 乘号点'D' 实心菱形点'd' 细菱形点'_' 横线点'|' 竖线点

plt.plot(x, y1, "-+")plt.plot(x, y2, "-x")plt.plot(x, y3, "-D")plt.plot(x, y4, "-d")plt.plot(x, y5, "-_")

color="green" 指定颜色为绿色

linestyle="dashed" 指定线形为 dashed 类型

marker="o" 指定标记类型为 o 点

markerfacecolor="blue"指定标记的颜色为蓝色

markersize=20 指定标记的大小为 20

plt.plot(x, y1, "-P")plt.plot(x, y2, "-|")plt.plot(x, y3, color="#000000")plt.plot(x, y4, "-o", markersize=20)plt.plot(x, y5, "-^", markerfacecolor="blue")


散点图plt.scatter(x, y, s, c ,marker, alpha)

x,y: x 轴与 y 轴的数据

s: 点的面积

c: 点的颜色

marker: 点的形状

alpha: 透明度

随机数x = np.random.randn(N)y2 = x + np.random.randn(N)*0.5

1.plot(x, y, marker='D')表示绘制折线图,marker 设置样式菱形。

2.scatter(x, y, marker='s', color='r')绘制散点图,红色正方形。 3.bar(x, y, 0.5, color='c')绘制柱状图,间距为 0.5,原色。 4.hist(data,40,normed=1,histtype='bar', facecolor='yellowgreen',alpha=0.75)直方图。 5.设置 x 轴和 y 轴的坐标值: xlim(-2.5, 2.5) #设置 x 轴范围 ylim(-1, 1) #设置 y 轴范围 6.显示中文和负号代码如下: plt.rcParams['font.sas-serig']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

from matplotlib import pyplot as pltimport numpy as npimport mathx=np.linspace(-10,10,100)

fig = plt.figure()ax1 = fig.add_subplot(231)plt.plot(x,x)plt.sca(ax1)ax2 = fig.add_subplot(232)plt.plot(x,x*x)plt.sca(ax2)ax3 = fig.add_subplot(233)plt.plot(x,x**3)plt.sca(ax3)ax4 = fig.add_subplot(234)plt.plot(x,np.sin(x))


plt.sca(ax4)ax5 = fig.add_subplot(235)plt.plot(x,np.cos(x))plt.sca(ax5)ax6 = fig.add_subplot(236)plt.plot(x,x*x+x**3)plt.sca(ax6)plt.grid(True)plt.show()


Python 的输入输出,文件目录小结

1,键盘输入

2,打印输出(显示器输出)

3,文件夹的建立

4,文件夹的命名

5,文件夹的删除

6,文件的删除

7,文件的输入

8,文件的输出

1,键盘输入str01=input("Please input a string:")print(str01)

将输入的字符串转换为整数

str01=input("Please input a string:")a=int(str01)b=a+10print(str01)print(a)print(b)


2,打印输出(显示器输出)

3,文件夹的建立

在 C 盘根目录下建立名为 pytest 的文件夹:

import osos.chdir("c:/")os.mkdir("pytest")


import osos.chdir("c:/")os.mkdir("pytest1")os.chdir("/pytest1")a=os.getcwd()print(a)


4,文件夹的命名os.rename( "test1.txt", "test2.txt" )

5,文件夹的删除os.rmdir("pytest1"): 删除文件夹

6,文件的删除import osos.chdir("c:/")os.chdir("/pytest1")a=os.getcwd()print(a)os.remove("a.txt")os.chdir("c:/")


os.rmdir("pytest1")

os.remove("a.txt"): 删除文件


getcwd()方法显示当前的工作目录

7,文件的输入

# 打开一个文件fp = open("c:/pytest/a.txt", "r+")print("文件名: ", fp.name)print("是否已关闭 : ", fp.closed)print("访问模式 : ", fp.mode)str=fp.read(5)fp.close()print(str)


建立一个空的文件 a.txt 供程序调用。

8,文件的输出

# 打开一个文件fp = open("c:/pytest/a.txt", "w")print("文件名: ", fp.name)print("是否已关闭 : ", fp.closed)print("访问模式 : ", fp.mode)


fp.write("hello,python");fp.close()


OPENCV & python & 机器视觉

https://docs.opencv.org/4.2.0/d6/d00/tutorial_py_root.html

软件安装

首先安装 python


Numpy package (for example, using pip install numpy command).

Matplotlib (pip install matplotlib) (Matplotlib is optional, but recommended since we use it a lot in our tutorials).


之前已经安装过了。

小知识:如何查找 python 环境中安装了什么?命令:pip list


确认 numpy 是正确安装并可以使用。

https://sourceforge.net/projects/opencvlibrary/files/4.2.0/opencv-4.2.0-vc14_vc15.exe/download

下载并解压

C:\opencv001\opencv\build\python\cv2\python-3.8

复制文件 cv2.pyd 到 C:\Python\Python38\Lib\site-packages 中


以上官方提供的方法可能会由于版本的不匹配不能安装,此时用下面的语句安装:

pip install opencv_python


输入 import cv2 出现如上图所示,表明安装完毕。

测试功能:打开图像文件 c:/a.jpg


原图为彩色图像,打开为黑白图像。

代码如下:import numpy as npimport cv2 as cvimg=cv.imread('c:/a.jpg',0)cv.imshow('image',img)cv.waitKey(0)cv.destroyAllWindows()


img=cv.imread('c:/a.jpg',0) 的参数含义:1:表示彩色, 0:表示灰度 or -1 cv.IMREAD_COLOR : Loads a color image. Any transparency of image will be neglected. It is the default flag.

cv.IMREAD_GRAYSCALE : Loads image in grayscale mode

cv.IMREAD_UNCHANGED : Loads image as such including alpha channel


彩色图像

将图像写入文件中

import numpy as npimport cv2 as cvimg=cv.imread('c:/a.jpg',0)cv.imwrite('c:/a1.jpg',img)cv.imshow('image',img)cv.waitKey(0)cv.destroyAllWindows()


原来彩色的图像,变成了灰度的图像了,这个可以作为图像转换的小应用。

使用 Matplotlib 库进行图像的显示,更多的显示方法,更多的参数选择,比如放大等


代码如下:

import numpy as npimport cv2 as cvfrom matplotlib import pyplot as plt

img=cv.imread('c:/a.jpg',0)plt.imshow(img,cmap='gray',interpolation='bicubic')plt.xticks([]),plt.yticks([])plt.show()

https://matplotlib.org/api/pyplot_api.html


https://blog.csdn.net/du_shuang/article/details/84111250

视频流的获取

import numpy as npimport cv2 as cvcap = cv.VideoCapture(0)if not cap.isOpened(): print("Cannot open camera") exit()while True: # Capture frame-by-frame ret, frame = cap.read() # if frame is read correctly ret is True if not ret: print("Can't receive frame (stream end?). Exiting ...") break # Our operations on the frame come here gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # Display the resulting frame cv.imshow('frame', gray) if cv.waitKey(1) == ord('q'): break# When everything done, release the capturecap.release()cv.destroyAllWindows()


CV_GRAY2RGB是 gray到RGB CV_BGR2GRAY, CV_RGB2GRAY, CV_GRAY2BGR, CV_GRAY2RGB

色彩空间转换的模式,该 code来实现不同类型的颜色空间转换。比如CV_BGR2GRAY表示转换为灰度图,CV_BGR2HSV将图片从RGB空间转换为HSV空间。其中当 code选用CV_BGR2GRAY时,dst需要是单通道图片。当 code选用CV_BGR2HSV时,对于 8位图,需要将RGB值归一化到 0-1之间。这样得到HSV图中的H范围才是 0-360,S和V的范围是 0-1

1、RGB和 BGR(opencv默认的彩色图像的颜色空间是 BGR)颜色空间的转换

cv::COLOR_BGR2RGBcv::COLOR_RGB2BGRcv::COLOR_RGBA2BGRAcv::COLOR_BGRA2RGBA

2、向RGB和 BGR图像中增添 alpha通道

cv::COLOR_RGB2RGBAcv::COLOR_BGR2BGRA

3、从RGB和 BGR图像中去除 alpha通道

cv::COLOR_RGBA2RGBcv::COLOR_BGRA2BGR

4、从RBG和 BGR颜色空间转换到灰度空间

cv::COLOR_RGB2GRAYcv::COLOR_BGR2GRAY

cv::COLOR_RGBA2GRAYcv::COLOR_BGRA2GRAY

5、从灰度空间转换到 RGB和 BGR颜色空间

cv::COLOR_GRAY2RGBcv::COLOR_GRAY2BGR

cv::COLOR_GRAY2RGBAcv::COLOR_GRAY2BGRA


6、RGB和 BGR颜色空间与 BGR565颜色空间之间的转换

cv::COLOR_RGB2BGR565cv::COLOR_BGR2BGR565cv::COLOR_BGR5652RGBcv::COLOR_BGR5652BGRcv::COLOR_RGBA2BGR565cv::COLOR_BGRA2BGR565cv::COLOR_BGR5652RGBAcv::COLOR_BGR5652BGRA

7、灰度空间域BGR565之间的转换

cv::COLOR_GRAY2BGR555cv::COLOR_BGR5552GRAY

8、RGB和 BGR颜色空间与 CIE XYZ之间的转换

cv::COLOR_RGB2XYZcv::COLOR_BGR2XYZcv::COLOR_XYZ2RGBcv::COLOR_XYZ2BGR

9、RGB和 BGR颜色空间与 uma色度(YCrCb空间)之间的转换

cv::COLOR_RGB2YCrCbcv::COLOR_BGR2YCrCbcv::COLOR_YCrCb2RGBcv::COLOR_YCrCb2BGR

10、RGB和 BGR颜色空间与 HSV颜色空间之间的相互转换

cv::COLOR_RGB2HSVcv::COLOR_BGR2HSVcv::COLOR_HSV2RGBcv::COLOR_HSV2BGR

11、RGB和 BGR颜色空间与 HLS颜色空间之间的相互转换

cv::COLOR_RGB2HLScv::COLOR_BGR2HLScv::COLOR_HLS2RGBcv::COLOR_HLS2BGR

12、RGB和 BGR颜色空间与 CIE Lab颜色空间之间的相互转换


cv::COLOR_RGB2Labcv::COLOR_BGR2Labcv::COLOR_Lab2RGBcv::COLOR_Lab2BGR

13、RGB和 BGR颜色空间与 CIE Luv颜色空间之间的相互转换

cv::COLOR_RGB2Luvcv::COLOR_BGR2Luvcv::COLOR_Luv2RGBcv::COLOR_Luv2BGR

14、Bayer格式(raw data)向RGB或BGR颜色空间的转换

cv::COLOR_BayerBG2RGBcv::COLOR_BayerGB2RGBcv::COLOR_BayerRG2RGBcv::COLOR_BayerGR2RGBcv::COLOR_BayerBG2BGRcv::COLOR_BayerGB2BGRcv::COLOR_BayerRG2BGRcv::COLOR_BayerGR2BGR

彩色的视频捕捉

import numpy as npimport cv2 as cvcap = cv.VideoCapture(0)if not cap.isOpened(): print("Cannot open camera") exit()while True: # Capture frame-by-frame ret, frame = cap.read() # if frame is read correctly ret is True if not ret: print("Can't receive frame (stream end?). Exiting ...") break cv.imshow("Video",frame) if cv.waitKey(1) == ord('q'): break# When everything done, release the capturecap.release()


cv.destroyAllWindows()


  • Python 绘图库 Matplotlib


相关推荐

软件测试|Python requests库的安装和使用指南

简介requests库是Python中一款流行的HTTP请求库,用于简化HTTP请求的发送和处理,也是我们在使用Python做接口自动化测试时,最常用的第三方库。本文将介绍如何安装和使用request...

python3.8的数据可视化pyecharts库安装和经典作图,值得收藏

1.Deepin-linux下的python3.8安装pyecharts库(V1.0版本)1.1去github官网下载:https://github.com/pyecharts/pyecharts1...

我在安装Python库的时候一直出这个错误,尝试很多方法,怎么破?

大家好,我是皮皮。一、前言前几天在Python星耀群【我喜欢站在一号公路上】问了一个Python库安装的问题,一起来看看吧。下图是他的一个报错截图:二、实现过程这里【对不起果丹皮】提示到上图报错上面说...

自动化测试学习:使用python库Paramiko实现远程服务器上传和下载

前言测试过程中经常会遇到需要将本地的文件上传到远程服务器上,或者需要将服务器上的文件拉到本地进行操作,以前安静经常会用到xftp工具。今天安静介绍一种python库Paramiko,可以帮助我们通过代...

Python 虚拟环境管理库 - poetry(python虚拟环境virtualenv)

简介Poetry是Python中的依赖管理和打包工具,它允许你声明项目所依赖的库,并为你管理它们。相比于Pipev,我觉得poetry更加清爽,显示更友好一些,虽然它的打包发布我们一般不使...

pycharm(pip)安装 python 第三方库,时下载速度太慢咋办?

由于pip默认的官方软件源服务器在国外,所以速度慢,导致下载时间长,甚至下载会频繁中断,重试次数过多时会被拒绝。解决办法1:更换国内的pip软件源即可。pip指定软件源安装命令格式:pipinsta...

【Python第三方库安装】介绍8种情况,这里最全看这里就够了!

**本图文作品主要解决CMD或pycharm终端下载安装第三方库可能出错的问题**本作品介绍了8种安装方法,这里最全的python第三方库安装教程,简单易上手,满满干货!希望大家能愉快地写代码,而不要...

python关于if语句的运用(python中如何用if语句)

感觉自己用的最笨的方式来解这道题...

Python核心技术——循环和迭代(上)

这次,我们先来看看处理查找最大的数字问题上,普通人思维和工程师思维有什么不一样。例如:lst=[3,6,10,5,7,9,12]在lst列表中寻找最大的数字,你可能一眼能看出来,最大值为...

力扣刷题技巧篇|程序员萌新如何高效刷题

很多新手初刷力扣时,可能看过很多攻略,类似于按照类型来刷数组-链表-哈希表-字符串-栈与队列-树-回溯-贪心-动态规划-图论-高级数据结构之类的。可转念一想,即...

“千万别学我!从月薪3000到3万,我靠这3个笨方法逆袭”

3年前,我还在为房租而忧心忡忡,那时月薪仅有3000元;如今,我的月收入3万!很多人都问我是如何做到的,其实关键就在于3个步骤。今天我毫无保留地分享给大家,哪怕你现在工资低、缺乏资源,照着做也能够实...

【独家攻略】Anaconda秒建PyTorch虚拟环境,告别踩坑,小白必看

目录一.Pytorch虚拟环境简介二.CUDA简介三.Conda配置Pytorch环境conda安装Pytorch环境conda下载安装pytorch包测试四.NVIDIA驱动安装五.conda指令一...

入门扫盲:9本自学Python PDF书籍,让你避免踩坑,轻松变大神!

工作后在学习Python这条路上,踩过很多坑。今天给大家推荐9本自学Python,让大家避免踩坑。入门扫盲:让你不会从一开始就从入门到放弃1《看漫画学Python:有趣、有料、好玩、好用》2《Pyth...

整蛊大法传授于你,不要说是我告诉你的

大家好,我是白云。给大家整理一些恶搞代码,谨慎使用!小心没朋友。1.电脑死机打开无数个计算器,直到死机setwsh=createobject("wscript.shell")do...

python 自学“笨办法”7-9章(笨办法学python3视频)

笨办法这本书,只强调一点,就是不断敲代码,从中增加肌肉记忆,并且理解和记住各种方法。第7章;是更多的打印,没错就是更多的打印第八章;打印,打印,这次的内容是fomat的使用与否f“{}{}”相同第九...

取消回复欢迎 发表评论: