1. 程式人生 > >[python3 OpenCV3使用技巧]使用numpy矩陣實現RGB轉HSI

[python3 OpenCV3使用技巧]使用numpy矩陣實現RGB轉HSI

python3OpenCV3使用矩陣實現RGB轉HSI

看到網上有很多部落格都是通過迴圈遍歷的方式來進行RGB轉HSI操作,但是我們知道在python中使用Numpy陣列並行操作可以更加簡潔,速度也更快。

  • 程式碼如下
import cv2
import numpy as np
import sys


In_path = "BGR.jpg"

img = cv2.imread(In_path)
img = cv2.resize(img,(400,300))
line, cols, chl = img.shape
img = img.astype(np.float32)
img_bgr = img.copy()/255 b,g,r = cv2.split(img_bgr) Tdata = np.where((2*np.sqrt((r-g)**2+(r-b)*(g-b))) != 0,np.arccos((2*r-b-g)/(2*np.sqrt((r-g)**2+(r-b)*(g-b)))),0) Hdata = np.where(g >= b,Tdata,2*3.1415926-Tdata) Hdata = Hdata / (2*3.1415926) Sdata = np.where((b+g+r) != 0, 1 - 3*np.minimum(b,g,r)/(
b+g+r),0) Idata = (b+g+r)/3 img_hsi = np.zeros((300,400,3)) img_hsi[:,:,0] = Hdata*255 img_hsi[:,:,1] = Sdata*255 img_hsi[:,:,2] = Idata*255 img_hsi = np.array(img_hsi) print(img_hsi.shape) print(img.shape) while(True): cv2.imshow('rgb_lwpImg', img.astype(np.uint8)) cv2.imshow('hsi_lwpImg', img_hsi.
astype(np.uint8)) cv2.imwrite("BGR_deal2.jpg",img_hsi.astype(np.uint8)) if(cv2.waitKey(1000//12) & 0xff == ord("q")): break cv2.destroyAllWindows()
  • 結果如圖
    執行截圖