[Model.py 02] 地图按比例放大的实现

news2024/10/13 0:30:52

要求:实现地图按比例放大

分析:考虑到地图放大过程中需要保留河流道路这些物体的相对位置关系,这里选择将河流和道路这些物体的坐标矩阵合并成terrain_matrix并对这个合并后的矩阵进行缩放处理。放大后的矩阵,根据矩阵中标记的物体位置,更新各自物体的放大矩阵。

思路:对于地图按比例放大,借用图片放大的思路,使用最近邻插值的方式,填充放大后产生的空隙。

实现:

补充大小调整参数self.zoomScale

_init_self.grid初始化之前,补充大小调整参数:self.zoomScale_init_函数修改部分的代码如下:

    def __init__(self, N=10, K=0, width=50, height=102,
                 civil_info_exchange=True, model_layer=-1, is_fired=False, is_flood=True, count=0):
        self.warning_UI = ""  # 警示信息
        self.resizeScale=3 # parameter using to control the scale of the map

_init_函数中补充地图放大、更新代码

        # 将安全通道坐标加载到地图中
        self.draw_environment(self.pos_exits)
        # 创建坐标空间
        self.graph = path_finding.create_graph(self)


        self.combine_matrices()
        # To rescale the terrain map size after combination.
        self.resize_matrices(self.resizeScale)
        self.separate_matrix() # update different object matrix from the resized matrix.

地图放大函数resize_matrices的定义

    def resize_matrices(self, degree):
        """
        Resize the terrain and constituent matrices while maintaining aspect ratio.

        :param degree: New rescaling degree.
        """
        scaling_factor = (degree, degree)

        # Resize the main terrain matrix
        self.terrain_matrix = zoom(self.terrain_matrix, scaling_factor, order=0)
        # order=1 for bilinear interpolation and 0 for nearest-neighbor interpolation.
        # This change will ensure that your matrices' integer values are preserved during the resizing process.

放大后更新其他物体的坐标矩阵函数separate_matrix

    def separate_matrix(self):
        """
        Separate the combined terrain matrix into individual feature matrices.

        Each matrix should represent one feature (e.g., river, road) with 1s where the feature exists
        and 0s where it doesn't.
        """
        # Identify all unique features in the terrain matrix, excluding 0 (empty)
        unique_features = np.unique(self.terrain_matrix)

        # Define a mapping from feature codes to the corresponding class attributes
        feature_mapping = {
            1: 'river_matrix',
            2: 'road_matrix',
            3: 'wall_matrix',
            4: 'indoor_matrix',
            5: 'exits_matrix',
            6: 'pillar_matrix',
            7: 'ditch_matrix'
        }

        # Initialize each matrix as an array of zeros
        for matrix_name in feature_mapping.values():
            setattr(self, matrix_name, np.zeros_like(self.terrain_matrix))

        # For each feature, populate the corresponding matrix
        for feature in unique_features:
            if feature == 0:
                continue  # Skip the 'empty' feature

            matrix_name = feature_mapping.get(feature)
            if not matrix_name:
                continue  # Skip if the feature is not recognized

            # Update the corresponding matrix directly
            feature_matrix = np.where(self.terrain_matrix == feature, 1, 0)
            setattr(self, matrix_name, feature_matrix)

        # At this point, each feature matrix (e.g., self.river_matrix) has been updated directly
        # No need to return anything since we're modifying the class attributes directly

补充:放大后地图的可视化脚本

请与单独的.py文件中运行。

# It's assumed you have executed the following installation command in your local environment:
# !pip install datashader

import datashader as ds
import datashader.transfer_functions as tf
import pandas as pd

# Load and prepare the data
from matplotlib import pyplot as plt

file_path = 'G:\\terrain_matrix3.csv'
data = pd.read_csv(file_path)

# Calculate the aspect ratio of the original data
num_rows, num_cols = data.shape  # Assuming 'data' is your DataFrame
aspect_ratio = num_cols / num_rows

# Ensure column headers are consistent and represent coordinates or indexing
# If headers are numeric: good; if not, you might want to set headers as a range of numbers representing columns
data.columns = range(len(data.columns))

# Resetting the index to turn it into a column for melting
data = data.reset_index()

# Melting the data (now 'X' should be consistently numeric)
melted_data = data.melt(id_vars=['index'], var_name='X', value_name='Value')
melted_data['Y'] = melted_data['index']
melted_data.drop(columns=['index'], inplace=True)

# Convert 'X' and 'Y' to numeric values, coercing errors (i.e., non-numeric values are set as NaN)
melted_data['X'] = pd.to_numeric(melted_data['X'], errors='coerce')
melted_data['Y'] = pd.to_numeric(melted_data['Y'], errors='coerce')

