2017-07-06 108 views
0

我正在嘗試實現this面向方向梯度(HOG)的版本。我的代碼如下。我的代碼唯一的區別是,我用opencv來讀取圖像並將其轉換爲灰度。面向方向梯度的Python直方圖

import cv2 
import matplotlib.pyplot as plt 
from skimage.feature import hog 
from skimage import data, color, exposure 

filename = 'match1/hockey15.jpg' 
im = cv2.imread(filename) 
gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) 

print im.shape 
image = gr 

fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16), 
        cells_per_block=(1, 1), visualise=True) 

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharex=True, sharey=True) 

ax1.axis('off') 
ax1.imshow(image, cmap=plt.cm.gray) 
ax1.set_title('Input image') 
ax1.set_adjustable('box-forced') 

# Rescale histogram for better display 
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02)) 

ax2.axis('off') 
ax2.imshow(hog_image_rescaled, cmap=plt.cm.gray) 
ax2.set_title('Histogram of Oriented Gradients') 
ax1.set_adjustable('box-forced') 
plt.show() 

的樣品的輸入和輸出是:

輸入:

enter image description here

輸出:

enter image description here

爲什麼輸出如此混亂?我甚至在上面的skimage鏈接中嘗試了與宇航員的圖像。爲此,我得到了很多混亂,輸出結果完全不像鏈接中顯示的那樣。我怎樣才能解決這個問題?

回答

0

我可以用你的代碼重現你的錯誤,並得到相同的混亂的形象。我修改了一下你的代碼,特別是改變軸,我得到了下面的輸出。

enter image description here

下面是修改後的代碼。

import cv2 
import matplotlib.pyplot as plt 
from skimage.feature import hog 
from skimage import data, color, exposure 

filename = r"pathtoimage\hockey.jpg" 

im = cv2.imread(filename) 

gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) 

print im.shape 
image = gr 

fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16), 
        cells_per_block=(1, 1), visualise=True) 

fig, ax = plt.subplots(1, 2, figsize=(20, 10), sharex=True, sharey=True) 

ax[0].axis('off') 
ax[0].imshow(image, cmap=plt.cm.gray) 
ax[0].set_title('Input image') 
ax[0].set_adjustable('box-forced') 

# Rescale histogram for better display 
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02)) 

ax[1].axis('off') 
ax[1].imshow(hog_image, cmap=plt.cm.gray) 
ax[1].set_title('Histogram of Oriented Gradients') 
ax[1].set_adjustable('box-forced') 

plt.show() 
0

我不知道爲什麼,但錯誤是由於閱讀圖像並將其轉換爲灰度與opencv。使用matplotlib這樣的教程建議,給了我正確的結果。

0

只需將值0.02更改爲0.5之類的值即可。這會讓它變暗。

hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02)) 

更改爲

hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.5))