OpenCV 矩形填充

15

输入图像描述我试图填充这个矩形,但是即使将代码更改为(将厚度更改为-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”。您如何定义“bbox”和“labels”?否则很难回答您的问题... - alkasm
bbox和label在detect_common_objects函数中被定义。 - robotlover
请将您的问题压缩成一个最小,完整和可验证的示例。我知道您留下了部分代码,以避免在此处转储大量代码,但是转储大量代码和不完整的代码都没有帮助。给出一个实际的示例,包括图片,其中包含绝对最少量的代码来复制该问题。即加载单个图像,手动定义单个边界框并绘制它。 - alkasm
以上是绝对最低要求,因为对象检测程序需要上述所有功能。我已经附上一张照片。 - robotlover
1
不是这样的,正如你所说,问题在于在图像上绘制框。如果您可以获得绘制图片框的代码,则这不是您的问题,并且可以从问题中消除,您的问题将从“我的程序未填充矩形”变为“yolo未检测到我想要的内容”。您的程序显然做了很多其他事情,而不仅仅是绘制填充的矩形。例如,您正在基于某些置信度阈值过滤内容,这与绘制矩形毫无关系... - alkasm
抱歉。我的问题是,尽管我将厚度的值设为-1,但我无法获得一个填充的矩形(如上所示)。我将编辑我的问题。然而,我的问题不是yolo没有检测到我想要的东西。它正在检测到我想要的东西,但我希望矩形(绘制在检测到的对象周围)被填充。 - robotlover
3个回答

10

我有一个矩形边界,需要填充这些矩形。请使用"-1"进行填充。

cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 255, 255), -1)

错误...不起作用...它填满了整个文档。 - Vikram Murthy
@VikramMurthy,答案中有一个错误 - 第三个参数应该是(x2,y2),而不是(w,h)。 - Filip Happy

9

您只需要将-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

我已经做了以下更改,但没有任何效果。 - robotlover
什么错误?因为我在本地尝试过,能够得到填充矩形。 - spaceman
真的吗?矩形没有被填充。 - robotlover
哈哈,伙计,你改变了你的问题...你面临的问题是什么? - spaceman
那么我怀疑你没有使用这个函数在图像上绘制矩形。 - spaceman
显示剩余5条评论

1

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

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

实际上,我更改了错误的文件(原始文件完全相同)。


谢谢你承认了这件事。这样故事就完整了:D - Michael Currie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接