python - 从图像标签创建边界框

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

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

标签图片输出如下:

[[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 彩色图像中的所有对象(由标签表示)周围绘制边界框?

最佳答案

使用 NumPy 的 boolean array indexing 可以轻松完成此任务和 OpenCV 的 boundingRect功能。

来自 here , 我拍了这张照片

image

和这个分割掩码

mask

掩码是索引图像,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()

这些是输出:

Outputs

我决定输出几张图片,因为对于给定的图片,边界框严重重叠。要将所有矩形绘制到同一张图像上,只需将相应的 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
----------------------------------------

关于python - 从图像标签创建边界框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64437590/

相关文章:

python - 从现有数据框中列的子字符串创建新的 Pyspark 数据框

node.js - 使用 Node.js 在现有 PNG 上编写文本

python - IoU 在 python/caffe 中实现每个类的语义分割

python - 将晦涩的文件类型输入到tensorflow中

python - 使用 Python 3.5 安装 numpy Windows 8 64

python - 筛选“pandas”中不包含字母(alpha)的所有行

java - 如何将图像转换为 0-255 灰度图像

c# - 图像处理 - 在不去除的情况下减少物体厚度

OpenCV 地板分割检测

python - 分割后如何去除前景中的阴影?