detectron2中save_text_instance_predictions⭐

news2024/10/7 12:38:55

save_text_instance_predictions

  • demo.py中修改
    • 关于路径
      • os.path.join()函数用于路径拼接文件路径,可以传入多个路径
      • os.path.basename(path)就是给定一串路径的最终找到的那个文件
      • python官方文档链接
    • 将 Python 对象序列化为 JSON 字符串
      • with open 打开文件,并以写入模式 **创建或覆盖 ** 文件
      • 使用 json.JSONEncoder() 方法
      • dump、dumps序列化为json格式和序列化为json字符串,区别?(用到再说)
        • 保存列表为.txt文件
        • python对CSV、Excel、txt、dat、mat文件的处理
      • python将数据保存为json文件时,打开json文件里面的中文发现是unicode码
      • with open(os.path.join(args.output, "data.json"), "a") as file: 读写文件参数
    • predictor.py
    • visualizer.py中save_text_instance_predictions(deepsolo/adet/visualizer.py,import了 detectron2的visualizer.py⭐

demo.py中修改

import json

## 生成json格式的数据
class Result:
    def __init__(self, id, image, value):
        self.id = id
        self.image = image
        self.value = value


def result_encoder(obj):
    if isinstance(obj, Result):
        return {'id': obj.id, 'image': obj.image, 'value': obj.value}
    return json.JSONEncoder.default(obj)
    

    visualized_output.save(out_filename)
    #predictions.save(out_filename)
    #print(predictions)
    res = Result(os.path.basename(path), out_filename, text_output)
    with open(os.path.join(args.output, "data.json"), "a", encoding="utf8") as file:
        json.dump(result_encoder(res), file, ensure_ascii=False, indent=4)

关于路径

assert os.path.isdir(args.output), args.output 
	out_filename = os.path.join(args.output, os.path.basename(path))

Python编程语言判断是否是目录

在Python编程语言中可以使用os.path.isdir()函数判断某一路径是否为目录。其函数原型如下所示。

os.path.isdir(path) 

其参数含义如下。path 要进行判断的路径。以下实例判断E:\book\temp是否为目录。

>>> import os  
>>> os.path.isdir('E:\\book\\temp') 

判断E:\book\temp是否为目录

True 表示 E:\book\temp是目录,注意力 python里面是True不是true

os.path.join()函数用于路径拼接文件路径,可以传入多个路径

>>> import os
>>> print(os.path.join('path','abc','yyy'))
path\abc\yyy

os.path.basename(path)就是给定一串路径的最终找到的那个文件

在这里插入图片描述
在这里插入图片描述
来个例子

import os
# --------------------------------------------------------#
filePath = r"D:\Python\Python35\Lib\site-packages\jieba\analyse\idf.txt"
print('路径为:',filePath)
print(os.path.basename(filePath))
print(os.path.dirname(filePath))
# --------------------------------------------------------#
filePath = r'D:\Python\Python35\Lib\site-packages\jieba'
print('路径为:',filePath)
print(os.path.basename(filePath))
print(os.path.dirname(filePath))

输出

路径为: D:\Python\Python35\Lib\site-packages\jieba\analyse\idf.txt
idf.txt
D:\Python\Python35\Lib\site-packages\jieba\analyse
路径为: D:\Python\Python35\Lib\site-packages\jieba
jieba
D:\Python\Python35\Lib\site-packages
————————————————

原文链接:https://blog.csdn.net/m0_46653437/article/details/115876616

python官方文档链接

将 Python 对象序列化为 JSON 字符串

with open 打开文件,并以写入模式 **创建或覆盖 ** 文件

这段很基础对我很重要,一开始在想,是否需要手动创建之后才能with open……,如果不存在,会自动创建

import json

# 创建一个字典对象


data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# 打开文件,并以写入模式创建或覆盖文件
with open("data.json", "w") as file:
    # 将字典对象转换为JSON格式并写入文件
    json.dump(data, file)

上述代码将创建一个名为data.json的JSON文件,并将data字典对象写入文件中。如果你想要格式化输出的JSON文件,使其更易读,你可以使用indent参数指定缩进级别,如下所示:

import json

data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

with open("data.json", "w") as file:
    json.dump(data, file, indent=4)

作者:百科全书77
链接:https://www.zhihu.com/question/631483792/answer/3299538515
来源:知乎

使用 json.JSONEncoder() 方法

我们还可以使用 json.JSONEncoder() 方法来创建自定义的编码器,将 Python 对象序列化为 JSON 字符串,然后将其写入文件。以下是一个示例:

import json
 
class Person:
    def __init__(self, name, age, city):
        self.name = name
        self.age = age
        self.city = city
 
def person_encoder(obj):
    if isinstance(obj, Person):
        return {'name': obj.name, 'age': obj.age, 'city': obj.city}
    return json.JSONEncoder.default(obj)
 
person = Person('John', 30, 'New York')
 
with open('data.json', 'w') as f:
    json_str = json.dumps(person, default=person_encoder)
    f.write(json_str)

在这个示例中,我们首先定义了一个自定义的类 Person,然后定义了一个自定义的编码器 person_encoder,将 Person 对象序列化为 JSON 格式。最后,我们使用 json.dumps() 方法将 Person 对象序列化为 JSON 字符串,并将其写入文件 data.json 中。

原文链接:Python 如何创建 json 文件?

dump、dumps序列化为json格式和序列化为json字符串,区别?(用到再说)

import json
 
data = {'name': 'John', 'age': 30, 'city': 'New York'}
 
with open('data.json', 'w') as f:
    json.dump(data, f)

在这个示例中,我们使用了 json.dump() 方法将 Python 字典对象 data 序列化为 JSON 格式,并将其写入到文件 data.json 中。

除了使用 json.dump() 方法直接将 Python 对象写入到文件中,我们还可以使用 json.dumps() 方法将 Python 对象序列化为 JSON 字符串,然后将其写入文件。以下是一个示例:

import json
 
data = {'name': 'John', 'age': 30, 'city': 'New York'}
 
with open('data.json', 'w') as f:
    json_str = json.dumps(data)
    f.write(json_str)

在这个示例中,我们首先使用 json.dumps() 方法将 Python 字典对象 data 序列化为 JSON 字符串,然后使用文件对象的 write() 方法将其写入文件 data.json 中。
在这里插入图片描述
python中dict和json的转换以及读取json文件
python 把字典转json
将dict类型变量转换为json存在dump和dumps两个方法
dump将dict转换为str类型
注意
如果想将dict输出到文件中,直接用dumps即可,如果先dump再dumps就会输出一整个字符串,因为有引号的存在并不是正常的json格式

保存列表为.txt文件
#1/list写入txt

ipTable = ['158.59.194.213', '18.9.14.13', '58.59.14.21']  
fileObject = open('sampleList.txt', 'w')  
for ip in ipTable:  
    fileObject.write(ip)  
    fileObject.write('\n')  
fileObject.close()  

python对CSV、Excel、txt、dat、mat文件的处理

python将数据保存为json文件时,打开json文件里面的中文发现是unicode码

开保存之后的json文件发现除了字母,原来的字典数据里面的中文全部变成了unicode码,像下面这个样子
在这里插入图片描述

Python 使用 json.dump() 保存文件时中文会变成 Unicode。在打开写出文件时加入 encoding="utf8",在dump时加入 ensure_ascii=False 即可解决。

city_list = [{"name": "黑龙江呼玛", "lon": 126.6, "lat": 51.72}, 
			/{"name": "黑龙江塔河", "lon": 124.7, "lat": 52.32}, 
			/{"name": "黑龙江漠河", "lon": 122.37, "lat": 53.48}]
f = open("city.json", "w", encoding="utf8")
json.dump(city_list, f, ensure_ascii=False)

总结一下:

1、python3里面默认编码是unicode

2、做dump与dumps操作时,会默认将中文转换为unicode,但在做逆向操作load和loads时会转换为中文,但是中间态(例如存储的json文件)的中文编码方式仍然是unicode

解决办法:
在dump里面添加ensure_ascii=False
原文链接

with open(os.path.join(args.output, “data.json”), “a”) as file: 读写文件参数

在这里插入图片描述
Python实现将内容写入文件的五种方法总结

predictor.py

def run_on_image(self, image):

……
 else:
     if "sem_seg" in predictions:
          vis_output = visualizer.draw_sem_seg(
              predictions["sem_seg"].argmax(dim=0).to(self.cpu_device))
      if "instances" in predictions:
          instances = predictions["instances"].to(self.cpu_device)
          vis_output = visualizer.draw_instance_predictions(predictions=instances)
          
  text_output = visualizer.save_text_instance_predictions(predictions=instances)

  return predictions, vis_output,text_output

追溯到 visualizer.py写的save_text_instance_predictions 函数

visualizer.py中save_text_instance_predictions(deepsolo/adet/visualizer.py,import了 detectron2的visualizer.py⭐

class TextVisualizer(Visualizer):
……

    def _ctc_decode_recognition(self, rec):
        last_char = '###'
        s = ''
        for c in rec:
            c = int(c)
            if c < self.voc_size - 1:
                if last_char != c:
                    if self.voc_size == 37 or self.voc_size == 96:
                        s += self.CTLABELS[c]
                        last_char = c
                    else:
                        s += str(chr(self.CTLABELS[c]))
                        last_char = c
            else:
                last_char = '###'
        return s

    def draw_instance_predictions(self, predictions):
        ctrl_pnts = predictions.ctrl_points.numpy()
        scores = predictions.scores.tolist()
        recs = predictions.recs
        bd_pts = np.asarray(predictions.bd)

        self.overlay_instances(ctrl_pnts, scores, recs, bd_pts)

        return self.output
    def overlay_instances(self, ctrl_pnts, scores, recs, bd_pnts, alpha=0.4):
        colors = [(0,0.5,0),(0,0.75,0),(1,0,1),(0.75,0,0.75),(0.5,0,0.5),(1,0,0),(0.75,0,0),(0.5,0,0),
        (0,0,1),(0,0,0.75),(0.75,0.25,0.25),(0.75,0.5,0.5),(0,0.75,0.75),(0,0.5,0.5),(0,0.3,0.75)]
        fg=True
        for ctrl_pnt, score, rec, bd in zip(ctrl_pnts, scores, recs, bd_pnts):
            color = random.choice(colors)

            # draw polygons
            if bd is not None:
                bd = np.hsplit(bd, 2)
                bd = np.vstack([bd[0], bd[1][::-1]])
                self.draw_polygon(bd, color, alpha=alpha)

            # draw center lines
            line = self._process_ctrl_pnt(ctrl_pnt)
            line_ = LineString(line)
            center_point = np.array(line_.interpolate(0.5, normalized=True).coords[0], dtype=np.int32)
            # self.draw_line(
            #     line[:, 0],
            #     line[:, 1],
            #     color=color,
            #     linewidth=2
            # )
            # for pt in line:
            #     self.draw_circle(pt, 'w', radius=4)
            #     self.draw_circle(pt, 'r', radius=2)

            # draw text
            text = self._ctc_decode_recognition(rec)

            if self.voc_size == 37:
                text = text.upper()
            # text = "{:.2f}: {}".format(score, text)
            text = "{}".format(text)
            
            lighter_color = self._change_color_brightness(color, brightness_factor=0)
            if bd is not None:
                text_pos = bd[0] - np.array([0,15])
            else:
                text_pos = center_point
            horiz_align = "left"
            font_size = self._default_font_size
            self.draw_text(
                        text,
                        text_pos,
                        color=lighter_color,
                        horizontal_alignment=horiz_align,
                        font_size=font_size,
                        draw_chinese=False if self.voc_size == 37 or self.voc_size == 96 else True
                    )


    def draw_text(
        self,
        text,
        position,
        *,
        font_size=None,
        color="g",
        horizontal_alignment="center",
        rotation=0,
        draw_chinese=False
    ):
        """
        Args:
            text (str): class label
            position (tuple): a tuple of the x and y coordinates to place text on image.
            font_size (int, optional): font of the text. If not provided, a font size
                proportional to the image width is calculated and used.
            color: color of the text. Refer to `matplotlib.colors` for full list
                of formats that are accepted.
            horizontal_alignment (str): see `matplotlib.text.Text`
            rotation: rotation angle in degrees CCW
        Returns:
            output (VisImage): image object with text drawn.
        """
        if not font_size:
            font_size = self._default_font_size

        # since the text background is dark, we don't want the text to be dark
        color = np.maximum(list(mplc.to_rgb(color)), 0.2)
        color[np.argmax(color)] = max(0.8, np.max(color))
        
        x, y = position
        if draw_chinese:
            font_path = "./simsun.ttc"
            prop = mfm.FontProperties(fname=font_path)
            self.output.ax.text(
                x,
                y,
                text,
                size=font_size * self.output.scale,
                family="sans-serif",
                bbox={"facecolor": "white", "alpha": 0.8, "pad": 0.7, "edgecolor": "none"},
                verticalalignment="top",
                horizontalalignment=horizontal_alignment,
                color=color,
                zorder=10,
                rotation=rotation,
                fontproperties=prop
            )
        else:
            self.output.ax.text(
                x,
                y,
                text,
                size=font_size * self.output.scale,
                family="sans-serif",
                bbox={"facecolor": "white", "alpha": 0.8, "pad": 0.7, "edgecolor": "none"},
                verticalalignment="top",
                horizontalalignment=horizontal_alignment,
                color=color,
                zorder=10,
                rotation=rotation,
            )
        return self.output

结合这几段,按图索骥,
overlay_instances函数里的

for ctrl_pnt, score, rec, bd in zip(ctrl_pnts, scores, recs, bd_pnts):
……
text = self._ctc_decode_recognition(rec)

总之就是模仿draw_instance_predictions添加了一个函数save_text_instance_predictions

    def save_text_instance_predictions(self, predictions):
        recs = predictions.recs
        text_output = ""
        for rec in recs:
            text_output = text_output + ' ' + self._ctc_decode_recognition(rec)
            
        return text_output   

就是不知道return self.output有什么特别含义,

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1305702.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

基于.NET Core + Quartz.NET+ Vue + IView开箱即用的定时任务UI

前言 定时任务调度应该是平时业务开发中比较常见的需求&#xff0c;比如说微信文章定时发布、定时更新某一个业务状态、定时删除一些冗余数据等等。今天给大家推荐一个基于.NET Core Quartz.NET Vue IView开箱即用的定时任务UI&#xff08;不依赖数据库,只需在界面做简单配…

java--HashMap、LinkedHashMap、TreeMap底层原理

1.HashMap集合的底层原理 ①HashMap跟HashSet的底层原理是一模一样的&#xff0c;都是基于哈希表实现的。 ②实际上&#xff1a;原来学的Set系列集合的底层原理就是基于Map实现的&#xff0c;只是Set集合中的元素只要键数据&#xff0c;不要值数据而已。 2.哈希表 ①JDK8之前…

如何使用nacos进行配置管理以及代码集成

首先需要在maven的pom文件中引入nacos-config依赖 <!--nacos配置管理依赖--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency> 在项目中添加boo…

好用便签有什么软件?好用的便签是什么

在工作中&#xff0c;我经常需要记录一些重要的信息&#xff0c;以便在需要时能够快速查找。但是&#xff0c;我曾经使用过的便签软件总是让我感到不满意&#xff0c;要么功能不够强大&#xff0c;要么使用起来不够方便。我一直在寻找一款好用的便签软件&#xff0c;能够让我事…

使用Kali Linux端口扫描

端口扫描 【实训目的】 掌握端口扫描的基本概念和端口扫描的原理&#xff0c;掌握各种类型端口扫描的方法及其区别。 【场景描述】 在虚拟机环境下配置4个虚拟系统“Win XP1” “Win XP2” “Kali Linux”和“Metasploitable2”&#xff0c;使得4个系统之间能够相互通信。实…

软件兼容性测试:保障多样化用户体验的重要功能

随着移动设备和操作系统的快速发展&#xff0c;软件兼容性测试变得越发重要。这项测试确保软件在不同平台、设备和环境下都能够正常运行&#xff0c;提供一致而稳定的用户体验。下面是软件兼容性测试中的一些关键功能&#xff1a; 1. 跨平台兼容性测试 在不同操作系统上运行的软…

【PHP编程实战】手把手教你如何下载文件,实例代码详解!

本文将向大家详细介绍PHP文件下载实例代码&#xff0c;具有一定的参考价值。对于一个网站而言&#xff0c;文件下载功能几乎是必备的。因此&#xff0c;了解如何使用PHP实现文件下载是非常必要的。在接下来的内容中&#xff0c;我们将一起探讨PHP文件下载的实现方法。 无控制类…

串口实验(中断)

需求&#xff1a; 通过中断的方法接受串口工具发送的字符串&#xff0c;并将其发送回串口工具。 硬件接线&#xff1a; 同上 串口配置&#xff1a; 前 4 步同上 5. 打开中断 编程实现&#xff1a; 1、这段代码主要实现了在接收到回车符时判断是否接收到换行符&#xff0c…

正态总体的区间估计

目录 一、区间估计 1.区间估计原理 2.区间估计定义 二、三大分布 1.正态分布 2.χ分布 3.t分布 三、 情况分类 1. μ 的区间估计 (1)已知σ (2)未知σ 2. σ的区间估计 四、公式推导 1.标准正态分布 2.t分布 3. χ分布 五、例题 一、区间估计 1.区间估计原理…

前沿重器[39] | 对话式推荐系统——概念和技术点

前沿重器 栏目主要给大家分享各种大厂、顶会的论文和分享&#xff0c;从中抽取关键精华的部分和大家分享&#xff0c;和大家一起把握前沿技术。具体介绍&#xff1a;仓颉专项&#xff1a;飞机大炮我都会&#xff0c;利器心法我还有。&#xff08;算起来&#xff0c;专项启动已经…

P1单片机定时器配置及定时器中断——C51(超详细)

目录 1. 简介 1.1 概念解读 1.2 定时器怎么定时 1.什么是晶振 2.什么是时钟周期 3.什么是机器周期 4.加1经过了多少时间 1.3 定时器编程 1.如何算出10ms定时器的初值(TL0 TH0) 2.关于TCON ,怎么知道爆表 3.怎么开始计时(TR0) 4.定时器使用是有很多种模式的&#xf…

sylar高性能服务器-配置(P10-p11)代码解析+调试分析

文章目录 p9&#xff1a;配置模块搭建一、ConfigvarBase二、ConfigVar三、Config四、小结 p10&#xff1a;YAML的使用一、安装yaml-cpp二、使用yaml-cpp三、代码解析 P11&#xff1a;YAML与日志的整合一、方法函数二、代码调试三、test_config结果四、小结 p9&#xff1a;配置模…

2023年全球软件开发大会(QCon广州站2023)-核心PPT资料下载

一、峰会简介 本次峰会包含&#xff1a;泛娱乐时代的边缘计算与通讯、稳定性即生命线、下一代软件架构、出海的思考、现代数据架构、AGI 与 AIGC 落地、大前端技术探索、编程语言实战、DevOps vs 平台工程、新型数据库、AIGC 浪潮下的企业出海、AIGC 浪潮下的效能智能化、数据…

联邦边缘学习中的知识蒸馏综述

联邦边缘学习中的知识蒸馏综述 移动互联网的快速发展伴随着智能终端海量用户数据的产生。如何在保护数据隐私的前提下,利用它们训练出性能优异的机器学习模型,一直是业界关注的难点。为此,联邦学习应运而生,它允许在终端本地训练并协同边缘服务器进行模型聚合来实现分布式机器…

C++字符串插入函数(insert)

1.在下标为n处插入y #include <iostream> #include <algorithm> #include <string> using namespace std;string x,y; int n;int main() {cin>>x>>y>>n;x.insert(n,y); //在下表为n处插入ycout<<x<<endl;return 0; }2…待续

十几个软件测试实战项目【外卖/医药/银行/电商/金融】

项目一&#xff1a;ShopNC商城 项目概况&#xff1a; ShopNC商城是一个电子商务B2C电商平台系统&#xff0c;功能强大&#xff0c;安全便捷。适合企业及个人快速构建个性化网上商城。 包含PCIOS客户端Adroid客户端微商城&#xff0c;系统PC后台是基于ThinkPHP MVC构架开发的跨…

【TiDB理论知识10】TiDB6.0新特性

新特性 Placement Rules in SQL 小表缓存 内存悲观锁 Top SQL TiDB Enterprise Manager 一 Placement Rules in SQL Placement Rules in SQL 之前会遇到的问题 比如 北京的业务需要访问 T2 和 T3表 &#xff0c;但是T3表的数据在纽约 纽约的业务需要问访T4 T5 T6表…

基于PaddleNLP的深度学习对文本自动添加标点符号(一)

前言 目前以深度学习对文本自动添加标点符号研究很少&#xff0c;已知的开源项目并不多&#xff0c;详细的介绍就更少了&#xff0c;但对文本自动添加标点符号又在古文识别语音识别上有重大应用。 基于此&#xff0c;本文开始讲解基于PaddleNLP的深度学习对文本自动添加标点符号…

js 有关递归简单介绍

递归&#xff1a;指调用自身的函数 重点&#xff1a;递归函数必须有可以终止递归调用的语句&#xff0c;否则会导致内存溢出 递归的性能不好&#xff0c;因为在递归终止前&#xff0c;JavaScript引擎会为每一次递归分配一块内存以存储栈帧&#xff0c;随着递归的深入&#xff…

【C语言】结构体实现位段

引言 对位段进行介绍&#xff0c;什么是位段&#xff0c;位段如何节省空间&#xff0c;位段的内存分布&#xff0c;位段存在的跨平台问题&#xff0c;及位段的应用。 ✨ 猪巴戒&#xff1a;个人主页✨ 所属专栏&#xff1a;《C语言进阶》 &#x1f388;跟着猪巴戒&#xff0c;…