从作为Numpy数组的图像中裁剪边界框

2024-05-17 06:58:32 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我得到了一个形状为(224244,3)的ndarray图像。我有一个像这样的图像的边界框注释

{
  annotations: [
  {
    class: "rect",
    height: 172,
    width: 341,
    x: 282,
    y: 165
  },
  {
    class: "rect",
    height: 172,
    width: 353,
    x: 592,
    y: 90
  }
 ],
   class: "image",
   filename: "img_05974.jpg"
}

我该如何裁剪numpy数组,以便它给我一个像上面的边界矩形一样的图像?


Tags: rect图像imagenumpyimg数组filenamewidth
1条回答
网友
1楼 · 发布于 2024-05-17 06:58:32

原则上,只需将数组中正确的部分切掉,就可以轻松地进行裁剪。E、 g.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()

enter image description here

相关问题 更多 >