RGB 和 HSI互相转换 python代码
2021/4/9 20:27:49
本文主要是介绍RGB 和 HSI互相转换 python代码,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
# -*- coding: utf-8 -*- import numpy as np def __Rgb2Hsi(R, G, B): # 归一化到[0,1] R /= 255 G /= 255 B /= 255 eps = 1e-8 H, S, I = 0, 0, 0 sumRGB = R + G + B Min = min(R,G,B) S = 1 - 3 * Min / (sumRGB + eps) H = np.arccos((0.5 * (R + R - G - B)) / np.sqrt((R - G) * (R - G) + (R - B) * (G - B) + eps)) if B > G: H = 2 * np.pi - H H = H / (2 * np.pi) if S == 0: H = 0 I = sumRGB / 3 return np.array([H, S, I], dtype = float) def Rgb2Hsi(img): HSIimg = np.zeros(img.shape, dtype = float) width, height = img.shape[:2] for w in range(width): for h in range(height): HSIimg[w,h,:] = __Rgb2Hsi(img[w,h,0],img[w,h,1],img[w,h,2]) return HSIimg def __Hsi2Rgb(H, S, I): pi3 = np.pi / 3 # 扩充弧度范围[0,2pi] H *= 2 * np.pi if H >= 0 and H < 2 * pi3: # [0,2pi/3)对应红->绿 B = I * (1 - S) R = I * (1 + S * np.cos(H) / np.cos(pi3 - H)) G = 3 * I - (R + B) elif H >= 2 * pi3 and H <= 4 * pi3: # [2pi/3,4pi/3)对应绿->蓝 H = H - 2 * pi3 R = I * (1 - S) G = I * (1 + S * np.cos(H) / np.cos(pi3 - H)) B = 3 * I - (R + G) else: # [4pi/3,2pi)对应蓝->红 H = H - 4 * pi3 G = I * (1 - S) B = I * (1 + S * np.cos(H) / np.cos(pi3 - H)) R = 3 * I - (B + G) return (np.array([R,G,B]) * 255).astype(np.uint8) def Hsi2Rgb(img): RGBimg = np.zeros(img.shape, dtype = np.uint8) width, height = img.shape[:2] for w in range(width): for h in range(height): RGBimg[w,h,:] = __Hsi2Rgb(img[w,h,0],img[w,h,1],img[w,h,2]) return RGBimg
这篇关于RGB 和 HSI互相转换 python代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python