切片具有多个y1:y2,x1:x2的numpy数组的多个帧

如何解决切片具有多个y1:y2,x1:x2的numpy数组的多个帧

我有一个多帧(numple_frames)的numpy数组,我想用不同的y1,y2,x1,x2对每个帧的高度和宽度进行切片,以在每个帧中绘制一个正方形“ 1”。 (slice_yyxx)是一个numpy数组,每帧包含一个y1,y2,x1,x2数组。

slice_yyxx = np.array(slice_yyxx).astype(int)
nbr_frame = slice_yyxx.shape[0]

multiple_frames = np.zeros(shape=(nbr_frame,target_shape[0],target_shape[1],target_shape[2]))
print(multiple_frames.shape)
# (5,384,640,1)

print(slice_yyxx)
# Value ok

print(slice_yyxx.shape)
# (5,4)
# Then 5 array of coord like [y1,y2,x1,x2] for slice each frames

print(slice_yyxx.dtype)
# np.int64

multiple_frames[:,slice_yyxx[:,0]:slice_yyxx[:,1],2]:slice_yyxx[:,3]] = 1
# ERROR: TypeError: only integer scalar arrays can be converted to a scalar index

解决方法

这里真正的问题是如何将任意切片转换为可以在多个维度上使用而不会循环的对象。我认为,诀窍是使用花式索引,arangerepeat的巧妙组合。

目标是创建一个与每个维度相对应的行和列索引数组。让我们以一个简单的可视化案例为例:3帧3x3矩阵集,其中我们希望将左上和右下2x2子数组分配给前两个帧,并将整个对象分配给最后一帧:

multi_array = np.zeros((3,3,3))
slice_rrcc = np.array([[0,2,2],[1,1,3],[0,3]])

让我们提出与每个索引匹配的索引以及大小和形状:

nframes = slice_rrcc.shape[0]                       # 3
nrows = np.diff(slice_rrcc[:,:2],axis=1).ravel()  # [2,3]
ncols = np.diff(slice_rrcc[:,2:],3]
sizes = nrows * ncols                               # [4,4,9]

我们需要以下精美索引才能进行分配:

frame_index = np.array([0,2])
row_index   = np.array([0,2])
col_index   = np.array([0,2])

如果我们可以获得数组frame_indexrow_indexcol_index,则可以如下设置每个段的数据:

multi_array[frame_index,row_index,col_index] = 1

frame_index索引很容易获得:

frame_index = np.repeat(np.arange(nframes),sizes)

row_index需要做更多的工作。您需要为每个单独的帧生成一组nrows索引,并重复ncols次。您可以通过生成连续范围并使用减法在每帧重新开始计数来实现此目的:

row_range = np.arange(nrows.sum())
row_offsets = np.zeros_like(row_range)
row_offsets[np.cumsum(nrows[:-1])] = nrows[:-1]
row_index = row_range - np.cumsum(row_offsets) + np.repeat(slice_rrcc[:,0],nrows)
segments = np.repeat(ncols,nrows)
row_index = np.repeat(row_index,segments)

col_index仍然不那么琐碎。您需要为具有正确偏移量的每一行生成一个序列,并针对每一行然后针对每一帧以大块重复该序列。该方法类似于row_index的方法,但有一个额外的花式索引可以使订单正确:

col_index_index = np.arange(sizes.sum())
col_index_resets = np.cumsum(segments[:-1])
col_index_offsets = np.zeros_like(col_index_index)
col_index_offsets[col_index_resets] = segments[:-1]
col_index_offsets[np.cumsum(sizes[:-1])] -= ncols[:-1]
col_index_index -= np.cumsum(col_index_offsets)

