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

标签 python image numpy matplotlib

所以我有一个形状为 (224,244,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 数组,以便它给我一个像上面的边界矩形一样的图像?

最佳答案

原则上,只需从数组中切出正确的部分即可轻松完成裁剪。例如。 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": "/image/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

关于python - 从作为 Numpy 数组的图像裁剪边界框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41909408/

相关文章:

python - 在 Python/Pygame 中构建 Tilemap 并测试鼠标位置

python - 选择 tkinter 时按钮会立即改变颜色

c# - 我可以从 word 文件中检索图像和形状并将它们显示在 C# 的 PictureBox 控件中吗?

swift - UIImageView UIImage 字符串值 Swift 4

python - `numpy.random.normal` 在不同的系统上生成不同的数字

python - 使用 numpy.loadtxt 加载复数

python - 将 Flask 应用程序部署到 Bluehost(或任何)网络服务器是如何工作的?

python - 如何在 python 进程之间实时共享对象和数据?

php - 在 Laravel 中提供 PHP 图像资源作为响应

python - 不同大小数组的协方差近似