python将txt坐标批量打印到原图上

# -*- coding: utf-8 -*-
# liufangtao
#批量处理img和xml文件,根据xml文件中的坐标把img中的目标标记出来,并保存到指定文件夹。
import xml.etree.ElementTree as ET
import os, cv2
import numpy 
# from tqdm import tqdm
from PIL import Image, ImageDraw, ImageFont

annota_dir = r'\ann\atxt' #txt文件夹
origin_dir = r'\testjyz\ann\bimages'  #图片文件夹
target_dir1= r'\testjyz\ann\cresult'  #保存地址

class_dist = {0:'盘式绝缘子', 1:'棒式绝缘子', 2:'复合绝缘子', 
                        3:'柱上开关绝缘子', 4:'针式绝缘子', 5:'玻璃绝缘子',6:'悬式棒绝缘子'}
        

def divide_img(oriname):
    img_file = os.path.join(origin_dir, oriname + '.jpg')
    im = cv2.imread(img_file)
    h, w = im.shape[:2]
    # print(w)
    # 图像从OpenCV格式转换成PIL格式 
    img_PIL = Image.fromarray(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(img_PIL)
    #字体路径和字体大小
    font = ImageFont.truetype('SimHei.ttf', 40) 

    xml_file = open(os.path.join(annota_dir, oriname + '.txt'))  # 读取每个原图像的xml文件
    # print(xml_file)
    for bbox in xml_file.readlines():
        id, x1, y1, x2, y2 = float(bbox.split(' ')[0]), float(bbox.split(' ')[1]), float(bbox.split(' ')[2]), float(bbox.split(' ')[3]), float(bbox.split(' ')[4])
        xmin = ((x1*2*w)-x2*w)/2
        xmax = ((x1*2*w)+x2*w)/2
        ymin = ((y1*2*h)-y2*h)/2
        ymax = ((y1*2*h)+y2*h)/2

        # print(xmin, ymin, xmax, ymax)
        # cv2.rectangle(image, (x1, y1), (x2, y2), (0, 0, 255), 2)
        # 在边界框的两点(左上角、右下角)画矩形,无填充,边框红色,边框像素为5
        draw.rectangle(((xmin, ymin), (xmax, ymax)), fill=None, outline='red', width=5)
        draw.text((xmin, ymin-40), class_dist[id], font=font, fill=(0, 255, 0))       
    
    # 转换回OpenCV格式 
    img_OpenCV = cv2.cvtColor(numpy.asarray(img_PIL),cv2.COLOR_RGB2BGR) 
    img_name = oriname + '.jpg'
    print(img_name)
    to_name = os.path.join(target_dir1, img_name)
    cv2.imwrite(to_name, img_OpenCV)

img_list = os.listdir(origin_dir)

for name in img_list:
    divide_img(name.rstrip('.jpg'))

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

慕容洛凝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值