【问题标题】:Create Bounding Boxes from Image Labels从图像标签创建边界框
【发布时间】:2021-02-02 20:01:57
【问题描述】:

我有一个 2D 彩色图像和一个标签图像(标签的投影)

标签图片的输出如下:

[[16 16 16 ... 16 16 16 ]
 [16 16 16 ... 16 16 16 ]
 [16 16 16 ... 16 16 16 ]
 ...
 [ 2  2  2 ...  2  2  2 ]
 [ 2  2  2 ...  2  2  2 ]
 [ 2  2  2 ...  2  2  2 ]]

如何在原始 2D 彩色图像中的所有对象(由标签表示)周围绘制边界框?

【问题讨论】:

  • 你在做像素级分类吗?
  • 是的,这些是实例分割标签。每个像素对应一个标签(例如:1是椅子,2是床等等)
  • 你如何显示图像?
  • 使用 cv2.imread 和 cv2.imshow... 我想使用 cv2.rectangle 在彩色图像上显示地面实况边界框(我只有地面实况实例分割),但我没有不知道如何计算边界框角坐标。
  • 你能计算出属于每个边界框的点吗?如果是这样,您可以从那里获取角坐标。确定边界框的定义是您必须通过查看数据来回答的问题。

标签: python image-processing image-segmentation bounding-box


【解决方案1】:

使用 NumPy 的 boolean array indexing 和 OpenCV 的 boundingRect 函数可以轻松完成这项任务。

来自here,我拍了这张照片

还有这个分割掩码

掩码是索引图像,OpenCV 存在问题,另请参阅here。这就是为什么我们也会使用Pillow 来完成这项任务。

代码如下:

import cv2
import numpy as np
from PIL import Image

# Read color image
img = cv2.imread('0.jpg')

# Read mask; OpenCV can't handle indexed images, so we need Pillow here
# for that, see also: https://stackoverflow.com/q/59839709/11089932
mask = np.array(Image.open('0_mask.png'))

# Iterate all colors in mask
for color in np.unique(mask):

    # Color 0 is assumed to be background or artifacts
    if color == 0:
        continue

    # Determine bounding rectangle w.r.t. all pixels of the mask with
    # the current color
    x, y, w, h = cv2.boundingRect(np.uint8(mask == color))

    # Draw bounding rectangle to color image
    out = cv2.rectangle(img.copy(), (x, y), (x+w, y+h), (0, int(color), 0), 2)

    # Show image with bounding box
    cv2.imshow('img_' + str(color), out)

# Show mask
cv2.imshow('mask', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()

这些是输出:

我决定输出几张图像,因为对于给定的图像,边界框严重重叠。要将所有矩形绘制到同一张图片上,只需将对应的rectangle命令替换为

img = cv2.rectangle(img, (x, y), (x+w, y+h), (0, int(color), 0), 2)
----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.5
NumPy:       1.19.2
OpenCV:      4.4.0
Pillow:      7.2.0
----------------------------------------

【讨论】:

  • 谢谢,很有帮助!
猜你喜欢
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 2019-10-06
  • 1970-01-01
  • 1970-01-01
  • 2011-07-28
  • 2021-08-29
  • 1970-01-01
相关资源
最近更新 更多