본문 바로가기
  • Hello_
Python/Error

[Python_Error] ValueError: all the input arrays must have same number of dimensions (np.concatenate 오류)

by LDwDL 2022. 10. 4.
728x90
반응형

본 포스팅은 업무 중 발생했던 오류들을 예시를 통해 어떻게 해결을 하는지 작성했다.

 

ValueError: all the input arrays must have same number of 
dimensions, but the array at index 0 has 3 dimension(s) 
and the array at index 1 has 4 dimension(s)

해당 오류는 np.concatenate()을 사용할때 발생했던 오류이며, 특히 3차원 이상의 어레이들을 concat할때 많이 보이는 오류이다. 특히 2차원 이미지에 배치, 채널이 포함된 데이터의 경우 자주 발생했다.

 

[예시_1]

다음과 같이 np.concatenate는 사용할 때 특정 축을 기준으로 결합이 되기 때문에 axis 인자에 입력한 특정 축을 제외한 나머지 축의 사이즈가 통일되어야 한다. 이 경우는 축의 개수는 동일하지만 사이즈가 다른 경우이다.

 

gray_img = np.random.rand(30,3,256,256)
color_img = np.random.rand(30,3,512,512)

np.concatenate([gray_img,color_img],axis=1)
"""
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
----> 1 np.concatenate([gray_img,color_img],axis=1)

File <__array_function__ internals>:5, in concatenate(*args, **kwargs)

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 2, the array at index 0 has size 256 and the array at index 1 has size 512
"""

 

[해결_1]

간단히 사이즈를 맞춰주면 concat이 된다 (예시를 위해 np.resize로 간단하게 사이즈만 맞췄습니다).

 

_gray_img = np.resize(gray_img,[30,3,512,512])

concat_array = np.concatenate([_gray_img,color_img],axis=1)
print(concat_array.shape)
# (30, 6, 512, 512)

 

[예시_2]

이 예시도 마찬가지로 gray_img_1의 두번째 axis가 color_img와 결합이 될 수 없는 상황이다. 두 입력값의 사이즈가 다른 경우이며, 이 경우는 오히려 축이 하나 더 많은 경우이다.

 

import numpy as np

gray_img_1 = np.random.rand(30,512,512)
color_img = np.random.rand(30,3,512,512)

np.concatenate([gray_img_1,color_img],axis=1)
"""
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
----> 1 np.concatenate([gray_img_1,color_img],axis=1)

File <__array_function__ internals>:5, in concatenate(*args, **kwargs)

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 3 dimension(s) and the array at index 1 has 4 dimension(s)
"""

 

[해결_2]

np.expaned_dims을 활용하여 원하는 축을 새롭게 생성하여 구성할 수 있다. 따라서 _gray_img_1의 사이즈는 (30,512,512) -> (30,1,512,512)로 변경되고 color_img와 결합할 수 있는 조건이 되었다.

 

_gray_img_1 = np.expand_dims(gray_img_1,axis=1)

concat_array = np.concatenate([_gray_img_1,color_img],axis=1)

print(concat_array.shape)
# (30, 4, 512, 512)

 

[예시_3]

이 경우는 오히려 축이 하나 더 많은 경우이다. 

 

gray_img_2 = np.random.rand(30,1,1,512,512)

np.concatenate([gray_img_2,color_img],axis=1)
"""
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
----> 1 np.concatenate([gray_img_2,color_img],axis=1)

File <__array_function__ internals>:5, in concatenate(*args, **kwargs)

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 5 dimension(s) and the array at index 1 has 4 dimension(s)
"""

 

[해결_3]

이 경우는 축이 더 있는 경우로 np.squeeze을 활용하여 원하는 축을 지정하여 사이즈를 압축할 수 있다.

 

_gray_img_2 = np.squeeze(gray_img_2,axis=1)

concat_array = np.concatenate([_gray_img_2,color_img],axis=1)

print(concat_array.shape)
# (30, 4, 512, 512)

 

다음과 같이 np.concatenate()을 할 때 사이즈의 문제가 자주 발생할 수 있다. 그럴때는 입력의 사이즈를 수시로 확인해주며 np.squeeze 혹은 np.expand_dims을 활용하여 원하는 사이즈로 변환하면 해결이 가능하다.

 

 

 

728x90
반응형

댓글