本文介绍了切片具有多个y1:y2,x1:x2的numpy数组的多个帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多帧的numpy数组(multiple_frames),我想用不同的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]))打印(multiple_frames.shape)#(5,384,640,1)打印(slice_yyxx)#值还可以打印(slice_yyxx.shape)#(5,4)#然后像[y1,y2,x1,x2]的5个坐标数组对每个帧进行切片打印(slice_yyxx.dtype)#np.int64multiple_frames [:, slice_yyxx [:,0]:slice_yyxx [:,1],slice_yyxx [:,2]:slice_yyxx [:,3]] = 1#错误:TypeError:只能将整数标量数组转换为标量索引 
解决方案

这是使用

I have an numpy array of multiple frame (multiple_frames) and I want to slice height and width of each frame with different y1,y2,x1,x2 to draw a square of "1" in each frames.(slice_yyxx) is a numpy array and contain one array of y1,y2,x1,x2 for each frame.

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], slice_yyxx[:,2]:slice_yyxx[:,3]] = 1
# ERROR: TypeError: only integer scalar arrays can be converted to a scalar index
解决方案

This is a benchmarking post using benchit package (few benchmarking tools packaged together; disclaimer: I am its author) to benchmark proposed solutions.

We are benchmarking set_slices from @Mad Physicist's soln with arr[frame_index, row_index, col_index] = 1 and set_slices_loop without any changes to get runtime (sec).

np.random.seed(0xABCDEF)
in_ = {}
for nframes in [10, 100, 1000]:
    for dim in [10, 32, 100]:
        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, dim, size=(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')

这篇关于切片具有多个y1:y2,x1:x2的numpy数组的多个帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 03:03