Python Numpy 和 CV 應用
1. 檢視圖片轉為矩陣後的維度和型別:
if __name__ == "__main__": import numpy as np from PIL import Image from matplotlib import pyplot as plt img = np.array(Image.open("TT.jpg")) # display the dimension and data type print (img.shape, img.dtype) plt.imshow(img) plt.show()
顯示結果如下(其結果應對應你的圖片大小而有所不同):
(1810, 2715, 3) uint8
矩陣維度是 1810 * 2715 * 3 (三通道),每個元素為 uint8 (0~ 255)
2. 圖片轉為單通道(灰階):
if __name__ == "__main__": import numpy as np from PIL import Image from matplotlib import pyplot as plt img = np.array(Image.open("TT.jpg").convert("L"), "f") # display the dimension and data type print (img.shape, img.dtype) plt.imshow(img, cmap="gray") plt.show()
顯示結果如下(其結果應對應你的圖片大小而有所不同):
(1810, 2715) float32
矩陣維度是 1810 * 2715 * 1 (單通道),每個元素為 float32
3. 矩陣間相互轉換:
if __name__ == "__main__": import numpy as np from PIL import Image from matplotlib import pyplot as plt img = np.array(Image.open("TT.jpg").convert("L"), "f") # display the dimension and data type print (img.shape, img.dtype) img = np.uint8(img) print (img.shape, img.dtype)
顯示結果如下(其結果應對應你的圖片大小而有所不同):
(1810, 2715) float32 (1810, 2715) uint8
4. 從矩陣中切片:
if __name__ == "__main__": import numpy as np from PIL import Image from matplotlib import pyplot as plt img = np.array(Image.open("TT.jpg").convert("L"), "f") # plt.subplot(211) print (img.shape, img.dtype) plt.imshow(img, cmap="gray") # plt.subplot(212) img2 = img[50:200,50:200] plt.imshow(img2, cmap="gray") plt.show()
5. 矩陣元素統一運算:
if __name__ == "__main__": import numpy as np from PIL import Image from matplotlib import pyplot as plt img = np.array(Image.open("TT.jpg").convert("L")) # just a demo img = (255 - img)/2 # display the dimension and data type print (img.shape, img.dtype) plt.imshow(img, cmap="gray")
反白再將亮度減半的結果如下:
!!! 假設原矩陣是整數型別,對其進行浮點數乘除會將整個矩陣元素轉型成浮點數。 !!!
留言
張貼留言