HSI模型代码python
时间: 2023-12-15 16:31:49 浏览: 86
以下是一个Python实现的RGB和HSI模型之间相互转换的代码示例:
```python
import numpy as np
import cv2
def rgb2hsi(img):
# 将RGB图像转换为HSI图像
img = img.astype(np.float32) / 255.0
b, g, r = cv2.split(img)
hsi = np.zeros_like(img)
eps = 1e-6
for i, color in enumerate([b, g, r]):
numerator = 0.5 * ((r - g) + (r - b))
denominator = np.sqrt((r - g) ** 2 + (r - b) * (g - b))
theta = np.arccos(numerator / (denominator + eps))
h = np.zeros_like(theta)
h[color <= b] = theta[color <= b]
h[color > b] = 2 * np.pi - theta[color > b]
hsi[..., i] = h / (2 * np.pi)
hsi[..., 1] = 1 - 3 * np.min(hsi[..., :3], axis=-1)
hsi[..., 2] = np.sum(img, axis=-1) / 3.0
return hsi
def hsi2rgb(img):
# 将HSI图像转换为RGB图像
img = img.copy()
h, s, i = cv2.split(img)
h = h * 2 * np.pi
bgr = np.zeros_like(img)
for i, color in enumerate([bgr[..., 0], bgr[..., 1], bgr[..., 2]]):
if i == 0: # Blue
idx = np.logical_and(h >= 0, h < 2 * np.pi / 3)
color[idx] = i + (1 - s[idx])
idx = np.logical_and(h >= 2 * np.pi / 3, h < 4 * np.pi / 3)
color[idx] = i + (1 - s[idx]) * (h[idx] - 2 * np.pi / 3) / (2 * np.pi / 3)
idx = np.logical_and(h >= 4 * np.pi / 3, h < 2 * np.pi)
color[idx] = i + s[idx]
elif i == 1: # Green
idx = np.logical_and(h >= 0, h < 2 * np.pi / 3)
color[idx] = i + s[idx] * (h[idx]) / (2 * np.pi / 3)
idx = np.logical_and(h >= 2 * np.pi / 3, h < 4 * np.pi / 3)
color[idx] = i + (1 - s[idx])
idx = np.logical_and(h >= 4 * np.pi / 3, h < 2 * np.pi)
color[idx] = i + s[idx] * (2 * np.pi - h[idx]) / (2 * np.pi / 3)
else: # Red
idx = np.logical_and(h >= 0, h < 2 * np.pi / 3)
color[idx] = i + s[idx]
idx = np.logical_and(h >= 2 * np.pi / 3, h < 4 * np.pi / 3)
color[idx] = i + s[idx] * (4 * np.pi / 3 - h[idx]) / (2 * np.pi / 3)
idx = np.logical_and(h >= 4 * np.pi / 3, h < 2 * np.pi)
color[idx] = i + (1 - s[idx])
bgr[..., 0] = bgr[..., 0] * 255.0
bgr[..., 1] = bgr[..., 1] * 255.0
bgr[..., 2] = bgr[..., 2] * 255.0
return bgr.astype(np.uint8)
# 示例代码
img = cv2.imread('example.jpg')
hsi_img = rgb2hsi(img)
rgb_img = hsi2rgb(hsi_img)
cv2.imshow('Original Image', img)
cv2.imshow('HSI Image', hsi_img)
cv2.imshow('RGB Image', rgb_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文
相关推荐

















