0

我需要为图像中的补丁实现定向梯度直方图(每个补丁一个 HOG 特征向量,而不是整个图像的一个 HOG)。我一直在此链接上使用 Matlab 代码并将代码翻译为 opencv python。我已经进行了一些更改以适应我的目的,Matlab 和 Python 代码之间的主要区别之一是我获取每个单元格的渐变的方式,而在 Matlab 中我使用的是上面链接中使用的filter2 ,在 Opencv 中,我使用Sobel运算符。我的问题是这两种方法产生的渐变是不同的,我很难修复它。我尝试更改图像和内核数字表示。我也试过在opencv中使用filter2D ,还有imfilter在 Matlab 中,但基本上没有一个工作。这是使用filter2计算梯度的 Matlab 代码:

blockSize=26;
cellSize=floor(blockSize/2);
cellPerBlock=4;
numBins=9;
dim = [444,262];
RGB = imread('testImage.jpg');
img= rgb2gray(RGB);

img = imresize(img, [262,444], 'bilinear', 'Antialiasing',false);

%operators 
hx = [-1,0,1];
hy = [-1;0;1] ;

%derivatives 
dx = filter2(hx, double(img));
dy = filter2(hy, double(img));

% Remove the 1 pixel border.
dx = dx(2 : (size(dx, 1) - 1), 2 : (size(dx, 2) - 1));
dy = dy(2 : (size(dy, 1) - 1), 2 : (size(dy, 2) - 1)); 

% Convert the gradient vectors to polar coordinates (angle and magnitude).
ang = atan2(dy, dx);
ang(ang < 0) = ang(ang < 0)+ pi;
mag = ((dy.^2) + (dx.^2)).^.5;

这是我使用Sobel运算符编写的 Python OpenCV 版本:

blockSize=26
cellSize=int(blockSize/2)
cellPerBlock=4
numBins=9
dim = (444,262)
angDiff=10**-6
img = cv2.imread('3132 2016-04-25 12-35-43-53991.jpg',0)
img = cv2.resize(img, dim, interpolation = cv2.INTER_LINEAR)

sobelx = cv2.Sobel(img.astype(float),cv2.CV_64F,1,0,ksize=1)
sobelx = sobelx[1 : np.shape(sobelx)[0] - 1, 1 : np.shape(sobelx)[1] - 1]

sobely = cv2.Sobel(img.astype(float),cv2.CV_64F,0,1,ksize=1)
sobely = sobely[1 : np.shape(sobely)[0] - 1, 1 : np.shape(sobely)[1] - 1]

mag, ang = cv2.cartToPolar(sobelx, sobely)
ang[ang>np.pi+angDiff]= ang[ang>np.pi+angDiff] - np.pi

编辑:我按照这里的帖子,在 Matlab 中使用双线性方法,在 OpenCV 中使用 cv2.INTER_LINEAR,并在 Matlab 中停用抗锯齿,但两个调整大小的图像仍然不完全匹配。这是 Matlab 中测试图像的调整大小图像的一部分: 在此处输入图像描述

这是来自 OpenCV 的相同部分: 在此处输入图像描述

第二次编辑:事实证明,舍入的方式会导致这种差异。所以,我将我的 OpenCV 代码更改为:

img = cv2.resize(img.astype(float), dim, interpolation = cv2.INTER_LINEAR)

和 Matlab:

imresize(double(img), [262,444], 'bilinear', 'Antialiasing',false);

现在两者都给了我相同的结果。 在此处输入图像描述

我认为问题是由衍生方法引起的。我在 OpenCV 中检查了 cv2.filter2D,但结果仍然不同。我希望有人能给我提示可能导致问题的原因。

4

0 回答 0