从OpenCV + Python获取HOG图像功能?
image-processing
opencv
python
5
0

我已经阅读了有关如何使用OpenCV的基于HOG的行人检测器的文章: 如何使用OpenCV检测和跟踪人员?

我想使用HOG来检测图像中的其他类型的对象(不仅仅是行人)。但是, HOGDetectMultiScale的Python绑定似乎无法提供对实际HOG功能的访问。

是否可以使用Python + OpenCV直接从任何图像中提取HOG功能?

参考资料:
Stack Overflow
收藏
评论
共 5 个回答
高赞 时间 活跃

1.获取内置文档:在python控制台上执行以下命令将帮助您了解HOGDescriptor类的结构:

 import cv2; 
 help(cv2.HOGDescriptor())

2.实施例编号:下面是一个代码片段来初始化不同参数的cv2.HOGDescriptor(I这里所用的术语是被OpenCV的文档中良好定义的标准条款这里 ):

import cv2
image = cv2.imread("test.jpg",0)
winSize = (64,64)
blockSize = (16,16)
blockStride = (8,8)
cellSize = (8,8)
nbins = 9
derivAperture = 1
winSigma = 4.
histogramNormType = 0
L2HysThreshold = 2.0000000000000001e-01
gammaCorrection = 0
nlevels = 64
hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,derivAperture,winSigma,
                        histogramNormType,L2HysThreshold,gammaCorrection,nlevels)
#compute(img[, winStride[, padding[, locations]]]) -> descriptors
winStride = (8,8)
padding = (8,8)
locations = ((10,20),)
hist = hog.compute(image,winStride,padding,locations)

3.推理:最终的生猪描述符将具有以下尺寸:9个方向X(获得1个归一化的4个角块+得到2个归一化的边缘上的6x4块+得到4个归一化的6x6块的边缘)= 1764。 hog.compute()的一个位置。

4.还有一种初始化方法是从包含所有参数值的xml文件中进行初始化

hog = cv2.HOGDescriptor("hog.xml")

要获取xml文件,可以执行以下操作:

hog = cv2.HOGDescriptor()
hog.save("hog.xml")

并在xml文件中编辑相应的参数值。

收藏
评论

在python opencv中,您可以像这样计算hog:

 import cv2
 hog = cv2.HOGDescriptor()
 im = cv2.imread(sample)
 h = hog.compute(im)
收藏
评论

尽管存在如先前答案中所述的方法:

猪= cv2.HOGDescriptor()

我想发布一个python实现,您可以在opencv的examples目录中找到它,希望它对了解HOG函数的有用性:

def hog(img):
    gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
    gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)
    mag, ang = cv2.cartToPolar(gx, gy)
    bin_n = 16 # Number of bins
    bin = np.int32(bin_n*ang/(2*np.pi))

    bin_cells = []
    mag_cells = []

    cellx = celly = 8

    for i in range(0,img.shape[0]/celly):
        for j in range(0,img.shape[1]/cellx):
            bin_cells.append(bin[i*celly : i*celly+celly, j*cellx : j*cellx+cellx])
            mag_cells.append(mag[i*celly : i*celly+celly, j*cellx : j*cellx+cellx])   

    hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)]
    hist = np.hstack(hists)

    # transform to Hellinger kernel
    eps = 1e-7
    hist /= hist.sum() + eps
    hist = np.sqrt(hist)
    hist /= norm(hist) + eps

    return hist

问候。

收藏
评论

如果您想要用于HOG功能的快速Python代码,我已将代码移植到Cython: https : //github.com/cvondrick/pyvision/blob/master/vision/features.pyx

收藏
评论

这是仅使用OpenCV的解决方案:

import numpy as np
import cv2
import matplotlib.pyplot as plt

img = cv2.cvtColor(cv2.imread("/home/me/Downloads/cat.jpg"),
                   cv2.COLOR_BGR2GRAY)

cell_size = (8, 8)  # h x w in pixels
block_size = (2, 2)  # h x w in cells
nbins = 9  # number of orientation bins

# winSize is the size of the image cropped to an multiple of the cell size
hog = cv2.HOGDescriptor(_winSize=(img.shape[1] // cell_size[1] * cell_size[1],
                                  img.shape[0] // cell_size[0] * cell_size[0]),
                        _blockSize=(block_size[1] * cell_size[1],
                                    block_size[0] * cell_size[0]),
                        _blockStride=(cell_size[1], cell_size[0]),
                        _cellSize=(cell_size[1], cell_size[0]),
                        _nbins=nbins)

n_cells = (img.shape[0] // cell_size[0], img.shape[1] // cell_size[1])
hog_feats = hog.compute(img)\
               .reshape(n_cells[1] - block_size[1] + 1,
                        n_cells[0] - block_size[0] + 1,
                        block_size[0], block_size[1], nbins) \
               .transpose((1, 0, 2, 3, 4))  # index blocks by rows first
# hog_feats now contains the gradient amplitudes for each direction,
# for each cell of its group for each group. Indexing is by rows then columns.

gradients = np.zeros((n_cells[0], n_cells[1], nbins))

# count cells (border cells appear less often across overlapping groups)
cell_count = np.full((n_cells[0], n_cells[1], 1), 0, dtype=int)

for off_y in range(block_size[0]):
    for off_x in range(block_size[1]):
        gradients[off_y:n_cells[0] - block_size[0] + off_y + 1,
                  off_x:n_cells[1] - block_size[1] + off_x + 1] += \
            hog_feats[:, :, off_y, off_x, :]
        cell_count[off_y:n_cells[0] - block_size[0] + off_y + 1,
                   off_x:n_cells[1] - block_size[1] + off_x + 1] += 1

# Average gradients
gradients /= cell_count

# Preview
plt.figure()
plt.imshow(img, cmap='gray')
plt.show()

bin = 5  # angle is 360 / nbins * direction
plt.pcolor(gradients[:, :, bin])
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
plt.colorbar()
plt.show()

我已经使用HOG描述符计算和可视化来了解数据布局并对组中的循环进行矢量化处理。

收藏
评论
新手导航
  • 社区规范
  • 提出问题
  • 进行投票
  • 个人资料
  • 优化问题
  • 回答问题

关于我们

常见问题

内容许可

联系我们

@2020 AskGo
京ICP备20001863号