关于yolov5输出结果的相关问题

yolov5中对于已经得到的检测结果的图像处理,现在已经得到detcet结果,希望识别目标变成全黑,图片其余部分变为全白

为了实现您的需求,您需要对YOLOv5的输出进行后处理。在得到检测结果后,您可以使用OpenCV库创建一个全黑图像,并将检测到的目标区域涂成白色。

以下是一个使用Python和OpenCV实现的示例:

import cv2
import numpy as np

def draw_black_boxes(image, detections):
    # 创建一个全黑图像
    black_image = np.zeros_like(image)

    # 遍历检测结果
    for detection in detections:
        # 获取检测框的坐标(注意:这里使用的是左上角和右下角坐标)
        x1, y1, x2, y2 = detection

        # 将目标区域涂成白色
        black_image[y1:y2, x1:x2] = 255

    return black_image

def main():
    # 加载图像(这里使用的是YOLOv5的检测结果图像)
    input_image = cv2.imread("detections.jpg")

    # 检测结果(这里是一个示例,您需要使用YOLOv5的实际输出)
    detections = [
        (50, 50, 150, 150),
        (200, 200, 300, 300)
    ]

    # 生成黑白图像
    output_image = draw_black_boxes(input_image, detections)

    # 显示结果
    cv2.imshow("Result", output_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()

在这个示例中,detections是一个包含检测框坐标的列表。您需要用YOLOv5的实际输出替换这个示例。函数draw_black_boxes创建一个与输入图像大小相同的全黑图像,并根据检测结果将目标区域涂成白色。

请注意,这个示例使用的是Python和OpenCV库。

  • 这篇博客: 用YOLOv5ds训练自己的数据集——同时检测和分割中的 2-1、det文件夹下 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • Annotations文件夹下存放xml文件

    images文件夹下存放图像

    注:xml文件应和对应图像名称相同

    det文件夹下新建一个生成.py文件,使用下面代码生成ImageSets,里面有一个Main文件夹,Main文件夹里包括test.txt、train.txt、trainval.txt、val.txt四个文本文档

    trainval.txt包含你数据集里所有图像名称

    train.txt为数据集的训练集,为总数据集的90%

    val.txt为数据集的验证集,为总数据集的10%

    test.txt文件里是空的不用担心,因为没有划分测试集

    # coding:utf-8
    
    import os
    import random
    import argparse
    
    parser = argparse.ArgumentParser()
    #xml文件的地址,根据自己的数据进行修改xml一般存放在Annotations下
    parser.add_argument('--xml_path', default='/home/dell/yolov5ds-main/paper_data/det/Annotations', type=str, help='input xml label path')
    #数据集的划分,地址选择自己数据下的ImageSets/Main
    parser.add_argument('--txt_path', default='/home/dell/yolov5ds-main/paper_data/det/ImageSets/Main', type=str, help='output txt label path')
    opt = parser.parse_args()
    
    trainval_percent = 1.0
    train_percent = 0.9
    xmlfilepath = opt.xml_path
    txtsavepath = opt.txt_path
    total_xml = os.listdir(xmlfilepath)
    if not os.path.exists(txtsavepath):
        os.makedirs(txtsavepath)
    
    num = len(total_xml)
    list_index = range(num)
    tv = int(num * trainval_percent)
    tr = int(tv * train_percent)
    trainval = random.sample(list_index, tv)
    train = random.sample(trainval, tr)
    
    file_trainval = open(txtsavepath + '/trainval.txt', 'w')
    file_test = open(txtsavepath + '/test.txt', 'w')
    file_train = open(txtsavepath + '/train.txt', 'w')
    file_val = open(txtsavepath + '/val.txt', 'w')
    
    for i in list_index:
        name = total_xml[i][:-4] + '\n'
        if i in trainval:
            file_trainval.write(name)
            if i in train:
                file_train.write(name)
            else:
                file_val.write(name)
        else:
            file_test.write(name)
    
    file_trainval.close()
    file_train.close()
    file_val.close()
    file_test.close()
    
    

    在det文件夹下新建一个voc_labels.py文件,使用下面的程序将xml转换为yolo用的txt格式数据集

    注意修改数据集路径、类别,注意自己的图像是jpg还是png格式

    # -*- coding: utf-8 -*-
    import xml.etree.ElementTree as ET
    import os
    from os import getcwd
    
    sets = ['train', 'val', 'test']
    classes = ["feed", "person", "railing", "obstacle", "road", "cow"]   # 改成自己的类别
    abs_path = os.getcwd()
    print(abs_path)
    
    def convert(size, box):
        dw = 1. / (size[0])
        dh = 1. / (size[1])
        x = (box[0] + box[1]) / 2.0 - 1
        y = (box[2] + box[3]) / 2.0 - 1
        w = box[1] - box[0]
        h = box[3] - box[2]
        x = x * dw
        w = w * dw
        y = y * dh
        h = h * dh
        return x, y, w, h
    
    def convert_annotation(image_id):
        in_file = open('/home/dell/yolov5ds-main/paper_data/det/Annotations/%s.xml' % (image_id), encoding='UTF-8')
        out_file = open('/home/dell/yolov5ds-main/paper_data/det/labels/%s.txt' % (image_id), 'w')
        tree = ET.parse(in_file)
        root = tree.getroot()
        size = root.find('size')
        w = int(size.find('width').text)
        h = int(size.find('height').text)
        for obj in root.iter('object'):
            # difficult = obj.find('difficult').text
            difficult = obj.find('difficult').text###
            cls = obj.find('name').text
            if cls not in classes or int(difficult) == 1:
                continue
            cls_id = classes.index(cls)
            xmlbox = obj.find('bndbox')
            b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
                 float(xmlbox.find('ymax').text))
            b1, b2, b3, b4 = b
            # 标注越界修正
            if b2 > w:
                b2 = w
            if b4 > h:
                b4 = h
            b = (b1, b2, b3, b4)
            bb = convert((w, h), b)
            out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
    
    wd = getcwd()
    for image_set in sets:
        if not os.path.exists('/home/dell/yolov5ds-main/paper_data/det/labels/'):
            os.makedirs('/home/dell/yolov5ds-main/paper_data/det/labels/')
        image_ids = open('/home/dell/yolov5ds-main/paper_data/det/ImageSets/Main/%s.txt' % (image_set)).read().strip().split()
        list_file = open('./%s.txt' % (image_set), 'w')
        for image_id in image_ids:
            list_file.write(abs_path + '/images/%s.png\n' % (image_id))
            convert_annotation(image_id)
        list_file.close()
    
    

    运行之后会在det目录下生成train.txt、test.txt、val.txt三个文件,对应的图像名称前加入了绝对路径

    这是det文件夹结构

  • 以下回答由chatgpt基于相关博客总结生成:

    我可以提供以下解决方案:

    针对该问题,可以通过以下步骤处理yolov5的检测结果,使检测到的目标区域变成全黑,其余部分变为全白:

    1. 读取检测结果的图片,可以使用Python中的OpenCV库进行读取。比如,我们可以使用以下代码读取result.jpg:
    import cv2
    
    # read the detection result image
    img = cv2.imread('result.jpg')
    
    1. 将图片转换为灰度图,因为在灰度图中我们可以更方便地对像素进行处理。使用以下代码将彩色图转换为灰度图:
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    1. 对灰度图进行二值化处理,将灰度图中的目标区域变成全黑,其余部分变为全白。可以调用OpenCV中的threshold函数进行二值化处理,具体代码如下:
    # threshold the grayscale image
    ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV)
    

    在上述代码中,cv2.THRESH_BINARY_INV表示二值化后黑白颜色反转,即目标区域变成了全黑。

    1. 将二值化后的图像保存为文件,方便后续查看。可以使用以下代码将二值化后的图像保存为result_binary.jpg:
    # save the binary image
    cv2.imwrite('result_binary.jpg', binary)
    
    1. 完整的处理代码如下:
    import cv2
    
    # read the detection result image
    img = cv2.imread('result.jpg')
    
    # convert the image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # threshold the grayscale image
    ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV)
    
    # save the binary image
    cv2.imwrite('result_binary.jpg', binary)
    

    经过以上处理,我们就可以得到处理后的二值图像,其中检测到的目标区域是全黑的。

