region-based color histogram feature.
import numpy as np
import cv2
#HSV 颜色空间中每个通道的 bins,可进行调整
bins = (8, 12, 3)
#计算单个区域的颜色直方图特征
def histogram(image, mask):
#根据设定的 bins,从图像的 mask 区域提取 3D 颜色直方图.
hist = cv2.calcHist([image], [0, 1, 2], mask, bins, [0, 180, 0, 256, 0, 256])
#直方图归一化
hist = cv2.normalize(hist, hist).flatten()
return hist
#计算基于区域颜色直方图特征,特征向量维度为:bins[0]*bins[1]*bins[2]*5
def describe(img_cv2):
#转换到 HSV 空间.
img_hsv = cv2.cvtColor(img_cv2, cv2.COLOR_BGR2HSV)
h, w = img_hsv.shape[:2]
cX, cY = (int(w * 0.5), int(h * 0.5)) #图片中心
#将图像化分为 4 块:
#(top-left, top-right, bottom-right, bottom-left)
segments = [(0, cX, 0, cY),
(cX, w, 0, cY),
(cX, w, cY, h),
(0, cX, cY, h)]
#构建椭圆mask(elliptical mask) 来表示图片中心
axesX, axesY = (int(w * 0.75) // 2, int(h * 0.75) // 2)
ellipMask = np.zeros(img_hsv.shape[:2], dtype = "uint8")
cv2.ellipse(ellipMask, (cX, cY), (axesX, axesY), 0, 0, 360, 255, -1)
#计算区域颜色直方图
features = []
for (startX, endX, startY, endY) in segments:
#构建图片每个角的 mask,并提取其椭圆中心.
cornerMask = np.zeros(img_hsv.shape[:2], dtype = "uint8")
cv2.rectangle(cornerMask, (startX, startY), (endX, endY), 255, -1)
cornerMask = cv2.subtract(cornerMask, ellipMask)
#构建颜色直方图
hist = histogram(img_hsv, cornerMask)
features.extend(hist)
#提取各椭圆区域的颜色直方图
hist = histogram(img_hsv, ellipMask)
features.extend(hist)
#特征向量features包含 4 个角区域和 1 个中心区域五部分,
#特征向量维度等于 bins[0]*bins[1]*bins[2]*5
return features
#
img_cv2 = cv2.imread('test.jpg')
extract_feats = describe(img_cv2)
print("[INFO]Image color histogram feature:{}".format(extract_feats))