OpenCV+TensorFlow 人工智能圖像處理 (1)

1. OpenCV初識

OpenCV是一個開源的計算機視覺庫,OpenCV是一個基於BSD許可(開源)發行的跨平臺計算機視覺庫,可以運行在Linux、Windows、Android和Mac OS操作系統上。它輕量級而且高效——由一系列 C 函數和少量 C++ 類構成,同時提供了Python、Ruby、MATLAB等語言的接口,實現了圖像處理和計算機視覺方面的很多通用算法。

主要應用場景:指紋識別,自動駕駛,人臉識別等。

2. Tensorflow 初識

TensorFlow是谷歌基於DistBelief進行研發的第二代人工智能學習系統,其命名來源於本身的運行原理。Tensor(張量)意味着N維數組,Flow(流)意味着基於數據流圖的計算,TensorFlow爲張量從流圖的一端流動到另一端計算過程。TensorFlow是將複雜的數據結構傳輸至人工智能神經網中進行分析和處理過程的系統。

3. Hello World

import tensorflow as tf
# 先運行,之後就有代碼提示了
hello = tf.constant('hello tensorflow!')
sess = tf.Session()
# 使用print時必須使用session
print(sess.run(hello))
b'hello tensorflow!'
import cv2
print('hello opencv!')
hello opencv!

4. 圖片的讀取和展示

# cv 讀取圖片, 先讀取圖片,在展示出來, 再暫停窗口
import cv2
img = cv2.imread('images/image0.jpg', 1) # 圖片的讀取,第二個參數表示讀取圖片的類型,0: gray圖   1: color圖
cv2.imshow('image', img) # 窗口的title, 需要展示的內容
cv2.waitKey(0)
1048603

5. OpenCV模塊組織結構

官網:https://opencv.org/

  • calib3d: 主要用於3D
  • core: 非常重要記錄了OpenCV的基礎數據類型,矩陣操作,繪圖相關
  • dnn: 神經網絡相關
  • features2d: 圖形焦點相關,如圖像匹配的時候需要使用
  • flann: 聚類相關
  • highgui: 圖形交互界面
  • imgcodecs, imgproc: 非常重要 圖形處理相關,如濾波器,直方圖統計,均衡化,集合變換,顏色處理
  • ml: 非常重要 機器學習模塊
  • objdetect: 物體檢測
  • photo: 非常重要 圖片處理,如,圖片修復,去噪
  • shape: 形狀
  • stitching: 拼接模塊,主要用於大圖像拼接
  • video, videoio, videostab: 視頻信息,視頻分解圖像,圖像合成視頻等

6. 圖像寫入

import cv2
# 1. 文件的讀取   2. 封裝格式解析   3. 數據解碼   4. 數據加載
img = cv2.imread('images/image0.jpg', 1)
# png jpg 這些都是文件的壓縮格式,通過壓縮格式使用對應的解碼器可以解碼圖片
cv2.imshow("image", img)

cv2.waitKey(0)
-1
import cv2
img = cv2.imread("images/image0.jpg", 1)
cv2.imwrite('images/image1.jpg', img) # 第一個參數是圖片的路徑,需要加上圖片的類型(拓展名)  第二個參數是寫入的數據
True

7. 不同質量圖片保存

