[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()

  • 结果如图
    运行截图

猜你喜欢

转载自blog.csdn.net/xiaosongshine/article/details/84552982