【问题标题】:OpenCV Rectangle FilledOpenCV矩形填充
【发布时间】:2019-03-01 17:38:39
【问题描述】:

我正在尝试填充矩形,但即使更改代码(将厚度更改为 -10)也没有效果。我觉得这与全球有关。

我附上了下面的代码。

import cv2
import os
import numpy as np
from .utils import download_file

initialize = True
net = None
dest_dir = os.path.expanduser('~') + os.path.sep + '.cvlib' + os.path.sep + 'object_detection' + os.path.sep + 'yolo' + os.path.sep + 'yolov3'
classes = None
COLORS = np.random.uniform(0, 255, size=(80, 3))




def draw_bbox(img, bbox, labels, confidence, colors=None, write_conf=False):

    global COLORS
    global classes

    if classes is None:
        classes = populate_class_labels()

    for i, label in enumerate(labels):

        if colors is None:
            color = COLORS[classes.index(label)]            
        else:
            color = colors[classes.index(label)]

        if write_conf:
            label += ' ' + str(format(confidence[i] * 100, '.2f')) + '%'

        cv2.rectangle(img, (bbox[i][0],bbox[i][1]), (bbox[i][2],bbox[i][3]), color,-1)
        cv2.putText(img, label, (bbox[i][0],bbox[i][1]-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

    return img

def detect_common_objects(image):

    Height, Width = image.shape[:2]
    scale = 0.00392

    global classes
    global dest_dir

    config_file_name = 'yolov3.cfg'
    config_file_abs_path = dest_dir + os.path.sep + config_file_name

    weights_file_name = 'yolov3.weights'
    weights_file_abs_path = dest_dir + os.path.sep + weights_file_name    

    url = 'https://github.com/arunponnusamy/object-detection-opencv/raw/master/yolov3.cfg'

    if not os.path.exists(config_file_abs_path):
        download_file(url=url, file_name=config_file_name, dest_dir=dest_dir)

    url = 'https://pjreddie.com/media/files/yolov3.weights'

    if not os.path.exists(weights_file_abs_path):
        download_file(url=url, file_name=weights_file_name, dest_dir=dest_dir)    

    global initialize
    global net

    if initialize:
        classes = populate_class_labels()
        net = cv2.dnn.readNet(weights_file_abs_path, config_file_abs_path)
        initialize = False

    blob = cv2.dnn.blobFromImage(image, scale, (416,416), (0,0,0), True, crop=False)

    net.setInput(blob)

    outs = net.forward(get_output_layers(net))

    class_ids = []
    confidences = []
    boxes = []
    conf_threshold = 0.5
    nms_threshold = 0.4

    for out in outs:
        for detection in out:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.5 and class_id=='person':
                center_x = int(detection[0] * Width)
                center_y = int(detection[1] * Height)
                w = int(detection[2] * Width)
                h = int(detection[3] * Height)
                x = center_x - w / 2
                y = center_y - h / 2
                class_ids.append(class_id)
                confidences.append(float(confidence))
                boxes.append([x, y, w, h])


    indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)

    bbox = []
    label = []
    conf = []

    for i in indices:
        i = i[0]
        box = boxes[i]
        x = box[0]
        y = box[1]
        w = box[2]
        h = box[3]
        if str(classes[class_ids[i]])=='person':
            bbox.append([round(x), round(y), round(x+w), round(y+h)])
            label.append(str(classes[class_ids[i]]))
            conf.append(confidences[i])

    return bbox, label, conf

整个代码如上。它是一个使用 Yolo 和 opencv 的对象检测程序。我还在最后一行添加了几行以仅启用人员类,但它似乎检测到所有类。我也尝试过修改矩形的粗细,但更改值没有效果。

【问题讨论】:

  • 你不需要在函数中声明全局变量除非你实际上是在修改值;你没有改变COLORS,所以你不需要将它声明为global。你如何定义bboxlabels?否则很难回答你的问题......
  • bbox 和 label 最后定义为函数 detect_common_objects。
  • 请将您的问题压缩为minimal, complete, and verifiable 示例。我知道您留下部分代码是为了不在这里转储大量代码,但是转储大量代码和不完整代码都没有帮助。给出一个实际的例子,并附上一张图片,它具有复制问题的绝对最少代码量。即,加载单个图像,手动定义单个边界框,然后绘制它。
  • 以上是绝对最小值,因为目标检测程序需要以上所有功能。我附上了一张照片。
  • 不,不是,正如您所说,问题在于在图像上绘制框。如果您可以获得在框上绘制图片的代码,那么这不是您的问题并且可以从问题中消除,并且您的问题从“我的程序没有填充矩形”变为“yolo 没有检测到我想要的东西。 "您的程序显然比仅绘制填充矩形要多得多。例如您正在根据某个置信度阈值过滤内容,这与绘制矩形完全无关......

标签: python image opencv video cvlib


【解决方案1】:

您只需将 -10 更改为 -1。更改后您的代码将如下所示

def draw_bbox(img, bbox, labels, confidence, colors=None, write_conf=False):

    global COLORS
    global classes

    if classes is None:
        classes = populate_class_labels()

    for i, label in enumerate(labels):

        if colors is None:
            color = COLORS[classes.index(label)]            
        else:
            color = colors[classes.index(label)]

        if write_conf:
            label += ' ' + str(format(confidence[i] * 100, '.2f')) + '%'

        cv2.rectangle(img, (bbox[i][0],bbox[i][1]), (bbox[i][2],bbox[i][3]), color,-1)
        cv2.putText(img, label, (bbox[i][0],bbox[i][1]-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

    return img

【讨论】:

  • 我做了以下更改,但没有效果。
  • 错误是什么,因为我在本地尝试过并且能够填充矩形。
  • 真的吗?矩形没有被填充。
  • 哈哈,哥们,你换个问题了……你遇到什么问题了??
  • 我的问题是矩形没有被填充。我改变了我的问题,因为我认为我的代码的另一部分可能会影响我的 cv2.rectangle 函数。
【解决方案2】:

我确实犯了一个愚蠢的错误。我正在更改我的 Github 文件夹中的 object/detection.py 文件。然而,当我看到这一切时,一切都变得有意义了。

File "/Users/dukeglacia/anaconda3/lib/python3.6/site-packages/cvlib/object_detection.py"

我实际上是在更改错误的文件(虽然最初完全一样)。

【讨论】:

    【解决方案3】:

    我有一个矩形边界并用于填充这些矩形。放“-1”

    cv2.rectangle(frame, (x, y), (w, h), (255, 255, 255), -1)
    

    【讨论】:

    • 错误..不起作用..它填满了整个文档