# Handle or remove any rows with NaN if necessary (created by 'coerce')
melted_data.dropna(subset=['X', 'Y'], inplace=True)

# Define the dimensions for the canvas
plot_width = 800
plot_height = int(plot_width / aspect_ratio)  # Maintain the aspect ratio of the original data

# Set up the canvas with the correct aspect ratio
canvas = ds.Canvas(plot_width=plot_width, plot_height=plot_height)

# Aggregating data into a grid
agg = canvas.points(melted_data, 'X', 'Y', ds.mean('Value'))

# Creating an image by coloring the aggregated data
img = tf.shade(agg, cmap=['lightblue', 'darkblue'], how='linear')

# Convert the Datashader image to a format that can be displayed by matplotlib
img_to_plot = tf.shade(agg, cmap=['lightblue', 'darkblue'], how='linear')
img_plt = tf.set_background(img_to_plot, 'white')

# Display the image using matplotlib
plt.imshow(img_plt.to_pil())
plt.axis('off')  # Optional: this removes the axes for a cleaner look
plt.title('Presentation of the rescaling map data(3X).')

plt.show()

以下是可视化脚本的输出案例。其中,2X和3X分别表示设置的地图放大倍数。

在这里插入图片描述
在这里插入图片描述

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

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

相关文章

如何处理前端响应式图片?

聚沙成塔每天进步一点点 ⭐ 专栏简介 前端入门之旅:探索Web开发的奇妙世界 欢迎来到前端入门之旅!感兴趣的可以订阅本专栏哦!这个专栏是为那些对Web开发感兴趣、刚刚踏入前端领域的朋友们量身打造的。无论你是完全的新手还是有一些基础的开发…

Jenkins+vue发布项目

在Jenkins 中先创建一个任务名称 然后进行下一步,放一个项目 填写一些参数 参数1: 参数2: 参数3:参数4: 点击保存就行了 配置脚本 // git def git_url http://gitlab.xxxx.git def git_auth_id GITEE_RIVER…

面试题:线程池中线程抛了异常,该如何处理?

文章目录 1. 模拟线程池抛异常2. 如何获取和处理异常方案一:使用 try -catch方案二:使用Thread.setDefaultUncaughtExceptionHandler方法捕获异常方案三:重写afterExecute进行异常处理 1. 模拟线程池抛异常 在实际开发中,我们常常…

2023年【四川省安全员A证】模拟试题及四川省安全员A证作业模拟考试

题库来源:安全生产模拟考试一点通公众号小程序 2023年四川省安全员A证模拟试题为正在备考四川省安全员A证操作证的学员准备的理论考试专题,每个月更新的四川省安全员A证作业模拟考试祝您顺利通过四川省安全员A证考试。 1、【多选题】36V照明适用的场所条…

嵌入式实时操作系统的设计与开发 (中断管理)

中断发生及响应 硬件抽象HAL层响应 中断请求IRQ被中断控制器汇集成中断向量(Interrupt Vector),每个中断向量对应一个中断服务程序ISR,中断向量存放了ISRs的入口地址或ISRs的第一条指令。 系统中通常包含多个中断向量&#xff0…

PyTorch深度学习实战(22)——从零开始实现YOLO目标检测

PyTorch深度学习实战(22)——从零开始实现YOLO目标检测 0. 前言1. YOLO 架构1.1 R-CNN 目标检测模型的局限性1.2 YOLO 目标检测模型原理 2. 实现 YOLO 目标检测2.1 编译 DarkNet2.2 设置数据集格式2.3 配置网络架构2.4 模型训练和测试 小结系列链接 0. 前…

C# 关于托管调试助手 “FatalExecutionEngineError“:“运行时遇到了错误。解决方案

托管调试助手 “FatalExecutionEngineError”:“运行时遇到了错误。此错误的地址为 0x740161f8,在线程 0x1174 上。错误代码为 0xc0000005。此错误可能是 CLR 中的 bug,或者是用户代码的不安全部分或不可验证部分中的 bug。此 bug 的常见来源包括用户对 …

手术麻醉临床信息管理系统源码,客户端可以接入监护仪、麻醉机、呼吸机

一、手术麻醉临床信息管理系统介绍 1、手术麻醉临床信息管理系统是数字化手段应用于手术过程中的重要组成部分,用数字形式获取并存储手术相关信息,既便捷又高效。既然是管理系统,那就是一整套流程,管理患者手术、麻醉的申请、审批…

【C语言】输入一个正整数,判断其是否为素数

