将RGB转换成HSI图像再转换成RGB图像代码
时间: 2024-03-13 15:47:03 浏览: 75
以下是Python代码实现将RGB图像转换为HSI图像再转换回RGB图像:
```python
import numpy as np
import cv2
import math
# 将RGB颜色值转换为HSI颜色值
def rgb2hsi(rgb):
R, G, B = rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0
I = (R + G + B) / 3.0
if R == G and G == B:
S = 0.0
H = 0.0
else:
numerator = 0.5 * ((R - G) + (R - B))
denominator = ((R - G) ** 2 + (R - B) * (G - B)) ** 0.5
theta = math.acos(numerator / denominator)
if B > G:
H = 2 * math.pi - theta
else:
H = theta
if I == 0.0:
S = 0.0
else:
S = 1.0 - 3.0 * min(R, G, B) / (R + G + B)
return np.array([H, S, I])
# 将HSI颜色值转换为RGB颜色值
def hsi2rgb(hsi):
H, S, I = hsi[0], hsi[1], hsi[2]
if S == 0.0:
R = G = B = int(I * 255)
else:
if H >= 0 and H < 2 * math.pi / 3:
B = I * (1.0 - S)
R = I * (1.0 + S * math.cos(H) / math.cos(math.pi / 3 - H))
G = 3.0 * I - (R + B)
elif H >= 2 * math.pi / 3 and H < 4 * math.pi / 3:
H = H - 2 * math.pi / 3
R = I * (1.0 - S)
G = I * (1.0 + S * math.cos(H) / math.cos(math.pi / 3 - H))
B = 3.0 * I - (R + G)
else:
H = H - 4 * math.pi / 3
G = I * (1.0 - S)
B = I * (1.0 + S * math.cos(H) / math.cos(math.pi / 3 - H))
R = 3.0 * I - (G + B)
R, G, B = int(max(0, min(255, R * 255))), int(max(0, min(255, G * 255))), int(max(0, min(255, B * 255)))
return np.array([R, G, B])
# 读取RGB图像
img = cv2.imread("test.jpg")
# 分离RGB通道
R, G, B = cv2.split(img)
# 将RGB图像转换为HSI图像
HSI = np.zeros_like(img, dtype=np.float32)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
rgb = [R[i][j], G[i][j], B[i][j]]
hsi = rgb2hsi(rgb)
HSI[i][j] = hsi
# 对HSI图像进行处理,例如可以对饱和度和亮度进行调整或者滤波操作
# 这里直接将饱和度和亮度乘以一个系数,进行简单的调整
HSI[:, :, 1] *= 0.5
HSI[:, :, 2] *= 1.5
# 将HSI图像转换为RGB图像
RGB = np.zeros_like(img)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
hsi = HSI[i][j]
rgb = hsi2rgb(hsi)
RGB[i][j] = rgb
# 将RGB图像显示出来
cv2.imshow("RGB", img)
cv2.imshow("HSI", HSI)
cv2.imshow("RGB2", RGB)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个示例中,我们读取了一张RGB图像,然后将其转换为HSI图像。接着,我们对HSI图像进行了一些简单的处理,例如将饱和度和亮度乘以一个系数。最后,我们将处理后的HSI图像转换回RGB图像,并将其显示出来。
阅读全文