programing

Numpy 배열에 새로운 차원을 추가하려면 어떻게 해야 합니까?

madecode 2023. 7. 10. 23:51
반응형

Numpy 배열에 새로운 차원을 추가하려면 어떻게 해야 합니까?

저는 이미지의 희미한 배열로 시작할 것입니다.

In[1]:img = cv2.imread('test.jpg')

모양은 640x480 RGB 이미지에서 예상할 수 있는 모양입니다.

In[2]:img.shape
Out[2]: (480, 640, 3)

하지만, 제가 가지고 있는 이 이미지는 100프레임 길이의 비디오의 프레임입니다.이상적으로는, 이 비디오의 모든 데이터를 포함하는 단일 어레이를 원합니다.img.shape아온다를 합니다.(480, 640, 3, 100).

다음 프레임, 즉 다음 이미지 데이터 세트, 다른 480 x 640 x 3 배열을 초기 배열에 추가하는 가장 좋은 방법은 무엇입니까?

다음과 같이 치수를 numpy 배열에 추가할 수 있습니다.

image = image[..., np.newaxis]

대신

image = image[..., np.newaxis]

@dbliss의 대답에서, 당신은 또한 다음과 같이 사용할 수 있습니다.

image = np.expand_dims(image, <your desired dimension>)

예: (위의 링크에서 가져온)

x = np.array([1, 2])

print(x.shape)  # prints (2,)

그리고나서

y = np.expand_dims(x, axis=0)

수확량

array([[1, 2]])

그리고.

y.shape

기브즈

(1, 2)

올바른 크기의 배열을 미리 만들어 채우면 됩니다.

frames = np.empty((480, 640, 3, 100))

for k in xrange(nframes):
    frames[:,:,:,k] = cv2.imread('frame_{}.jpg'.format(k))

프레임이 특정 방식으로 이름이 지정된 개별 jpg 파일인 경우(예: frame_0.jpg, frame_1.jpg 등).

참고로, 당신은 사용하는 것을 고려할 수 있습니다.(nframes, 480,640,3)대신 모양 배열을 사용합니다.

피톤체의

X = X[:, :, None]

와 동등한.

X = X[:, :, numpy.newaxis]그리고.X = numpy.expand_dims(X, axis=-1)

이 이미지하고 있기 에, 저는 합니다.listnp.stack([X1, X2, X3])당신이 루프에서 수집했을 수도 있습니다.

치수 순서가 마음에 들지 않으면 다시 정렬할 수 있습니다.np.transpose()

사용할 수 있습니다.np.concatenate()을 사용합니다.axis연결해야 하는 치수를 지정하는 매개 변수입니다. 차원이 연중인배이차없다으사수있다용습니음할을을 사용할 수 .np.newaxis를 나타냅니다.

import numpy as np
movie = np.concatenate((img1[:,np.newaxis], img2[:,np.newaxis]), axis=3)

여러 파일에서 읽는 경우:

import glob
movie = np.concatenate([cv2.imread(p)[:,np.newaxis] for p in glob.glob('*.jpg')], axis=3)
a = np.expand_dims(a, axis=-1) 

또는

a = a[:, np.newaxis] 

또는

a = a.reshape(a.shape + (1,))

형상 변경 방법을 사용한 접근법 1과 동일한 결과를 생성하는 np.new 축 방법을 사용한 접근법 2를 고려합니다.

#Lets suppose, we have:
x = [1,2,3,4,5,6,7,8,9]
print('I. x',x)

xNpArr = np.array(x)
print('II. xNpArr',xNpArr)
print('III. xNpArr', xNpArr.shape)

xNpArr_3x3 = xNpArr.reshape((3,3))
print('IV. xNpArr_3x3.shape', xNpArr_3x3.shape)
print('V. xNpArr_3x3', xNpArr_3x3)

#Approach 1 with reshape method
xNpArrRs_1x3x3x1 = xNpArr_3x3.reshape((1,3,3,1))
print('VI. xNpArrRs_1x3x3x1.shape', xNpArrRs_1x3x3x1.shape)
print('VII. xNpArrRs_1x3x3x1', xNpArrRs_1x3x3x1)

#Approach 2 with np.newaxis method
xNpArrNa_1x3x3x1 = xNpArr_3x3[np.newaxis, ..., np.newaxis]
print('VIII. xNpArrNa_1x3x3x1.shape', xNpArrNa_1x3x3x1.shape)
print('IX. xNpArrNa_1x3x3x1', xNpArrNa_1x3x3x1)

결과는 다음과 같습니다.

I. x [1, 2, 3, 4, 5, 6, 7, 8, 9]

II. xNpArr [1 2 3 4 5 6 7 8 9]

III. xNpArr (9,)

IV. xNpArr_3x3.shape (3, 3)

V. xNpArr_3x3 [[1 2 3]
 [4 5 6]
 [7 8 9]]

VI. xNpArrRs_1x3x3x1.shape (1, 3, 3, 1)