col_range = np.arange(ncols.sum())
col_offsets = np.zeros_like(col_range)
col_offsets[np.cumsum(ncols[:-1])] = ncols[:-1]
col_index = col_range - np.cumsum(col_offsets) + np.repeat(slice_rrcc[:,ncols)
col_index = col_index[col_index_index]

使用此公式,您甚至可以加倍为每个帧指定一个不同的值。如果要在我的示例中将values = [1,3]分配给框架,只需

multi_array[frame_index,col_index] = np.repeat(values,sizes)

我们将看看是否有更有效的方法来做到这一点。我问的一部分是here

基准

在{10,100,1000}中对nframes的循环和我的矢量化解决方案在multi_array中对{100,1000,10000}的宽度和高度的比较:

def set_slices_loop(arr,slice_rrcc):
    for a,s in zip(arr,slice_rrcc):
        a[s[0]:s[1],s[2]:s[3]] = 1

np.random.seed(0xABCDEF)
for nframes in [10,100,1000]:
    for dim in [10,32,100]:
        print(f'Size = {nframes}x{dim}x{dim}')
        arr = np.zeros((nframes,dim,dim),dtype=int)
        slice = np.zeros((nframes,4),dtype=int)
        slice[:,::2] = np.random.randint(0,dim - 1,size=(nframes,2))
        slice[:,1::2] = np.random.randint(slice[:,::2] + 1,2))
        %timeit set_slices_loop(arr,slice)
        arr[:] = 0
        %timeit set_slices(arr,slice)

结果非常支持循环,唯一例外的是非常多的帧和较小的帧大小。使用循环,大多数“正常”情况的速度要快一个数量级:

循环

        |          Dimension          |
        |   100   |   1000  |  10000  |
--------+---------+---------+---------+
F    10 | 33.8 µs | 35.8 µs | 43.4 µs |
r  -----+---------+---------+---------+
a   100 |  310 µs |  331 µs |  401 µs |
m  -----+---------+---------+---------+
e  1000 | 3.09 ms | 3.31 ms | 4.27 ms |
--------+---------+---------+---------+

矢量化

        |          Dimension          |
        |   100   |   1000  |  10000  |
--------+---------+---------+---------+
F    10 |  225 µs |  266 µs |  545 µs |
r  -----+---------+---------+---------+
a   100 |  312 µs |  627 µs | 4.11 ms |
m  -----+---------+---------+---------+
e  1000 | 1.07 ms | 4.63 ms | 48.5 ms |
--------+---------+---------+---------+

TL; DR

可以做,但不推荐:

def set_slices(arr,slice_rrcc,value):
    nframes = slice_rrcc.shape[0]
    nrows = np.diff(slice_rrcc[:,axis=1).ravel()
    ncols = np.diff(slice_rrcc[:,axis=1).ravel()
    sizes = nrows * ncols

    segments = np.repeat(ncols,nrows)

    frame_index = np.repeat(np.arange(nframes),sizes)

    row_range = np.arange(nrows.sum())
    row_offsets = np.zeros_like(row_range)
    row_offsets[np.cumsum(nrows[:-1])] = nrows[:-1]
    row_index = row_range - np.cumsum(row_offsets) + np.repeat(slice_rrcc[:,nrows)
    row_index = np.repeat(row_index,segments)

    col_index_index = np.arange(sizes.sum())
    col_index_resets = np.cumsum(segments[:-1])
    col_index_offsets = np.zeros_like(col_index_index)
    col_index_offsets[col_index_resets] = segments[:-1]
    col_index_offsets[np.cumsum(sizes[:-1])] -= ncols[:-1]
    col_index_index -= np.cumsum(col_index_offsets)

    col_range = np.arange(ncols.sum())
    col_offsets = np.zeros_like(col_range)
    col_offsets[np.cumsum(ncols[:-1])] = ncols[:-1]
    col_index = col_range - np.cumsum(col_offsets) + np.repeat(slice_rrcc[:,ncols)
    col_index = col_index[col_index_index]

    if values.size == 1:
        arr[frame_index,col_index] = value
    else:
        arr[frame_index,sizes)
,

这是使用benchit程序包(打包在一起的很少有基准测试工具;免责声明:我是它的作者)对基准测试解决方案进行基准测试的帖子。

我们正在使用set_slicesarr[frame_index,col_index] = 1从@Mad Physicist的解决方案中对set_slices_loop进行基准测试,而无需进行任何更改即可获得运行时(sec)

np.random.seed(0xABCDEF)
in_ = {}
for nframes in [10,100]:
        arr = np.zeros((nframes,2))
        in_[(nframes,dim)] = [arr,slice] 
    
import benchit
funcs = [set_slices,set_slices_loop]
t = benchit.timings(funcs,in_,input_name=['NumFrames','Dim'],multivar=True)
t.plot(sp_argID=1,logx=True,save='timings.png')

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-