Raspberry pi OS에 tflite (with depth estimation)
환경 설정
tflite설치가 가능한 가장 최신 버전이 python인데 os에는 3.9만 깔려 있어서 virtualenv에서 쓰기 위해 다른 버전을 설치해야 한다.
아주 귀찮게도 3.8버전은 distutils 이슈가 있고, 3.7버전은 apt-get으로 설치가 안된다. 따라서 아래 방법으로 직접 빌드해야한다. (repository추가해서 하고 싶었는데 linux repo를 함부로 넣지 말라는 글을 보고 포기했다. 에러가 나기도 했고..)
sudo apt-get install -y build-essential tk-dev libncurses5-dev \
libncursesw5-dev libreadline6-dev libdb5.3-dev libgdbm-dev libsqlite3-dev \
libssl-dev libbz2-dev libexpat1-dev liblzma-dev zlib1g-dev libffi-dev
wget https://www.python.org/ftp/python/3.7.13/Python-3.7.0\13.tgz
sudo tar zxf Python-3.7.13.tgz
cd Python-3.7.13
sudo ./configure
sudo make -j 4
sudo make altinstall
가상환경을 생성한다. 주로 프로젝트 폴더 안에 생성한다고 한다. (venv는 기본과 다른 python 버전 설정이 안돼서 virtualenv사용)
virtualenv .venv --python=python3.7
. .venv/bin/activate
pi 3 model b 기준으로 설치했다. 오오오래 걸림..
https://www.tensorflow.org/lite/guide/python?hl=ko
Python 빠른 시작 | TensorFlow Lite
Python 빠른 시작 Python에서 TensorFlow Lite를 사용하면 Raspberry Pi 및 Edge TPU를 탑재한 Coral 기기와 같이 Linux 기반의 임베디드 기기에서 유익한 결과를 거둘 수 있습니다. 이 페이지에서는 단 몇 분 안에
www.tensorflow.org
pip install https://dl.google.com/coral/python/tflite_runtime-2.1.0.post1-cp37-cp37m-linux_armv7l.whl
opencv-python 설치
pip install opencv-python
실행 시 ImportError: libcblas.so.3: cannot open shared object file: No such file or directory 와 같은 에러가 발생하면 아래 코드로 해결 가능하다.
sudo apt-get install libatlas-base-dev
Inference
depth estimation을 위해 midas tflite 모델을 이용했다. 아래 페이지에서 모델을 다운로드할 수 있고, 코드를 tflite만으로 추론 가능하게 수정했다.
https://tfhub.dev/intel/lite-model/midas/v2_1_small/1/lite/1
TensorFlow Hub
tfhub.dev
import cv2
import tflite_runtime.interpreter as tflite
import numpy as np
# input
img = cv2.imread('src_img.jpeg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255.0
img_resized = cv2.resize(img, [256,256], interpolation=cv2.INTER_CUBIC)
mean=[0.485, 0.456, 0.406]
std=[0.229, 0.224, 0.225]
img_input = (img_resized - mean) / std
reshape_img = img_input.reshape(1,256,256,3)
tensor = reshape_img.astype(np.float32)
# load model
interpreter = tflite.Interpreter(model_path="lite-model_midas_v2_1_small_1_lite_1.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
input_shape = input_details[0]['shape']
# inference
interpreter.set_tensor(input_details[0]['index'], tensor)
interpreter.invoke()
output = interpreter.get_tensor(output_details[0]['index'])
output = output.reshape(256, 256)
# output file
prediction = cv2.resize(output, (img.shape[1], img.shape[0]), interpolation=cv2.INTER_CUBIC)
print(" Write image to: output.png")
depth_min = prediction.min()
depth_max = prediction.max()
img_out = (255 * (prediction - depth_min) / (depth_max - depth_min)).astype("uint8")
cv2.imwrite("output.png", img_out)
실행 결과