import cv2
img = cv2.imread('images/image0.jpg', 1)
cv2.imwrite('images/imageTest.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 10]) # 第三個參數指定圖像寫入時的質量,質量範圍是0-100 【有損壓縮】
True
# 壓縮成png   png相比jpg的特點: png 無損壓縮, png可以設置圖像的透明度
import cv2
img = cv2.imread('images/image0.jpg', 1)
cv2.imwrite('images/imageTest.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 0]) # compression 壓縮比[0-9]
True

8. 像素相關

像素:組成圖片的元素,由1個RGB組成 RGB:組成顏色的元素,R: red, G: green, B: blue 顏色深度: 比如8bit的顏色深度: 可以表示0-255種顏色 圖片的寬高: 表示圖片在水平和垂直方向上有多少像素點 圖片大小計算: 1.14M = 720*547*3*8 bit / 8 (B) = 1.14M 寬, 高, RGB3個值, 顏色深度, 這裏bit要轉成B,再從B轉爲M PNG圖片大小: PNG圖片還有一個alpha通道,透明屬性通道 BGR: OpenCV種經常這樣表示, blue green red

9. 像素操作

import cv2
img = cv2.imread('images/image0.jpg', 1)
(b, g, r) = img[100, 100]  # BGR是一個元組格式
print(b, g, r)
# 在(10, 100) -> (110, 100)處繪製直線
# for i in range(100):
#     img[10+i, 100] = (255, 0, 0)
img[10:100, 100] = (255, 0, 0)
cv2.imshow("image", img)
cv2.waitKey(0) # 指定0,直到用戶輸入程序纔會繼續執行,如果指定1000, 程序會在1000ms=1s後繼續執行
39 46 49





-1

10. Tensorflow的常量與變量

import tensorflow as tf
# 常量
# data1 = tf.constant(2.5)
data1 = tf.constant(2, dtype=tf.int32)
# 變量
data2 = tf.Variable(10, name='var') # 變量的內容設置爲10, 變量name爲var
print (data1)
print (data2)
'''
sess = tf.Session()
print(sess.run(data1))
# 變量需要初始化之後才能使用
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(data2))
sess.close()
'''
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(data2))
Tensor("Const_7:0", shape=(), dtype=int32)
<tf.Variable 'var_6:0' shape=() dtype=int32_ref>
10

11. Tensorflow的工作機制

Tensorflow的實質:張量Tensor + 計算圖Graphs

12. tf的四則運算

# 常量
import tensorflow as tf
data1 = tf.constant(6)
data2 = tf.constant(2)
dataAdd = tf.add(data1, data2)
dataSub = tf.subtract(data1, data2)
dataMul = tf.multiply(data1, data2)
dataDiv = tf.divide(data1, data2)

with tf.Session() as sess:
    print(sess.run(dataAdd))
    print(sess.run(dataSub))
    print(sess.run(dataMul))
    print(sess.run(dataDiv))
8
4
12
3.0
# 變量
import tensorflow as tf
data1 = tf.constant(6)
data2 = tf.Variable(2)
dataAdd = tf.add(data1, data2)
# 數據拷貝
dataCopy = tf.assign(data2, dataAdd) # 把dataAdd的結果賦予給data2
dataSub = tf.subtract(data1, data2)
dataMul = tf.multiply(data1, data2)
dataDiv = tf.divide(data1, data2)
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(dataAdd))
    print(sess.run(dataSub))
    print(sess.run(dataMul))
    print(sess.run(dataDiv))
    print('sess.run(dataCopy)', sess.run(dataCopy))
    print('dataCopy.eval()', dataCopy.eval())   # 執行運算圖
    print('tf.get_default_session()', tf.get_default_session().run(dataCopy))
8
4
12
3.0
sess.run(dataCopy) 8
dataCopy.eval() 14
tf.get_default_session() 20

13. tf矩陣基礎

# 使用placehold, 先定義變量,後賦值
import tensorflow as tf
data1 = tf.placeholder(tf.float32)
data2 = tf.placeholder(tf.float32)
dataAdd = tf.add(data1, data2)
with tf.Session() as sess:
    print(sess.run(dataAdd, feed_dict={data1:6, data2: 2.2}))
    # feed_dice: 字典類型,給placehold賦值
8.2
# 矩陣
import tensorflow as tf
# 1行2列
data1 = tf.constant([[6, 6]])
# 2行1列
data2 = tf.constant([[2], [2]])
data3 = tf.constant([[3, 3]])
# 3x2
data4 = tf.constant([[1, 2], 
                     [3, 4], 
                     [5, 6]])
print(data4.shape) # 打印矩陣的緯度

with tf.Session() as sess:
    print(sess.run(data4))
    print(sess.run(data4[0, 1]))  # 中括號第一個表示行,第二個表示列
(3, 2)
[[1 2]
 [3 4]
 [5 6]]
2
# 矩陣的運算
import tensorflow as tf
data1 = tf.constant([[6, 6]])
data2 = tf.constant([[2], 
                     [2]])
data3 = tf.constant([[3, 3]])
data4 = tf.constant([[1, 2], 
                     [3, 4], 
                     [5, 6]])