VII. xNpArrRs_1x3x3x1 [[[[1]
   [2]
   [3]]

  [[4]
   [5]
   [6]]

  [[7]
   [8]
   [9]]]]

VIII. xNpArrNa_1x3x3x1.shape (1, 3, 3, 1)

IX. xNpArrNa_1x3x3x1 [[[[1]
   [2]
   [3]]

  [[4]
   [5]
   [6]]

  [[7]
   [8]
   [9]]]]

numpy에는 나중에 더 많은 데이터를 추가할 수 있는 구조가 없습니다.

대신 numpy는 모든 데이터를 연속된 숫자 청크(기본적으로 C 배열)에 저장하고 크기를 조정하려면 이를 저장할 새 메모리 청크를 할당해야 합니다.Numpy의 속도는 동일한 메모리 청크에 있는 Numpy 어레이의 모든 데이터를 유지할 수 있는 데서 비롯됩니다. 예를 들어 수학적 연산을 병렬화하여 속도를 높일 수 있고 캐시 누락 횟수를 줄일 수 있습니다.

따라서 두 가지 솔루션이 제공됩니다.

  1. Numpy 배열에 대한 메모리를 미리 할당하고 Josh Adel의 답변처럼 값을 입력합니다.
  2. 실제로 모든 데이터를 통합해야 할 때까지 일반 파이썬 목록에 데이터를 보관합니다(아래 참조).

images = []
for i in range(100):
    new_image = # pull image from somewhere
    images.append(new_image)
images = np.stack(images, axis=3)

개별 이미지 배열의 치수를 먼저 확장할 필요도 없고 미리 예상되는 이미지 수를 알 필요도 없습니다.

축 파라미터와 함께 스택을 사용할 수 있습니다.

img.shape  # h,w,3
imgs = np.stack([img1,img2,img3,img4], axis=-1)   # -1 = new axis is last
imgs.shape #  h,w,3,nimages

예: 그레이스케일을 색상으로 변환하는 방법:

>>> d = np.zeros((5,4), dtype=int)  # 5x4
>>> d[2,3] = 1

>>> d3.shape
Out[30]: (5, 4, 3)

>>> d3 = np.stack([d,d,d], axis=-2)  # 5x4x3   -1=as last axis
>>> d3[2,3]
Out[32]: array([1, 1, 1])

저는 이 접근 방식을 따랐습니다.

import numpy as np
import cv2

ls = []

for image in image_paths:
    ls.append(cv2.imread('test.jpg'))

img_np = np.array(ls) # shape (100, 480, 640, 3)
img_np = np.rollaxis(img_np, 0, 4) # shape (480, 640, 3, 100).

이것은 저에게 효과가 있었습니다.

image = image[..., None]

원하는 위치에 축을 추가하는 데 도움이 됩니다.

    import numpy as np
    signal = np.array([[0.3394572666491664, 0.3089068053925853, 0.3516359279582483], [0.33932706934615525, 0.3094755563319447, 0.3511973743219001], [0.3394407172182317, 0.30889042266755573, 0.35166886011421256], [0.3394407172182317, 0.30889042266755573, 0.35166886011421256]])
    
    print(signal.shape)
#(4,3)
    print(signal[...,np.newaxis].shape)  or  signal[...:none]
#(4, 3, 1) 
    print(signal[:, np.newaxis, :].shape)  or signal[:,none, :]

#(4, 1, 3)

ndarray에 새로운 차원을 추가하는 세 가지 방법이 있습니다.

번째: "np.newaxis" 사용(@dbliss 답변과 같은 것)

  • np.newaxis는 쉽게 하기 위해 None에 대한 별칭이 부여됩니다.
    이해하다.np.new축을 None으로 바꾸면 동일하게 작동합니다.
    way. 하지만 좀 더 명확하게 하기 위해 np.new축을 사용하는 것이 좋습니다.
import numpy as np

my_arr = np.array([2, 3])
new_arr = my_arr[..., np.newaxis]

print("old shape", my_arr.shape)
print("new shape", new_arr.shape)

>>> old shape (2,)
>>> new shape (2, 1)

번째: "np.dims_dims" 사용

  • 첫 번째 인수에 원래 nd 배열을 지정하고 두 번째 인수 축에 차원을 추가할 위치를 지정합니다.
my_arr = np.array([2, 3])
new_arr = np.expand_dims(my_arr, -1)

print("old shape", my_arr.shape)
print("new shape", new_arr.shape)

>>> old shape (2,)
>>> new shape (2, 1)

번째: "모양 바꾸기" 사용

my_arr = np.array([2, 3])
new_arr = my_arr.reshape(*my_arr.shape, 1)

print("old shape", my_arr.shape)
print("new shape", new_arr.shape)

>>> old shape (2,)
>>> new shape (2, 1)

언급URL : https://stackoverflow.com/questions/17394882/how-can-i-add-new-dimensions-to-a-numpy-array

반응형