2017-09-02 315 views
-2

在以下函數imcrop_tosquare中。 假設我有一個形狀的圖像(8,4) 即8行和4列。 如果是這樣的話。我會得到額外的4. 然後extra%2 ==0條件得到滿足。python下面的裁剪函數如何使用numpy裁剪圖像?

crop = img[2:-2,:] 

2到-2代表什麼? 我假設它是從第二行到它的前一行。 1,2,3,4,5,6,7,8 [這將在循環中],因此-1爲1,-2爲2. 如果將前兩行結束,則不會損壞圖像?? 我解釋錯了嗎?任何人都可以指導我理解這一點。

def imcrop_tosquare(img): 
"""Make any image a square image. 

Parameters 
---------- 
img : np.ndarray 
    Input image to crop, assumed at least 2d. 

Returns 
------- 
crop : np.ndarray 
    Cropped image. 
""" 
    if img.shape[0] > img.shape[1]: 
    extra = (img.shape[0] - img.shape[1]) 
    if extra % 2 == 0: 
     crop = img[extra // 2:-extra // 2, :] 
    else: 
     crop = img[max(0, extra // 2 + 1):min(-1, -(extra // 2)), :] 
    elif img.shape[1] > img.shape[0]: 
    extra = (img.shape[1] - img.shape[0]) 
    if extra % 2 == 0: 
     crop = img[:, extra // 2:-extra // 2] 
    else: 
     crop = img[:, max(0, extra // 2 + 1):min(-1, -(extra // 2))] 
    else: 
    print("It is imgae") 
    crop = img 
    return crop 
+3

你應該閱讀numpy的文檔。它有你所有問題的答案。 – DyZ

回答

1
根據 documentation

負i和j被解釋爲N + i和n + j,其中n是在相應尺寸的元件的數量。

,所以如果你有你的陣列中的8行,crop = img[2:-2,:]將意味着crop = img[2:6,:]