【问题标题】:How will the following crop function on python crop a image using numpy? [duplicate]python上的以下裁剪功能将如何使用numpy裁剪图像? [复制]
【发布时间】:2017-09-02 06:27:08
【问题描述】:

在下面的函数imcrop_tosquare中。 假设我有一个形状 (8,4) 的图像 即8行4列。 如果是这样的话。我会得到额外的4。 然后extra%2 ==0 条件得到满足。

crop = img[2:-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

【问题讨论】:

  • 你应该阅读 numpy 文档。它有你所有问题的答案。

标签: python numpy machine-learning


【解决方案1】:

根据documentation

负数 i 和 j 被解释为 n + i 和 n + j,其中 n 是相应维度中的元素数。

所以如果数组中有 8 行,crop = img[2:-2,:] 将意味着 crop = img[2:6,:]

【讨论】:

    猜你喜欢
    • 2017-05-21
    • 1970-01-01
    • 2017-05-22
    • 2017-04-25
    • 2020-09-06
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多