OpenCV(2)numpy+tensorflow+matplotlib基礎
阿新 • • 發佈:2018-12-24
(1)numpy基礎
import numpy as np
#定義全零矩陣
image = np.zeros((480,640,3),np.uint8)) #可用於表示640*480的彩色圖矩陣
#定義線性增長矩陣
x = np.linspace(0,100,101) #0到100的一維矩陣
#矩陣相乘
y = np.matmul(x1,x2)
(2)tensorflow基礎
import tensorflow as tf #建立常量 x1 = tf.constant(5,dtype = tf.int32) #建立變數 x2 = tf.Variable(10,dtype = tf.int32) x3 = tf.Variable(tf.random_uniform([4,4],0,1,tf.float32)) #建立特殊矩陣 x4 = tf.zeros([3,4]) #定義三行四列零矩陣 x5 = tf.fill([3,4],10) #定義全為10的三行四列矩陣 x6 = tf.linspace(0,10,11) x7 = tf.zeros_like(x4) #定義維度和x4一樣的零矩陣 #執行張量 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(x1)) print(sess.run(x2)) print(sess.run(x3))
(3) matplotlib基礎
繪製折線圖、柱狀圖
import matplotlib.pyplot as plt
x = np.array([1,2,3,4,5])
y = np.array([2,4,6,8,10])
#折線圖
plt.plot(x,y,"r",lw=2) #"r"代表顏色 lw為線條粗細
plt.figure()
#柱狀圖
plt.bar(x,y,1,alpha=1,color="r")
plt.show()
綜合:利用matplotlib繪製圖片直方圖
import cv2 as cv import matplotlib.pyplot as plt import numpy as np img = cv.imread("dog.jpg",1) (height,width,deep) = img.shape count = np.zeros(256,np.float) color = ["b", "g", "r"] for k in range(3): #遍歷3通道 for i in range(height): for j in range(width): index = img[i,j,k] count[index] += 1 #歸一化:遍歷計算每個畫素值出現的概率 for h in range(256): count[h] = count[h]/(height*width) plt.figure() #新增視窗 #plt.bar繪製柱狀圖 1、x軸 2、y軸 3、寬度 plt.bar(x=range(256),height=count,width=1,alpha=1,color=color[k]) plt.show()