# HSV颜色空间下的图片相似性计算(python版)

• RGB与HSV的转换
• python多维矩阵转换为向量数组
• HSV三维空间坐标计算公式
• 具体代码实现

## RGB与HSV的转换

python实现图片读入和颜色空间转换：

import math
import cv2
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.mlab as mlab

HSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

## 多维矩阵转换为向量数组

H, S, V = cv2.split(HSV)
aH = np.array(H).flatten()
aS = np.array(S1).flatten()
aV = np.array(V).flatten()

### HSV三维空间坐标计算公式

$\begin{array}{rl}x& =r\ast V\ast S\ast cosH\\ y& =r\ast V\ast S\ast sinH\\ z& =h\ast \left(1-V\right)\end{array}$

x1 = r * V1[i] * S1[i] * math.cos(H1[i] / 180.0 * math.pi);
y1 = r * V1[i] * S1[i] * math.sin(H1[i] / 180.0 * math.pi);
z1 = h * (1 - V1[i]);

### 具体代码实现

import math
import cv2
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.mlab as mlab

HSV1 = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)
aH1, aS1, aV1 = cv2.split(HSV1)
H1 = np.array(aH1).flatten()
S1 = np.array(aS1).flatten()
V1 = np.array(aV1).flatten()

HSV2 = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)
aH2, aS2, aV2 = cv2.split(HSV2)
H2 = np.array(aH2).flatten()
S2 = np.array(aS2).flatten()
V2 = np.array(aV2).flatten()

R = 100.0;
angle = 30.0;
h = R * math.cos(angle / 180 * math.pi);
r = R * math.sin(angle / 180 * math.pi);

sum = 0.0
for i in range(0, len(H1)):
x1 = r * V1[i] * S1[i] * math.cos(H1[i] / 180.0 * math.pi);
y1 = r * V1[i] * S1[i] * math.sin(H1[i] / 180.0 * math.pi);
z1 = h * (1 - V1[i]);

x2 = r * V2[i] * S2[i] * math.cos(H2[i] / 180.0 * math.pi);
y2 = r * V2[i] * S2[i] * math.sin(H2[i] / 180.0 * math.pi);
z2 = h * (1 - V2[i]);

dx = x1 - x2;
dy = y1 - y2;
dz = z1 - z2;

sum = sum + dx * dx + dy * dy + dz * dz

eucli_dean = math.sqrt(sum)
print eucli_dean