参考我之前的笔记,将识别框内容全部涂黑就行了,具体函数我都在博文里标了,然后就是参考上面貌似是chat的回答代码,基本就OK:

要实现这个功能,你需要在得到检测结果后,对图像进行后处理。具体操作如下:

  1. 根据检测结果,创建一个与原图像尺寸相同的全白图像。
  2. 遍历检测结果的边界框,并将这些区域设置为全黑。

下面是一个使用Python和OpenCV实现的示例:

import cv2
import numpy as np

# 加载图像和检测结果
image_path = 'path/to/your/image.jpg'
image = cv2.imread(image_path)

# 这里是一个示例检测结果,你需要将其替换为你自己的检测结果
# 检测结果格式:[x1, y1, x2, y2]
detection_results = [
    [50, 50, 200, 200],
    [300, 300, 450, 450]
]

# 创建一个与原图像尺寸相同的全白图像
result_image = np.ones_like(image) * 255

# 遍历检测结果的边界框,并将这些区域设置为全黑
for bbox in detection_results:
    x1, y1, x2, y2 = bbox
    result_image[y1:y2, x1:x2] = 0

# 显示结果图像
cv2.imshow('Result', result_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 保存结果图像
cv2.imwrite('result.jpg', result_image)

在这个示例中,我们首先创建了一个与原图像尺寸相同的全白图像。然后,我们遍历检测结果的边界框,将对应区域设置为全黑。最后,我们显示并保存结果图像。

请注意,你需要根据实际情况修改image_pathdetection_results