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, "-
'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
閱讀更多 理思錄 的文章