프로그래밍/Python

[Python] 라즈베리파이 Teachable Machine 사용하기

Beginner:) 2021. 8. 5.
320x100

보통글 보면 opencv를 사용하여 teachable machine을 작동시킨다 .

 

사실 라즈베리파이에 opencv를 설치하는 것은 귀찮을 뿐더러 초보자가 설치하기엔 힘들다... 

 

os였나 ..? 어쨋건 버전도 맞춰야 한다.

 

웹캠을 찍는 방법은 cv2 에서 비디오객체를 가져온 후 read하는 방법도 있지만 

 

일반 터미널창에서 fswebcam을 이용해 캡쳐도 가능하다.

 

명령어는 아래와 같다 

fswebcam test_photo.jpg

 

이렇게 캡쳐본을 이미지로 저장하면 

 

Teachable Machine에서 제공되는 예제를 그대로 가져다 쓸 수 있다.

import tensorflow.keras
from PIL import Image, ImageOps
import numpy as np

# Disable scientific notation for clarity
np.set_printoptions(suppress=True)

# Load the model
model = tensorflow.keras.models.load_model('keras_model.h5')

# Create the array of the right shape to feed into the keras model
# The 'length' or number of images you can put into the array is
# determined by the first position in the shape tuple, in this case 1.
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)

# Replace this with the path to your image
image = Image.open('test_photo.jpg')

#resize the image to a 224x224 with the same strategy as in TM2:
#resizing the image to be at least 224x224 and then cropping from the center
size = (224, 224)
image = ImageOps.fit(image, size, Image.ANTIALIAS)

#turn the image into a numpy array
image_array = np.asarray(image)

# display the resized image
image.show()

# Normalize the image
normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1

# Load the image into the array
data[0] = normalized_image_array

# run the inference
prediction = model.predict(data)
print(prediction)

 

위의 예제에서 아래의 두 코드만 추가하면 된다.

import os


os.system('fswebcam test_photo.jpg')

 

os.system의 경우 사진을 찍고 저장시간을 주기 위해 sleep을 살짝 걸어두자 . 

 

 

사실 테스트도중 느낀거지만 

 

단색배경의 바나나등의 간단한 이미지가 아닌 

 

복잡한 이미지로 하면 계산을 제대로 못할때가 있다. 

 

의심이 가는건 있으나 ... 이유는 모른다. 

 

크기도 같고 육안으로 보면 같은 사진이지만 ... 뭔가 달라지는게 있나보다... 

 

하지만 fswebcam등으로 이미지를 저장하여 예제코드를 그대로 사용하면

 

Teachable Machine 홈페이지에서의 결과물과 같은 결과물을 보여준다.

 

반응형

 

 

참고로 Teachable Machine과 라즈베리파이를 연동하다 느낀점은 

1. 라즈베리파이 상에서 모델학습을 하면 멈춘다.

(모델 불러오기가 아닌 홈페이지에서 이미지를 올리고 학습하는 것을 말한다)

 

2. 일반 데스크톱등에서 모델학습을 하여 .h5 파일을 옮겨 라즈베리파이에서 실행하는 것은 가능하다.

다만 1~2초의 딜레이 시간이 있다 생각하면 안된다. 5초이상, 10초 이상 지연될수도 있다.

 

3. 

내가 테스트한 버전들은 

raspbian - buster 10 

python - 3.7.3

tensorflow - 2.3.0

opencv - 4.2.0

이다. 

 

좀 오래되서 기억안나지만 

위 환경설정들이 달라지면 실행이 안될수도 있다.

 

어렴풋이 기억나는건 tensorflow 2.3.0이 python 3.7...?인가 부터 되고 

openvcv 4.2.0은 buster, 3.2.0 버전인가.. ? 는 stretch 이고 ... 그랬던거 같다... 

확실치않다 .

반응형

댓글