gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:12:35 25 4
gpt4 key购买 nike

所以我有一个形状为 (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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com