如何用Python创建HSV圆盘图像(opencv和numpy)

-3 投票
1 回答
41 浏览
提问于 2025-04-14 18:09

有没有人能用opencv和numpy这两个库写个代码,生成一个500 x 500大小的HSV色盘图,像下面这个图一样:

HSV DISK

我试了几次,但总是做不出来,色盘的颜色不全。

1 个回答

1

更新的回答

我找了一些时间来写一个更详细的回答。虽然不是完美的,但应该能满足你95%的需求,你可以根据自己的需要调整旋转、缩放和饱和度:

#!/usr/bin/env python3

import numpy as np
import cv2 as cv

# Define length of side
N = 600

# Make grid to calculate Hue angles and radius
xx, yy = np.meshgrid(np.linspace(-1, 1, N), np.linspace(-1, 1, N))
H = (np.arctan2(xx, yy) + np.pi) / (np.pi * 2)
R = np.sqrt(xx ** 2 + yy ** 2)
# Scale to range 0..180 because OpenCV likes Hue in that range for np.uint8
H = (H * 180).astype(np.uint8)

# Generate Saturation and Value channels
S = np.full((600,600), 255, np.uint8)   # Solid white
V = np.full((600,600), 128, np.uint8)   # Solid mid-grey

cv.imwrite('DEBUG-H.png', H)
cv.imwrite('DEBUG-S.png', S)
cv.imwrite('DEBUG-V.png', V)

# Stack depthwise and convert to BGR
HSV = np.dstack((H,S,V))
BGR = cv.cvtColor(HSV, cv.COLOR_HSV2BGR)

# Make everything black outside unit circle
BGR[R>1] = 0

cv.imwrite('result.png', BGR)

这里输入图片描述

原始回答

我现在没有时间为你写代码,但你需要制作3个单独的灰度图像,像这样:

色相 (H):

这里输入图片描述

饱和度 (S):(纯白色):

这里输入图片描述

亮度 (V):(纯中灰色):

这里输入图片描述

然后把这三张图像叠加在一起,形成一个3通道的HSV图像,分别来自这三个单独的H、S和V通道:

HSV = np.dstack((H, S, V))

接着转换为BGR格式:

BGR = cv2.cvtColor(HSV, cv2.COLOR_HSV2BGR)

这样就会得到这个效果:

这里输入图片描述


记得色相通道应该是np.uint8类型,范围是0到180,而不是你可能期待的0到360。这是为了确保它适合无符号字符的范围。

撰写回答