【问题标题】:Get coordinates to generate bounding box from OpenCV output image获取坐标以从 OpenCV 输出图像生成边界框
【发布时间】:2019-02-09 20:40:09
【问题描述】:

我正在使用here 概述的 OpenCV GrabCut 算法来提取图像中的前景。

import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('messi5.jpg')
mask = np.zeros(img.shape[:2],np.uint8)

bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

rect = (50,50,450,290)
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)

mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]

现在我可以保存这张使用cv.imwrite('filename', img)获得的图像,输出图像只包含前景,背景被涂黑。

我想获取前景边界框的坐标为(LowerXcoordinate, LowerYcoordinate)(UpperXcoordinate, UpperYcoordinate)

我可以想象的一种方法是将图像视为像素的 2D 矩阵,以获取上 Y 坐标,从第 1 行开始并逐行检查所有像素的颜色值是否为黑色。具有非黑色像素的第一行将是前景开始的位置。同样,从 的最后一行开始,我可以得到较低的 Y 坐标。只需对列重复该过程即可获得 X 坐标。

目前我所知道的唯一天真的方法是手动编写循环来检查这一点。

有没有一些更简单的方法使用库函数来完成这个?

【问题讨论】:

    标签: image opencv image-processing


    【解决方案1】:

    确实比这容易得多!只需find the contours of your mask (docs),然后是轮廓的find the bounding rectangle (docs)

    _, contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    bounding_boxes = [cv2.boundingRect(contour) for contour in contours]
    

    这里注意,边界框将由(x, y, w, h)这四个项目表示,其中x, y是左上角,w, h分别是宽度和高度。掩码中的每个 blob 都会有一个边界框。

    另外,重要(烦人)的注意事项。旧版本的 OpenCV(我相信是 3.0 之前的版本)有 两个 来自 findContours() 的返回值;只是轮廓和层次结构。然后在 OpenCV 3 中进行了更改并返回了三个值:输入图像、轮廓和层次结构。在 OpenCV 4 中,这被改回了两个。因此,如果您不使用 OpenCV 3,请删除第一个 _

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      • 2015-08-10
      • 2020-07-20
      • 2022-01-05
      • 2015-08-08
      • 1970-01-01
      • 2021-01-05
      相关资源
      最近更新 更多