matMul = tf.matmul(data1, data2)
matMul2 = tf.multiply(data1, data2)
matAdd = tf.add(data1, data3)
with tf.Session() as sess:
#     print(sess.run(matMul))
#     print(sess.run(matAdd))
#     print(sess.run(matMul2))
    print(sess.run([matMul, matAdd, matMul2]))
[array([[24]]), array([[9, 9]]), array([[12, 12],
       [12, 12]])]
# 特殊矩陣
import tensorflow as tf
mat0 = tf.constant([[0, 0, 0], [0, 0, 0]])
mat1 = tf.zeros([2, 14])
mat2 = tf.ones([3, 2])
mat3 = tf.fill([3, 2], 15) # 使用某個值填充
with tf.Session() as sess:
#     print(sess.run(mat0))
#     print(sess.run(mat1))
#     print(sess.run(mat2))
    print(sess.run(mat3))
[[15 15]
 [15 15]
 [15 15]]
import tensorflow as tf
mat1 = tf.constant([[2], [3], [4]])
mat2 = tf.zeros_like(mat1)
mat3 = tf.linspace(0.0, 2.0, 11)
mat4 = tf.random_uniform([2, 3], -1, 2) # 產生2x3的隨機矩陣,矩陣值範圍:[-1 - 2)
with tf.Session() as sess:
#     print(sess.run(mat2))
#     print(sess.run(mat3))
      print(sess.run(mat4))
[[ 0.44656682 -0.9664166  -0.21917105]
 [-0.62286747 -0.39322567 -0.81225216]]

14. Numpy基礎

import numpy as np
data1 = np.array([1, 2, 3, 4, 5])
print (data1)
[1 2 3 4 5]
data2 = np.array([[1, 2], [3, 4]])
print (data2)
print (data2.shape)
[[1 2]
 [3 4]]
(2, 2)
# zero ones
print (np.zeros([3, 2]))
print (np.ones([2, 2]))
[[0. 0.]
 [0. 0.]
 [0. 0.]]
[[1. 1.]
 [1. 1.]]
# 矩陣的修改與查找
data2[1, 0] = 6
print (data2)
print (data2[1, 1])
[[1 2]
 [6 4]]
4
# 基本運算
data3 = np.ones([2, 3])
print (data3 * 2) # 對應相乘
data4 = np.array([[1, 2, 3], [4, 5, 6]])
print (data3 + data4) # 矩陣對應相加
print (data3 * data4)
a = np.array([[1, 2], [2, 1]])
b = np.array([[1, 2], [2, 2]])
print (a * b)  # 對應元素相乘
print (a.dot(b)) # 矩陣的乘法
[[2. 2. 2.]
 [2. 2. 2.]]
[[2. 3. 4.]
 [5. 6. 7.]]
[[1. 2. 3.]
 [4. 5. 6.]]
[[1 2]
 [2 1]]
[[1 2]
 [2 1]]
[[1 4]
 [4 2]]
[[5 6]
 [4 6]]

15. Matplotlib基礎

import numpy as np
import matplotlib.pyplot as plt
# 折線圖
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array([3, 7, 5, 6, 2, 4, 1, 8])
plt.plot(x, y, 'b') # 繪製折線圖  x y 顏色
plt.plot(x, y+6, 'g', lw=10) # lw 線條的寬度(line width)
[<matplotlib.lines.Line2D at 0x7f660c1fccf8>]
# 柱狀圖
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array([13, 17, 15, 16, 12, 14, 11, 18])
plt.bar(x, y, 0.5, alpha=0.5, color='b') # 第三個參數:每個柱子的寬度,佔一格的百分數  alpha:透明度,保存png圖片的時候纔有效
<BarContainer object of 8 artists>
# 餅圖
labels = ['p1', 'p2', 'p3']
sizes = [60, 30, 10]
colors = ['red', 'green', 'blue']
plt.pie(sizes, labels=labels, colors=colors,
        labeldistance = 1.1,autopct = '%3.1f%%',shadow = False,
        startangle = 90,pctdistance = 0.6)
