且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Python/PIL 检测 HSV 颜色空间(来自 RGB)中的阈值

更新时间:2023-01-27 09:53:36

好的,这确实有效(修复了一些溢出错误):

Ok, this does work (fixed some overflow errors):

import numpy, Image
i = Image.open(fp).convert('RGB')
a = numpy.asarray(i, int)

R, G, B = a.T

m = numpy.min(a,2).T
M = numpy.max(a,2).T

C = M-m #chroma
Cmsk = C!=0

# Hue
H = numpy.zeros(R.shape, int)
mask = (M==R)&Cmsk
H[mask] = numpy.mod(60*(G-B)/C, 360)[mask]
mask = (M==G)&Cmsk
H[mask] = (60*(B-R)/C + 120)[mask]
mask = (M==B)&Cmsk
H[mask] = (60*(R-G)/C + 240)[mask]
H *= 255
H /= 360 # if you prefer, leave as 0-360, but don't convert to uint8

# Value
V = M

# Saturation
S = numpy.zeros(R.shape, int)
S[Cmsk] = ((255*C)/V)[Cmsk]

# H, S, and V are now defined as integers 0-255

它基于***对HSV的定义.当我有更多时间时,我会查看它.肯定有加速,也许还有错误.如果你找到了,请告诉我.干杯.

It is based on the Wikipedia's definition of HSV. I'll look it over as I get more time. There are definitely speedups and maybe bugs. Please let me know if you find any. cheers.

结果:

从这个色轮开始:

我得到了这些结果:

色调:

值:

饱和度: