将图像从RGB空间和HSI空间进行转换的python代码
时间: 2024-02-06 07:03:49 浏览: 75
以下是将图像从RGB空间和HSI空间进行转换的Python代码:
```python
import numpy as np
import cv2
def rgb2hsi(img):
# 将RGB图像转换为HSI图像
r, g, b = cv2.split(img)
r = r / 255.0
g = g / 255.0
b = b / 255.0
num = 0.5 * ((r - g) + (r - b))
den = np.sqrt((r - g) ** 2 + (r - b) * (g - b))
theta = np.arccos(num / (den + 1e-5))
h = theta
h[b > g] = 2 * np.pi - h[b > g]
h = h / (2 * np.pi)
num = np.minimum(np.minimum(r, g), b)
den = r + g + b
den[den == 0] = 1e-5
s = 1 - 3 * num / den
hsi = cv2.merge((h, s, (r + g + b) / 3.0))
return hsi
def hsi2rgb(img):
# 将HSI图像转换为RGB图像
h, s, i = cv2.split(img)
h = h * 2 * np.pi
r = np.zeros_like(h)
g = np.zeros_like(h)
b = np.zeros_like(h)
# RG sector (0 <= H < 120)
idx = np.logical_and(h >= 0, h < 2 * np.pi / 3)
b[idx] = i[idx] * (1 - s[idx])
r[idx] = i[idx] * (1 + s[idx] * np.cos(h[idx]) / np.cos(np.pi / 3 - h[idx]))
g[idx] = 3 * i[idx] - (r[idx] + b[idx])
# BG sector (120 <= H < 240)
idx = np.logical_and(h >= 2 * np.pi / 3, h < 4 * np.pi / 3)
h[idx] = h[idx] - 2 * np.pi / 3
r[idx] = i[idx] * (1 - s[idx])
g[idx] = i[idx] * (1 + s[idx] * np.cos(h[idx]) / np.cos(np.pi / 3 - h[idx]))
b[idx] = 3 * i[idx] - (r[idx] + g[idx])
# BR sector (240 <= H <= 360)
idx = np.logical_and(h >= 4 * np.pi / 3, h < 2 * np.pi)
h[idx] = h[idx] - 4 * np.pi / 3
g[idx] = i[idx] * (1 - s[idx])
b[idx] = i[idx] * (1 + s[idx] * np.cos(h[idx]) / np.cos(np.pi / 3 - h[idx]))
r[idx] = 3 * i[idx] - (g[idx] + b[idx])
rgb = cv2.merge((r, g, b))
rgb = np.clip(rgb * 255.0, 0, 255).astype(np.uint8)
return rgb
# 示例代码
img = cv2.imread('test.png')
hsi = rgb2hsi(img)
rgb = hsi2rgb(hsi)
cv2.imshow('Original', img)
cv2.imshow('HSI', hsi)
cv2.imshow('RGB', rgb)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文