当前位置: 移动技术网 > IT编程>脚本编程>Python > yolo 根据标签画识别框

yolo 根据标签画识别框

2020年07月16日  | 移动技术网IT编程  | 我要评论
# -*- coding: utf-8 -*-
import os
import pandas as pd
from PIL import Image
from PIL import ImageDraw, ImageFont

def draw_img(img_path, boxes):
    img = Image.open(img_path)
    draw = ImageDraw.Draw(img)
    w, h = img.size
    for top, left, bottom, right in boxes:

        x = float(top) * w
        y = float(left) * h
        xx = float(bottom) * w
        yy = float(right) * h

        draw.rectangle([x, y, xx, yy], fill=None, outline=(0, 255, 0), width=5)
        # draw.text((x, y),
        #           line_parts[0] , fill=(255, 0, 0),
        #           font=font)
    del draw
    img.save(box_dir + '/box' + os.path.split(img_path)[-1])


def draw_images(images_dir, txt_dir, box_dir, font_type_path):
    font = ImageFont.truetype(font_type_path, 50)
    if not os.path.exists(box_dir):
        os.makedirs(box_dir)
    for file in os.listdir(txt_dir):
        print(file)
        image = os.path.splitext(file)[0].replace('xml', 'jpg') + '.jpg'
        # image = os.path.splitext(file)[0].replace('xml', 'jpg')
        img = Image.open(images_dir + '/' + image)

        if img.mode == "P":
            img = img.convert('RGB')

        w, h = img.size
        tag_path = txt_dir + '/' + file
        with open(tag_path) as f:
            for line in f:
                line_parts = line.split(' ')
                draw = ImageDraw.Draw(img)
                if int(line_parts[0]) not in [7]:
                    continue
                x = (float(line_parts[1]) - 0.5 * float(line_parts[3])) * w
                y = (float(line_parts[2]) - 0.5 * float(line_parts[4])) * h
                xx = (float(line_parts[1]) + 0.5 * float(line_parts[3])) * w
                yy = (float(line_parts[2]) + 0.5 * float(line_parts[4])) * h
                # x = float(line_parts[1])
                # y = float(line_parts[2])
                # xx = float(line_parts[3])
                # yy = float(line_parts[4])

                draw.rectangle([x-10, y-10, xx, yy], fill=None, outline=(0, 255, 0),width=5)
                # draw.text((x, y),
                #           line_parts[0] , fill=(255, 0, 0),
                #           font=font)
            del draw
            img.save(box_dir + '/' + image)


root_dir = '../data/'  #根目录

font_type_path = 'C:/Windows/Fonts/simsun.ttc'
# fontText = ImageFont.truetype("C:/Windows/Fonts/simsun.ttc", 10, encoding="utf-8")
box_dir = root_dir + '/box/'
txt_dir = root_dir + '/tmp_label/'
image_source_dir = root_dir + '/tmp_img/'
draw_images(image_source_dir, txt_dir, box_dir, font_type_path)

本文地址:https://blog.csdn.net/mndlgzzd/article/details/107371465

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网