문제상황:
머신러닝 모델 개발 중 데이터 전처리 과정에서 에러가 발생했습니다. 아래 코드는 이미지 데이터를 불러와 전처리하는 과정을 담고 있습니다.
import cv2
import numpy as np
def load_and_preprocess_image(image_path):
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.resize(image, (224, 224))
return image
image_path = "example.jpg"
preprocessed_image = load_and_preprocess_image(image_path)
print(preprocessed_image.shape)
에러로그 내용:
AttributeError: 'NoneType' object has no attribute 'shape'
해결방법:
에러가 수정된 코드+ 수정된 부분에 대한 주석
import cv2
import numpy as np
import os
def load_and_preprocess_image(image_path):
assert os.path.exists(image_path), f"Image path does not exist: {image_path}" # 추가된 코드
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.resize(image, (224, 224))
return image
image_path = "example.jpg"
preprocessed_image = load_and_preprocess_image(image_path)
print(preprocessed_image.shape)
원인분석:
에러 발생 원인은 cv2.imread() 함수가 이미지 파일을 불러올 수 없어 None 객체를 반환했기 때문입니다. 이 None 객체는 shape라는 속성이 없기 때문에 'NoneType' object has no attribute 'shape'라는 에러가 발생했습니다.
이미지 파일을 불러올 수 없는 원인은 다양합니다. 예를 들어, 파일 경로에 오탈자가 있거나 파일이 손상되었거나 지원하지 않는 형식일 수 있습니다. 이러한 원인을 찾기 위해 이미지 파일의 경로가 올바른지 확인하고, 이미지 파일이 존재하는지 확인하는 코드를 추가하였습니다.
참고링크:
728x90