Python圖像處理常用代碼,numpy教程

這裏的代碼是截取的我的代碼片段,或許難以閱讀,有不理解的地方歡迎交流


  • 生成空列表及末尾添加
x=[]
x.append(img_path[j])
  • 圖像矩陣和一維數組轉化
img_ndarray=numpy.asarray(img,dtype='float64')/256  #將圖像轉化爲數組並將像素轉化到0-1之間
data[d-1]=numpy.ndarray.flatten(img_ndarray)    #將圖像的矩陣形式轉化爲一維數組保存到data中
  • 將矩陣中浮點數轉化爲int類型
data_label=data_label.astype(numpy.int)  #將標籤轉化爲int類型
  • Python生成一個範圍內的隨機整數。其中參數a是下限,參數b是上限
print random.randint(12, 20) #生成的隨機數n: 12 <= n <= 20

numpy教程

y = 2.5
print type(y) # 輸出 "<type 'float'>"
print y ** 2 # 輸出 "6.25"
#Python中沒有 x++ 和 x-- 的操作符。

#布爾型:Python用英語實現了所有的布爾邏輯,而不是操作符(&&和||等)。
t = True
f = False
print type(t) # 輸出 "<type 'bool'>"
print t and f # 邏輯與 AND; prints "False"
print t or f  # 邏輯或 OR; prints "True"
print not t   # 邏輯非 NOT; prints "False"
print t != f  # 邏輯異或 XOR; prints "True"  

#字符串:Python對字符串的支持非常棒。
hello = 'hello'   # 字符串可以用單引號,也可以用雙引號
world = "world"   
print hello       # Prints "hello"
print len(hello)  # 字符串長度 prints "5"
hw = hello + ' ' + world  # 字符串連接
print hw  # prints "hello world"
hw12 = '%s %s %d' % (hello, world, 12)  # 格式化輸出
print hw12  # prints "hello world 12"

#字符串對象有一系列有用的方法,比如:
s = "hello"
print s.capitalize()  # 首字母大寫; prints "Hello"
print s.upper()       # 全部大寫; prints "HELLO"
print s.rjust(7)      # 右端對齊; prints "  hello"
print s.center(7)     # 中間對齊; prints " hello "
print s.replace('l', '(ell)')  # 字符串中字符替換; prints "he(ell)(ell)o"
print '  world '.strip()  # 去除首尾空格; prints "world"

1. 數組Arrays

  • 創建數組

import numpy as np

#一維數組
a = np.array([1, 2, 3])  
print type(a)            # Prints "<type 'numpy.ndarray'>"
print a.shape            # Prints "(3,)"
print a[0], a[1], a[2]   # Prints "1 2 3"
a[0] = 5                 # 改變數組中元素
print a                  # Prints "[5, 2, 3]"

#二維數組
b = np.array([[1,2,3],[4,5,6]])   
print b.shape                     # Prints "(2, 3)"
print b[0, 0], b[0, 1], b[1, 0]   # Prints "1 2 4"

#其他一些建立數組方法

a = np.zeros((2,2))  # Create an array of all zeros
print a              # Prints "[[ 0.  0.]
                     #          [ 0.  0.]]"

b = np.ones((1,2))   # Create an array of all ones
print b              # Prints "[[ 1.  1.]]"

c = np.full((2,2), 7) # Create a constant array
print c               # Prints "[[ 7.  7.]
                      #          [ 7.  7.]]"

d = np.eye(2)        # Create a 2x2 identity matrix
print d              # Prints "[[ 1.  0.]
                     #          [ 0.  1.]]"

e = np.random.random((2,2)) # Create an array filled with random values
print e                     # Might print "[[ 0.91940167  0.08143941]
                            #               [ 0.68744134  0.87236687]]"
  • 訪問數組
import numpy as np

# 創建shape (3, 4)的二維數組
# [[ 1  2  3  4]
#  [ 5  6  7  8]
#  [ 9 10 11 12]]
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

