Error

[에러노트/파이썬] AttributeError: 'Image' object has no attribute 'shape'

weweGH 2025. 4. 18. 09:00
반응형

error
error


AttributeError: 'Image' object has no attribute 'shape'

에러노트: 제가 직접 겪었던 에러와 해결 방법에 대해 소개합니다.

에러


파이썬에서 아래와 같이 laod_img를 통하여 이미지를 불러오고, 이미지의 크기를 조회하기 위해 shape를 사용했는데, 다음과 같은 에러가 발생했다.

AttributeError: 'Image' object has no attribute 'shape'

from keras_preprocessing.image import load_img

filename = 'output_20240301_V0000.png'
sample_img = load_img(filename)
sample_img.shape

error
error

반응형

해결


확인한 결과, shape이라는 속성이 없다는 경고문이었다. 에러를 해결하기 위한 방법으로는 cv2를 활용하거나 이미지의 타입을 변환하는 방법 이렇게 2가지 해결 방법이 있다.

i) cv2 활용

cv2 패키지를 활용하여 이미지를 불러오고, shape 속성을 통해 이미지의 크기를 확인하는 방법이다. cv2.imread를 활용하면 아래와 같이 이미지 크기를 확인할 수 있다.

import cv2

sample_img = cv2.imread('output_20240301_V0000.png')
print('sample_img size: ', sample_img.shape)

cv2 shape 결과
cv2 shape 결과


ii) 이미지 타입 변환

불러온 이미지를 numpy의 array로 타입을 변환하여 크기를 확인하는 방법이다. load_img로 이미지를 불러오고, array로 이미지 타입을 변환하면 아래와 같이 이미지의 크기를 확인할 수 있다.

import numpy as np

filename = 'output_20240301_V0000.png'
sample_img = load_img(filename)
sample_img = np.array(sample_img) 
print('sample_img size: ', sample_img.shape)

array shape
array shape


위의 해결방법과 같이 cv2 패키지나 이미지의 타입 변환을 하면, 이미지의 크기를 조회할 수 있다. 해결 완료.

반응형