【问题标题】:Cropping image by the center按中心裁剪图像
【发布时间】:2019-05-13 03:22:18
【问题描述】:

我有一个大小为 218、178 的 PNG 图像。我正在使用 matplotlib 的函数 imread 将其转换为 ndarray。我想裁剪它以获得图像的中间 64X64 部分。

我尝试使用 np.reshape 进行裁剪,但没有任何意义。我也尝试将切片作为普通数组,但由于实际数组的形状为 (218,178,3),所以我无法正确处理。我希望它(64,64,3)的前两个维度从 77 到 141 和 57 到 121。

【问题讨论】:

    标签: python matplotlib multidimensional-array png


    【解决方案1】:

    你想对numpy数组的前两个轴进行切片,分别对应高度和宽度(第三个是颜色通道)。

    import matplotlib.pyplot as pl
    
    # load image
    img = pl.imread('my_image.png')
    
    # confirm image shape
    print(img.shape)
    

    (218, 178, 3)

    这三个数字对应于每个轴的大小,对于图像通常解释为:(height, width, depth/colors)

    # crop image
    img_cropped = img[77:141, 57:121, :]
    
    # confirm cropped image shape
    print(img_cropped.shape)
    

    (64, 64, 3)

    另请注意,在裁剪时,您也可以省略最后一个冒号: img[77:141, 57:121]

    【讨论】:

    • 我省略了最后一个冒号,就是这样。谢谢!
    • 对我不起作用:>>> import matplotlib.pyplot as pl >>> img = pl.imread('/Users/bambrozi/Downloads/tmp/12517.png') >> > print(img.shape) (49, 159, 3) >>> img_cropped = img[77:141, 57:121] >>> print(img_cropped.shape) (0, 64, 3)
    • 您的图片高度为 49 像素,因此您无法从 77 像素裁剪到 141 像素。
    【解决方案2】:

    只需从数组中切出正确的部分即可轻松完成裁剪。例如。 image[100:200, 50:100, :] 对 y(垂直)方向上 100 到 200 像素之间的部分进行切片,在 x(水平)方向上切片 50 到 100 之间的部分。

    查看这个工作示例:

    import matplotlib.pyplot as plt
    
    mydic = {
      "annotations": [
      {
        "class": "rect",
        "height": 98,
        "width": 113,
        "x": 177,
        "y": 12
      },
      {
        "class": "rect",
        "height": 80,
        "width": 87,
        "x": 373,
        "y": 43
      }
     ],
       "class": "image",
       "filename": "https://i.stack.imgur.com/9qe6z.png"
    }
    
    
    def crop(dic, i):
        image = plt.imread(dic["filename"])
        x0 = dic["annotations"][i]["x"]
        y0 = dic["annotations"][i]["y"]
        width = dic["annotations"][i]["width"]
        height = dic["annotations"][i]["height"]
        return image[y0:y0+height , x0:x0+width, :]
    
    
    fig = plt.figure()
    ax = fig.add_subplot(121)
    ax.imshow(plt.imread(mydic["filename"]))
    
    ax1 = fig.add_subplot(222)
    ax1.imshow(crop(mydic, 0))
    
    ax2 = fig.add_subplot(224)
    ax2.imshow(crop(mydic, 1))
    
    plt.show()
    

    【讨论】:

    • 已修复,可能不需要字典和函数
    猜你喜欢
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    相关资源
    最近更新 更多