2017-03-09 126 views
1

我是圖像處理新手,並開始學習scikit-image。我試圖檢測一個矩形的角落,然後裁剪整個圖像。但我迷失在大量的分割和檢測算法中,不知道我需要哪一個以及如何去做。檢測矩形並將圖像裁剪至其大小

此代碼生成示例圖像。我想把它裁剪成綠色的矩形。我需要做什麼?

從matplotlib進口pyplot作爲pyplot

import numpy as np 
import skimage 
from skimage import draw 

img = np.zeros((500, 500, 3), dtype=np.double) 

poly = np.array([[25, 25], 
       [25, 75], 
       [75, 75], 
       [75, 25]]) 

rr, cc = draw.polygon(poly[:, 0], poly[:, 1], img.shape) 

img[rr, cc, 1] = 1 
plt.imshow(img) 
plt.show() 

的任務是檢測矩形(聚陣列)的邊緣和圖像裁剪到它。

我試過哈里斯角點檢測,Canny邊緣檢測等等,但我完全搞不懂。這似乎是一個簡單的任務,但我沒有得到它。

這對OpenCV會更容易嗎?請幫助!

+0

是。你應該使用OpenCV,檢查[這個SO帖子](http://stackoverflow.com/questions/11424002/how-to-detect-simple-geometric-shapes-using-opencv)。 – Bill

回答

0

如果您使用輪廓尋找方法,OpenCV是目前最好的選擇。如果您可以用其他方式識別對象,則使用skimage可以很容易地識別座標並裁剪圖像。例如:

import numpy as np 
import skimage 
from skimage import draw, measure 
import matplotlib.pyplot as plt 

# --- Generate test data --- 
img = np.zeros((500, 500, 3), dtype=np.double) 

poly = np.array([[25, 25], 
       [25, 75], 
       [75, 75], 
       [75, 25]]) 

rr, cc = draw.polygon(poly[:, 0], poly[:, 1], img.shape) 

img[rr, cc, 1] = 1 
# --- End generate test data --- 

# Generate a mask with all objects close to green 
green = (0, 1, 0) 
mask = np.sum((img - green)**2, axis=2) < 0.1 

# Label the different objects in the image 
label_img = measure.label(mask) 

# Find all objects 
regions = measure.regionprops(label_img) 

# Find the first object (since we only have one, that's the rectangle!) 
r = regions[0] 

# We'll use the `bbox` property to select the bounding box 
# # For a full list of properties, take a look at the docstring of 
# measure.regionprops 

print('The bounding box is {}'.format(r.bbox)) 

r0, c0, r1, c1 = r.bbox 
img_crop = img[r0:r1, c0:c1] 

f, (ax0, ax1) = plt.subplots(1, 2) 
ax0.imshow(img) 
ax1.imshow(img_crop) 
plt.show() 

enter image description here

+0

謝謝!你能再幫我一次嗎?您的解決方案適用於該示例,但我的實際圖片出現錯誤。當試圖生成掩碼時,由於矩陣不兼容,我得到了一個numpy錯誤:'ValueError:操作數無法與形狀(2048,2456)(3,)'一起廣播。我真的不明白它,因爲圖像數組應該具有與示例相同的尺寸(僅適用於更多像素) – cripcate