b = a[:2, 1:3]
# [[2 3]
#  [6 7]]

print a[0, 1]   # Prints "2"
b[0, 0] = 77    # b[0, 0] 和 a[0, 1]是同一個數據
print a[0, 1]   # Prints "77"

row_r1 = a[1, :]   
row_r2 = a[1:2, :]  
print row_r1, row_r1.shape  # Prints "[5 6 7 8] (4,)"
print row_r2, row_r2.shape  # Prints "[[5 6 7 8]] (1, 4)"

col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print col_r1, col_r1.shape  # Prints "[ 2  6 10] (3,)"
print col_r2, col_r2.shape  # Prints "[[ 2]
                            #          [ 6]
                            #          [10]] (3, 1)"

a = np.array([[1,2], [3, 4], [5, 6]])
print a[[0, 1, 2], [0, 1, 0]]  # Prints "[1 4 5]"
# 等價於print np.array([a[0, 0], a[1, 1], a[2, 0]])  # Prints "[1 4 5]"
  • 數據類型
import numpy as np

x = np.array([1, 2])  
print x.dtype         # Prints "int64"

x = np.array([1.0, 2.0])  
print x.dtype             # Prints "float64"

x = np.array([1, 2], dtype=np.int64) 
print x.dtype                         # Prints "int64"
  • 數組計算
import numpy as np

x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)

print x + y
print np.add(x, y)
# [[ 6.0  8.0]
#  [10.0 12.0]]矩陣加

print x - y
print np.subtract(x, y)
# [[-4.0 -4.0]
#  [-4.0 -4.0]]矩陣減

print x * y
print np.multiply(x, y)
# [[ 5.0 12.0]
#  [21.0 32.0]]矩陣乘

print x / y
print np.divide(x, y)
# [[ 0.2         0.33333333]
#  [ 0.42857143  0.5       ]]矩陣除

print np.sqrt(x)
# [[ 1.          1.41421356]
#  [ 1.73205081  2.        ]]矩陣開方


#和MATLAB不同,*是元素逐個相乘,而不是矩陣乘法。在Numpy中使用dot來進行矩陣乘法:

import numpy as np

x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
v = np.array([9,10])
w = np.array([11, 12])

# 矩陣乘法,輸出219
print v.dot(w)
print np.dot(v, w)

# 矩陣乘法,輸出[29 67]
print x.dot(v)
print np.dot(x, v)

# 矩陣乘法,輸出
# [[19 22]
#  [43 50]]
print x.dot(y)
print np.dot(x, y)


#Numpy提供了很多計算數組的函數,其中最常用的一個是sum:
import numpy as np
x = np.array([[1,2],[3,4]])
print np.sum(x)  # 計算所有元素和; prints "10"
print np.sum(x, axis=0)  # 計算列元素和; prints "[4 6]"
print np.sum(x, axis=1)  # 計算行元素和; prints "[3 7]"

#除了計算,我們還常常改變數組或者操作其中的元素。其中將矩陣轉置是常用的一個,在Numpy中,使用T來轉置矩陣:

import numpy as np
x = np.array([[1,2], [3,4]])
print x    # Prints "[[1 2]
           #          [3 4]]"
print x.T  # Prints "[[1 3]
           #          [2 4]]"
  • 廣播Broadcasting
#如果我們想要把一個向量加到矩陣的每一行,我們可以這樣做:
import numpy as np

x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x)   # 創建與x矩陣shape相同的空矩陣

for i in range(4):
    y[i, :] = x[i, :] + v

#或者
vv = np.tile(v, (4, 1))  # Stack 4 copies of v on top of each other
print vv                 # Prints "[[1 0 1]
                         #          [1 0 1]
                         #          [1 0 1]
                         #          [1 0 1]]"
y = x + v

#廣播機制可以使我們直接運算
y = x + v
print y
# [[ 2  2  4]
#  [ 5  5  7]
#  [ 8  8 10]
#  [11 11 13]]
發佈了37 篇原創文章 · 獲贊 84 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章