#labeldistance,文本的位置離遠點有多遠,1.1指1.1倍半徑的位置
#autopct,圓裏面的文本格式,%3.1f%%表示小數有三位,整數有一位的浮點數
#shadow,餅是否有陰影
#startangle,起始角度,0,表示從0開始逆時針轉,爲第一塊。一般選擇從90度開始比較好看
#pctdistance,百分比的text離圓心的距離
#patches, l_texts, p_texts,爲了得到餅圖的返回值,p_texts餅圖內部文本的,l_texts餅圖外label的文本
([<matplotlib.patches.Wedge at 0x7f66004ee240>,
  <matplotlib.patches.Wedge at 0x7f66004ee9b0>,
  <matplotlib.patches.Wedge at 0x7f6600476198>],
 [Text(-1.04616,-0.339919,'p1'),
  Text(1.1,2.05979e-07,'p2'),
  Text(0.339918,1.04616,'p3')],
 [Text(-0.570634,-0.18541,'60.0%'),
  Text(0.6,1.12352e-07,'30.0%'),
  Text(0.18541,0.570634,'10.0%')])

16. 實戰:人工神經網絡逼近股票收盤均價

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

# y軸表示日期
date = np.linspace(1, 15, 15)
# 收盤價
endPrice = np.array([2511.90,2538.26,2510.68,2591.66,2732.98,2701.69,2701.29,2678.67,2726.50,2681.50,2739.17,2715.07,2823.58,2864.90,2919.08])
# 開盤價
startPrice = np.array([2438.71,2500.88,2534.95,2512.52,2594.04,2743.26,2697.47,2695.24,2678.23,2722.13,2674.93,2744.13,2717.46,2832.73,2877.40])
# 繪圖
plt.figure()
for i in range(15):
    # 柱狀圖
    dataOne = np.zeros([2])
    dataOne[0] = i
    dataOne[1] = i
    priceOne = np.zeros([2])
    priceOne[0] = startPrice[i]
    priceOne[1] = endPrice[i]
    if endPrice[i] > startPrice[i]:
        plt.plot(dataOne, priceOne, 'r', lw=8)
    else:
        plt.plot(dataOne, priceOne, 'g', lw=8)
# 搭建神經網絡
# 輸入日期,輸出股價
# A(15*1) * w1(1*10) + b1(1*10) = B(15*10)
# B(15*10) * w2(10*1) + b2(15*1) = C(15*1)
# 爲了計算方便,將日期進行歸一化
dateNormal = np.zeros([15, 1])
priceNormal = np.zeros([15, 1])
for i in range(15):
    dateNormal[i] = i / 14.0
    priceNormal[i] = endPrice[i] / 3000.0

# 定義輸入層
x = tf.placeholder(tf.float32, [None, 1]) # 表面n行1列
y = tf.placeholder(tf.float32, [None, 1])

# 定義隱藏層
w1 = tf.Variable(tf.random_uniform([1, 10], 0, 1)) # 創建w1, 初始數據在0~1範圍內, 因爲神經網絡需要對其進行更新,所以是變量
b1 = tf.Variable(tf.zeros([1, 10]))
# 定義一個操作
wb1 = tf.matmul(x, w1) + b1
layer1 = tf.nn.relu(wb1) # 激勵函數

# 定義輸出層
w2 = tf.Variable(tf.random_uniform([10, 1], 0, 1))
b2 = tf.Variable(tf.zeros([15, 1]))
wb2 = tf.matmul(layer1, w2) + b2
layer2 = tf.nn.relu(wb2)

# 定義神經網絡輸出與實際值的差異,爲了調整循環次數
loss = tf.reduce_mean(tf.square(y-layer2)) # y是真實值  這行代碼實際是運算了標準差
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) # 梯度下降,步長,最小化loss

# 運行神經網絡
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer()) # 變量初始化
    for i in range(10000):
        sess.run(train_step, feed_dict={x:dateNormal, y:priceNormal})
    pred = sess.run(layer2, feed_dict={x:dateNormal})
    predPrice = np.zeros([15, 1])
    for i in range(15):
        predPrice[i] = pred[i]*3000
plt.plot(date, predPrice, 'b', lw=2)
plt.plot(date, endPrice, 'g', lw=1)
[<matplotlib.lines.Line2D at 0x7fef4481f908>]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章