2017-09-02 65 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,:]