defrgb2hsv(img): hsv = np.zeros_like(img, dtype=np.float32) img = img/255.0 R = img[...,2] G = img[...,1] B = img[...,0] Max = np.max(img, axis=2) Min = np.min(img, axis=2) min_arg = np.argmin(img, axis=2)
hsv[...,0][np.where(Max==Min)] = 0
ind = np.where(min_arg==0) # Min==B hsv[...,0][ind] = 60*(G[ind]-R[ind])/(Max[ind]-Min[ind]+0.001)+60
ind = np.where(min_arg==2) # Min==R hsv[...,0][ind] = 60*(B[ind]-G[ind])/(Max[ind]-Min[ind]+0.001)+180
ind = np.where(min_arg==1) # Min==G hsv[...,0][ind] = 60*(R[ind]-B[ind])/(Max[ind]-Min[ind]+0.001)+300
hsv[...,1] = Max-Min # S hsv[...,2] = Max # V return hsv
defhsv2rgb(hsv): H = hsv[...,0] S = hsv[...,1] V = hsv[...,2] C = S H_ = H/60 X = C*(1-np.abs(H_%2-1)) Z = np.zeros_like(C) rgb = np.zeros_like(hsv) table = [[Z,X,C],[Z,C,X],[X,C,Z],[C,X,Z],[C,Z,X],[X,Z,C]] for i inrange(6): ind = np.where((H_>=i)&(H_<(i+1))) rgb[...,0][ind] = (V-C)[ind]+table[i][0][ind] rgb[...,1][ind] = (V-C)[ind]+table[i][1][ind] rgb[...,2][ind] = (V-C)[ind]+table[i][2][ind]