RGB To HSV

This algorithm converts RGB color model to HSV color model.



									Public Structure RGB
	Private _r As Byte
	Private _g As Byte
	Private _b As Byte

	Public Sub New(r As Byte, g As Byte, b As Byte)
		Me._r = r
		Me._g = g
		Me._b = b
	End Sub

	Public Property R() As Byte
		Get
			Return Me._r
		End Get
		Set(value As Byte)
			Me._r = value
		End Set
	End Property

	Public Property G() As Byte
		Get
			Return Me._g
		End Get
		Set(value As Byte)
			Me._g = value
		End Set
	End Property

	Public Property B() As Byte
		Get
			Return Me._b
		End Get
		Set(value As Byte)
			Me._b = value
		End Set
	End Property

	Public Overloads Function Equals(rgb As RGB) As Boolean
		Return (Me.R = rgb.R) AndAlso (Me.G = rgb.G) AndAlso (Me.B = rgb.B)
	End Function
End Structure

Public Structure HSV
	Private _h As Double
	Private _s As Double
	Private _v As Double

	Public Sub New(h As Double, s As Double, v As Double)
		Me._h = h
		Me._s = s
		Me._v = v
	End Sub

	Public Property H() As Double
		Get
			Return Me._h
		End Get
		Set(value As Double)
			Me._h = value
		End Set
	End Property

	Public Property S() As Double
		Get
			Return Me._s
		End Get
		Set(value As Double)
			Me._s = value
		End Set
	End Property

	Public Property V() As Double
		Get
			Return Me._v
		End Get
		Set(value As Double)
			Me._v = value
		End Set
	End Property

	Public Overloads Function Equals(hsv As HSV) As Boolean
		Return (Me.H = hsv.H) AndAlso (Me.S = hsv.S) AndAlso (Me.V = hsv.V)
	End Function
End Structure

Public Shared Function RGBToHSV(rgb As RGB) As HSV
	Dim delta As Double, min As Double
	Dim h As Double = 0, s As Double, v As Double

	min = Math.Min(Math.Min(rgb.R, rgb.G), rgb.B)
	v = Math.Max(Math.Max(rgb.R, rgb.G), rgb.B)
	delta = v - min

	If v = 0.0 Then
		s = 0
	Else
		s = delta / v
	End If

	If s = 0 Then
		h = 0.0
	Else

		If rgb.R = v Then
			h = (rgb.G - rgb.B) / delta
		ElseIf rgb.G = v Then
			h = 2 + (rgb.B - rgb.R) / delta
		ElseIf rgb.B = v Then
			h = 4 + (rgb.R - rgb.G) / delta
		End If

		h *= 60

		If h < 0.0 Then
			h = h + 360
		End If
	End If

	Return New HSV(h, s, (v / 255))
End Function
								


Example

									Dim data As New RGB(82, 0, 87)
Dim value = RGBToHSV(data)
								


Output

									H: 296.55172413793105
S: 1
V: 0.3411764705882353