티스토리 뷰

이 코드는 MNIST 숫자 이미지를 로드하고, 사전 훈련된 딥러닝 모델을 사용하여 각 이미지의 숫자를 예측하는 과정을 포함하고 있습니다. 아래는 코드의 각 부분에 대한 자세한 설명입니다.

1. 라이브러리 임포트
import tensorflow as tf
import os
import cv2
import matplotlib.pyplot as plt
import numpy as np


tensorflow: 딥러닝 모델을 구축하고 예측하기 위해 사용됩니다.
os: 파일 및 디렉토리 경로 관련 작업을 위해 사용됩니다.
cv2: OpenCV 라이브러리로, 이미지 로드 및 처리에 사용됩니다.
matplotlib.pyplot: 이미지를 시각화하기 위해 사용됩니다.
numpy: 배열 및 수치 연산을 위해 사용됩니다.


2. 모델 로드
model = tf.keras.models.load_model('./model_mnist_b/11-0.0654.keras')
model.summary()
모델 로드: 지정된 경로에서 사전 훈련된 Keras 모델을 로드합니다.
모델 요약: model.summary()를 통해 모델의 구조와 레이어 정보를 출력합니다.


3. 테스트 이미지 경로 설정 및 로드
test_num1 = cv2.imread('./model/minist_test/3.jpg')
test_num2 = cv2.imread('./model/minist_test/6.jpg')
test_num3 = cv2.imread('./model/minist_test/5.jpg')
이미지 로드: OpenCV를 사용하여 지정된 경로에서 테스트 이미지를 읽어옵니다.


4. 이미지 로드 확인
if test_num1 is None or test_num2 is None or test_num3 is None:
    print("이미지를 로드하는 데 문제가 발생했습니다. 경로를 확인하세요.")
    sys.exit()
로드 확인: 각 이미지가 제대로 로드되었는지 확인합니다. 만약 로드되지 않았다면 에러 메시지를 출력하고 프로그램을 종료합니다.


5. 이미지 전처리
test_num1 = cv2.cvtColor(test_num1, cv2.COLOR_BGR2GRAY)
test_num2 = cv2.cvtColor(test_num2, cv2.COLOR_BGR2GRAY)
test_num3 = cv2.cvtColor(test_num3, cv2.COLOR_BGR2GRAY)
그레이스케일 변환: 이미지를 RGB에서 그레이스케일로 변환합니다. MNIST 데이터셋은 그레이스케일 이미지로 되어 있기 때문에 모델 입력에 맞추기 위해 변환합니다.


6. 색상 반전
test_num1 = 255 - test_num1
test_num2 = 255 - test_num2
test_num3 = 255 - test_num3
색상 반전: 그레이스케일 이미지를 반전하여 흰색 배경에 검은색 숫자가 되도록 만듭니다. 이는 MNIST 데이터셋의 특성과 일치합니다.

 

7. 이미지 시각화
plt.imshow(test_num1, cmap='Greys')
plt.title('Test Image 1')
plt.axis('off')
plt.show()
이미지 시각화: 각 이미지를 시각화합니다. cmap='Greys'를 사용하여 그레이스케일로 표시합니다.


8. 이미지 전처리 (reshape)
test_num1 = test_num1.reshape(1, 784).astype('float32') / 255
test_num2 = test_num2.reshape(1, 784).astype('float32') / 255
test_num3 = test_num3.reshape(1, 784).astype('float32') / 255


차원 변경 및 정규화: 이미지를 784차원 벡터로 변환하고, 픽셀 값을 0에서 1 사이로 정규화합니다. 이는 모델의 입력 형식에 맞추기 위한 과정입니다.

 

9. 예측
test_predict = [model.predict(test_num1), model.predict(test_num2), model.predict(test_num3)]
예측 수행: 각 이미지에 대해 모델을 사용하여 예측을 수행합니다. model.predict() 메서드를 사용하여 각 이미지의 예측 확률을 얻습니다.


10. 결과 출력
print('The Answer for Image 1 is', test_predict[0].argmax())
print('The Answer for Image 2 is', test_predict[1].argmax())
print('The Answer for Image 3 is', test_predict[2].argmax())


예측 결과 출력: 각 이미지에 대한 예측 결과(가장 높은 확률을 가진 클래스)를 출력합니다. argmax() 메서드를 사용하여 가장 높은 확률을 가진 인덱스를 반환합니다.


이 코드는 MNIST 데이터셋의 숫자 이미지를 로드하고, 사전 훈련된 모델을 사용하여 각 이미지의 숫자를 예측하는 전체적인 과정을 포함하고 있습니다. 이 코드를 통해 사용자 정의 숫자 이미지를 모델에 입력하고, 그에 대한 예측 결과를 확인할 수 있다.

 

전체코드는 아래 와 같습니다.

import tensorflow as tf
import os
import cv2
import matplotlib.pyplot as plt
import numpy as np

# 모델 로드
model = tf.keras.models.load_model('./model_mnist_b/11-0.0654.keras')
model.summary()

# 테스트 이미지 경로
test_num1 = cv2.imread('./model/minist_test/3.jpg')
test_num2 = cv2.imread('./model/minist_test/6.jpg')
test_num3 = cv2.imread('./model/minist_test/5.jpg')

# 이미지가 제대로 로드되었는지 확인
if test_num1 is None or test_num2 is None or test_num3 is None:
    print("이미지를 로드하는 데 문제가 발생했습니다. 경로를 확인하세요.")
    sys.exit()

# RGB 파일을 그레이스케일로 변환
test_num1 = cv2.cvtColor(test_num1, cv2.COLOR_BGR2GRAY)
test_num2 = cv2.cvtColor(test_num2, cv2.COLOR_BGR2GRAY)
test_num3 = cv2.cvtColor(test_num3, cv2.COLOR_BGR2GRAY)

# 색상 반전
test_num1 = 255 - test_num1
test_num2 = 255 - test_num2
test_num3 = 255 - test_num3

# 이미지 시각화
plt.imshow(test_num1, cmap='Greys')
plt.title('Test Image 1')
plt.axis('off')
plt.show()

plt.imshow(test_num2, cmap='Greys')
plt.title('Test Image 2')
plt.axis('off')
plt.show()

plt.imshow(test_num3, cmap='Greys')
plt.title('Test Image 3')
plt.axis('off')
plt.show()

# 이미지 전처리
test_num1 = test_num1.reshape(1, 784).astype('float32') / 255
test_num2 = test_num2.reshape(1, 784).astype('float32') / 255
test_num3 = test_num3.reshape(1, 784).astype('float32') / 255

# 예측
test_predict = [model.predict(test_num1), model.predict(test_num2), model.predict(test_num3)]

# 결과 출력
print('The Answer for Image 1 is', test_predict[0].argmax())
print('The Answer for Image 2 is', test_predict[1].argmax())
print('The Answer for Image 3 is', test_predict[2].argmax())
댓글