【问题标题】:Multiple bounding-boxes with cv2.rectangle()带有 cv2.rectangle() 的多个边界框
【发布时间】:2021-06-15 04:37:32
【问题描述】:

我目前有边界框的坐标数据,包含在嵌套数据结构中,如下所示:

 defaultdict(list,
            {'giraffe': [{'conf': 0.9869,
               'coords': {'center_x': 0.360333,
                'center_y': 0.532274,
                'height': 0.596343,
                'width': 0.144651}},
              {'conf': 0.253321,
               'coords': {'center_x': 0.016296,
                'center_y': 0.565007,
                'height': 0.580526,
                'width': 0.03498}}],
             'zebra': [{'conf': 0.998863,
               'coords': {'center_x': 0.545974,
                'center_y': 0.693267,
                'height': 0.301859,
                'width': 0.257102}}]})

我想遍历数据结构 (img_obj_data) 并为每个 object_class 的每个对象绘制矩形。

然后我想保存图像(绘制了框),以便稍后打开它。

我的第一次尝试如下:

import cv2

img = cv2.imread(img_path)
img_h, img_w = img.shape[:2]

for obj_class in img_obj_data.keys():
    for sub_dict in img_obj_data[obj_class]:
        x, y, w, h = sub_dict['coords'].values()
        
        # coords cannot be floats
        x = int(x*img_w)
        y = int(y*img_h)
        x_max = int(w*img_w)
        y_max = int(y*img_h)

        cv2.rectangle(img, (x, y), (x_max, y_max), color=(0, 255, 0), thickness=2)
cv2.imwrite('/content/foobar.jpg', img)

我现在遇到了两个问题:

问题 1) 边界框未与对象正确对齐并从图像中裁剪出来。 (坐标原本是浮点数,我将它们乘以图像的宽度和高度,但我有预感这是不正确的做法?)

问题 2)

我的代码目前所有框的颜色都相同。我怎样才能做到这一点,以便每个对象类的颜色不同?

这是有问题的图像,以及我的代码生成的图像:

【问题讨论】:

  • 你能把x, y, w, h = sub_dict['coords'].values()改成x, y, h, w = sub_dict['coords'].values()吗?这不是解决办法,而是要同台竞技。
  • @pond27 是的,我也想到了!将x, y, w, h 的顺序切换为x, y, h, w 会导致更大的边界框仍然未对齐。
  • 我的意思是,为了得到你的结果图像,你的 w, h 的 sn-p 应该被切换。
  • @pond27 我刚刚重新生成了图像。我的 sn-p 是x, y, w, h,生成的图像与我在此处发布的图像相同。切换顺序仍然会重现未对齐的框。
  • @pond27 我想你几乎成功了。矩形是一种改进(它们框住了动物),但它们仍然很大并且超出了图像范围。

标签: python opencv yolo bounding-box


【解决方案1】:

其中一个例子如下。 *如有必要,请根据您的环境切换hw

import cv2
from random import randint

img = cv2.imread(img_path)
img_h, img_w = img.shape[:2]
colors = {}

for obj_class in img_obj_data.keys():
    if obj_class not in colors:
        colors[obj_class] = [randint(0, 255), randint(0, 255), randint(0, 255)]

    for sub_dict in img_obj_data[obj_class]:
        x, y, h, w = sub_dict['coords'].values()
        # coords cannot be floats
        x_min = int((x-w/2)*img_w)
        y_min = int((y-h/2)*img_h)
        x_max = int((x+w/2)*img_w)
        y_max = int((y+h/2)*img_h)
        cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color=colors[obj_class], thickness=2)
cv2.imwrite('/content/foobar.jpg', img)

这个例子通过类名随机改变颜色,但是如果你知道类名,你可以提前定义colors

【讨论】:

    猜你喜欢
    • 2018-10-11
    • 2019-07-16
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    相关资源
    最近更新 更多