如何辨别两种颜色是否相似
如何辨别两个不同RGB值的颜色是否相似?
比如:RGB(125,1,34)和RGB(240,220,1),我们通过什么方法可辨别出这是两种颜色不相似,或者是这两种颜色相似?
能否给出代码?
[解决办法]
算法是这样的:RGB是个3维空间,分别计算两个颜色在这个空间的两个坐标点的直线距离,便是两个颜色的色差。
色差Cv=SQR(AbsR^2+AbsG^2+AbsB^2)
CS=阀值
CV<=CS为相似
CV>CS为不相似
获得两个RGB颜色的色差。
CV=ColorValueComp(RGB(255, 252, 255), RGB(255, 255, 252))
Type tpColorRGB
coR As Byte
coG As Byte
coB As Byte
End Type
Public Function ColorValueComp(ByVal pColorA As Long, ByVal pColorB As Long) As Long
'获得两个Long类型颜色的色差。
Dim tOutValue As Long
Dim tColorA As tpColorRGB
Dim tColorB As tpColorRGB
tColorA = ColorRGBGetByValue(pColorA)
tColorB = ColorRGBGetByValue(pColorB)
tOutValue = ColorRGBComp(tColorA, tColorB)
ColorValueComp = tOutValue
End Function
Public Function ColorRGBGetByValue(ByVal pColorValue As Long) As tpColorRGB
'从一个Long类型的颜色数据获得一个ColorRGB类型。
Dim tOutColor As tpColorRGB
With tOutColor
.coR = pColorValue Mod 2 ^ 8
.coG = (pColorValue \ 2 ^ 8) Mod 2 ^ 8
.coB = (pColorValue \ 2 ^ 16) Mod 2 ^ 8
End With
ColorRGBGetByValue = tOutColor
End Function
Public Function ColorRGBComp(ByRef pColorA As tpColorRGB, ByRef pColorB As tpColorRGB) As Long
'获得两个ColorRGB的色差。
Dim tOutValue As Long
Dim tAbsR As Long
Dim tAbsG As Long
Dim tAbsB As Long
tAbsR = Abs(CLng(pColorA.coR) - CLng(pColorB.coR))
tAbsG = Abs(CLng(pColorA.coG) - CLng(pColorB.coG))
tAbsB = Abs(CLng(pColorA.coB) - CLng(pColorB.coB))
tOutValue = Sqr(tAbsR ^ 2 + tAbsG ^ 2 + tAbsB ^ 2)
ColorRGBComp = tOutValue
End Function