如何用Python创建HSV圆盘图像(opencv和numpy)
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。这是为了确保它适合无符号字符的范围。