1、素数又叫质数。素数&#xff0c;指的是“大于1的整数中&#xff0c;只能被1和这个数本身整除的数”。 2、素数也可以被等价表述成&#xff1a;“在正整数范围内&#xff0c;大于1并且只有1和自身两个约数的数”。 #include<stdio.h>int main() {int i,m;printf("…

如何实现前端社交媒体分享功能?

聚沙成塔每天进步一点点 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 欢迎来到前端入门之旅&#xff01;感兴趣的可以订阅本专栏哦&#xff01;这个专栏是为那些对Web开发感兴趣、刚刚踏入前端领域的朋友们量身打造的。无论你是完全的新手还是有一些基础的开发…

如何创建前端自定义主题和样式?

聚沙成塔每天进步一点点 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 欢迎来到前端入门之旅&#xff01;感兴趣的可以订阅本专栏哦&#xff01;这个专栏是为那些对Web开发感兴趣、刚刚踏入前端领域的朋友们量身打造的。无论你是完全的新手还是有一些基础的开发…

【API篇】三、Flink转换算子API

文章目录 0、demo数据1、基本转换算子&#xff1a;映射map2、基本转换算子&#xff1a;过滤filter3、基本转换算子&#xff1a;扁平映射flatMap4、聚合算子&#xff1a;按键分区keyBy5、聚合算子&#xff1a;简单聚合sum/min/max/minBy/maxBy6、聚合算子&#xff1a;归约聚合re…

深入理解Java IO流: 包括字节流和字符流的用法、文件读写实践

文章目录 &#x1f4d5;我是廖志伟&#xff0c;一名Java开发工程师、Java领域优质创作者、CSDN博客专家、51CTO专家博主、阿里云专家博主、清华大学出版社签约作者、产品软文创造者、技术文章评审老师、问卷调查设计师、个人社区创始人、开源项目贡献者。&#x1f30e;跑过十五…

CCF ChinaSoft 2023 论坛巡礼|形式验证@EDA论坛

2023年CCF中国软件大会&#xff08;CCF ChinaSoft 2023&#xff09;由CCF主办&#xff0c;CCF系统软件专委会、形式化方法专委会、软件工程专委会以及复旦大学联合承办&#xff0c;将于2023年12月1-3日在上海国际会议中心举行。 本次大会主题是“智能化软件创新推动数字经济与社…

【Proteus仿真】【STM32单片机】路灯控制系统

文章目录 一、功能简介二、软件设计三、实验现象联系作者 一、功能简介 本项目使用Proteus8仿真STM32单片机控制器&#xff0c;使用LCD1602显示模块、人体红外传感器、光线检测模块、路灯继电器控制等。 主要功能&#xff1a; 系统运行后&#xff0c;LCD1602显示时间、工作模…

SpringMVC - 详解RESTful

文章目录 1. 简介2. RESTful的实现3.HiddenHttpMethodFilter4. RESTful案例1、准备工作2、功能清单3、具体功能&#xff1a;访问首页a>配置view-controllerb>创建页面 4、具体功能&#xff1a;查询所有员工数据a>控制器方法b>创建employee_list.html 5、具体功能&a…

游戏设计模式专栏(十一):在Cocos游戏开发中运用享元模式

点击上方亿元程序员关注和★星标 引言 大家好&#xff0c;我是亿元程序员&#xff0c;一位有着8年游戏行业经验的主程。 本系列是《和8年游戏主程一起学习设计模式》&#xff0c;让糟糕的代码在潜移默化中升华&#xff0c;欢迎大家关注分享收藏订阅。 享元模式&#xff08…

Linux常用命令——colrm命令

在线Linux命令查询工具 colrm 删除文件中的指定列 补充说明 colrm命令用于删除文件中的指定列。colrm命令从标准输入设备读取书记&#xff0c;转而输出到标准输出设备。如果不加任何参数&#xff0c;则colrm命令不会过滤任何一行。 语法 colrm(参数)参数 起始列号&#…

使用Python找到相似图片的方法

使用Python找到相似图片的方法 作者&#xff1a;安静到无声 个人主页 摘要&#xff1a;在日常生活中&#xff0c;我们可能会遇到需要查找相似图片的情况。例如&#xff0c;我们可能有一张图片&#xff0c;并希望找到文件夹中与该图片相似的其他图片。本文将介绍如何使用Pytho…

二分法求多项式单根

输出格式&#xff1a; 在一行中输出该多项式在该区间内的根&#xff0c;精确到小数点后2位。 输入样例&#xff1a; 3 -1 -3 1 -0.5 0.5 输出样例&#xff1a; 0.33 idea 精确到小数点后两位 >阈值为0.001 solution1 #include <stdio.h> #include <math.h…