栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

通过opencv标记图片以及写入Excel小方法

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过opencv标记图片以及写入Excel小方法

通过opencv标记图片以及写入Excel小方法
    • 通过opencv根据坐标绘制图片框,然后保存图片
    • 将结果读入并且写入Excel中进行保存
    • Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
    • Python rstrip() 删除 string 字符串末尾的指定字符(默认为空格)
    • Python rstrip() 删除 string 字符串头的指定字符(默认为空格)

通过opencv根据坐标绘制图片框,然后保存图片
import xml.etree.ElementTree as ET   #用于读取xml文件
import os, cv2


annota_dir = r'./train/train2021/Annotations/'
img_dir = r'./train/train2021/JPEGImages/'

def divide_img(oriname):
    img_file = os.path.join(img_dir, oriname + '.png')
    im = cv2.imread(img_file)   #cv读取图片
    print(oriname)
    xml_file = os.path.join(annota_dir, oriname + '.xml')  # 读取每个原图像的xml文件
    print(xml_file)
    tree = ET.parse(xml_file)
    root = tree.getroot()

    for object in root.findall('object'):
        object_name = object.find('name').text
        if(object_name == 'with_mask'):
            color = (20, 250, 27)
        elif(object_name == 'without_mask'):
            color = (27,24,250)
        else:
            color = (20, 250, 250)
        Xmin = int(object.find('bndbox').find('xmin').text)
        Ymin = int(object.find('bndbox').find('ymin').text)
        Xmax = int(object.find('bndbox').find('xmax').text)
        Ymax = int(object.find('bndbox').find('ymax').text)

        cv2.rectangle(im, (Xmin, Ymin), (Xmax, Ymax),color, 2)
        font = cv2.FONT_HERSHEY_SIMPLEX   #选择字体
        #cv2.putText(im, object_name, (Xmin, Ymin - 7), font, 0.5, color, 2)
        #cv2.imshow('01', im)
        cv2.waitKey(0)
    cv2.imwrite(r'./trainlabel/'+oriname+'.png',im)   #保存图片


img_list = os.listdir(img_dir)   #读入文件列表
print(img_list)
for name in img_list:
    divide_img(name.rstrip('.png'))  #删除字符串末尾的.png   

将结果读入并且写入Excel中进行保存
import xlsxwriter
import os, cv2

w = 'D:\tensorflowstudydata\saiti\daima\ppyolov2\PaddleDetection\output\data\'
annota_dir = os.listdir(w)
f = xlsxwriter.Workbook('data.xlsx')
sheet = f.add_worksheet('sheet1')   #添加工作表
i = 0
k = 0
for q in annota_dir:
    path = w+q
    f1 = open(path,'r',encoding='gbk')
    lines = f1.readlines()
    for line in lines:
        print(line)
        sheet.write(i,k,str(line).split(" ")[0])  #通过横纵坐标控制单元格

        i = i + 1
    k+=1
    i=0

f.close()

Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。 Python rstrip() 删除 string 字符串末尾的指定字符(默认为空格) Python rstrip() 删除 string 字符串头的指定字符(默认为空格)
str = "888888888888kkk    kkkkisisisisiisisisikkk  kkkk8888888888888888"
str1 = "        op       "
str1 = str1.strip()
print(str1)     #op
str = str.rstrip("8")
print(str)
str = str.lstrip("8")
print(str)
#结果:
#op
#888888888888kkk    kkkkisisisisiisisisikkk  kkkk
#kkk    kkkkisisisisiisisisikkk  kkkk

完结撒花!!!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/487793.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号