[딥러닝] TensorFlow.js로 가져온 모델 사용해보기

지현·2022년 6월 10일
0

지난 포스트 '[딥러닝] Keras 모델을 TensorFlow.js로 가져오기'에서 이어진다.
이번에는 웹캠을 연결해서 가져온 모델을 사용해보려고 한다.
성공을 기원하며 시작~!


WebCam 연결하기

  • webcam-easy : 웹캠 스트림에 접근하고 사진을 찍기 위한 자바 스크립트 라이브러리
  • Functions
    • start(startStream) : start streaming webcam
      • get permission from user
      • get all video input devices info
      • select camera based on facingMode
      • start stream
        startStream is optional parameter, default value is true
    • stop() : stop streaming webcam
    • stream() : start streaming webcam to video element
    • snap() : take photo from webcam
    • flip() : change Facing mode and selected camera
  • Properties
    • facingMode : 'user' or 'enviroment'
    • webcamList : all available camera device
    • webcamCount : number of available camera device

코드 (미완성)

출처

  • import문과 같은 부분이다. tensorflow.js와 webcam을 import 하는 부분이다.
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/webcam-easy/dist/webcam-easy.min.js"></script>
  • script 부분
<script type="module">
	const webcamElement = document.getElementById('webcam');
	const canvasElement = document.getElementById('canvas');
	const snapBtn = document.getElementById("btn-capture");
	const predictBtn = document.getElementById("btn-predict");
	const webcam = new Webcam(webcamElement, 'user', canvasElement);
	webcam.start()
	.then(result =>{
		console.log("webcam started");
	})
	.catch(err => {
		console.log(err);
	});
	snapBtn.onclick = async () => {
      // const base_model = VGG16(weights='imagenet', include_top=False, input_shape=(224,224,3))
      const picture = webcam.snap()
      const model = await tf.loadLayersModel('./tfjsmodel/model.json')

      let myFaceImage = tf.browser.fromPixels(webcamElement)

      myFaceImage = tf.image.resizeBilinear(myFaceImage, [244,244])
      myFaceImage = tf.expandDims(myFaceImage, 0)

      x_features = base_model.predict(myFaceImage)

      const prediction = model.predict(x_features)//.strides.findIndex(ele => ele==1)
      const predictionArray = prediction.dataSync()
      console.log("prediction", prediction)
      const maxValue = predictionArray.indexOf(Math.max(...predictionArray))
	}
</script>

Trouble Shooting

첫번째 오류


두번째 오류 (네번째 오류에서 해결)

세번째 오류

  • 두번째 오류에서 연결되는 VGG16의 import 오류

    • 첫번째 생각 : TensorFlow.js에서 공식으로 제공해주는 모델처럼 script에 src형태로 import 할 수 있을까? 생각했다. 하지만 ❌실패❌

    • 두번째 생각 : 케라스의 모델 파이썬 코드를 올려주는 깃허브를 발견했다. (블로그) 여기에 올라온 .py 코드를 이용할 수 있지 않을까? ❌실패❌

    • 세번째 생각 : 구글링을 하다가 찾은 깃허브 VGG16-with-TensorflowJs를 참고하여 keras에서 import해서 사용할 수 있는 VGG16을 TFJS.converters... 하여 model.json파일로 변환하였다. ⭕성공!⭕
      • 다음은 변환에 사용한 전체 코드이다.
import keras
import tensorflowjs as TFJS

vgg16 = keras.applications.vgg16.VGG16()
TFJS.converters.save_keras_model(vgg16, "test_tensorflowjs/tfjsmodel/vgg16")

네번째 오류 (두번째 오류')

  • VGG16을 import하고 기존 test 코드와 input값을 동일하게 설정하였지만 다음 오류는 고쳐지지 않았다.
    • 같은 팀원인 미서가 Input의 형태도 원인이 될 수 있겠지만 TensorFlow.js의 문제일 수도 있으니 Python으로 해당 코드를 실행해보자는 좋은 아이디어를 줘서 Python으로 실행해보았다.
    • 다음은 Python에서 진행한 내용이다.
      [딥러닝] CNN-LSTM 모델 이미지로 테스트하기

다섯번째 오류

  • Python 환경에서는 성공했지만 TensorFlow.js로 돌아오니 여전히 같은 오류가 났다.

    Error: Provided weight data has no target variable:

    • 첫번째 시도 : 지난번에 찾아봤던 stackoverflow 글을 다시 읽어보았다. 가중치에 숫자가 추가된 경우에 이런 오류가 발생한다고 하여 model.json파일에서 "lstm_25/lstm_cell_25/kernel"을 모두 "lstm/lstm_cell/kernel"로 바꿔주었다. 하지만 ❌실패❌

    • 두번째 시도 : tfjs 깃허브의 Issues를 참고하였다.
      • 답변으로 따르면 TensorFlow.js 버전 2.0.0의 버그이고 2.0.1로 업그레이드 하면 된다고 한다. ⭕성공⭕
      • 성공해서 굉장히 기뻤지만 한편으로는 너무 단순한 이유여서 착잡했다.

여섯번째 오류 (진행 중)

  • 모델에 전달하는 배열이 모델이 예상한 크기가 아니다.
  • Uncaught (in promise) Error: Error when checking model : the Array of Tensors that you are passing to your model is not the size the model expexted. Expexted to see 1 Tensor(s), but instead got 0 Tensors(s).

일곱번째 오류


(추가) 깃허브로 사이트 배포하기


참고
https://velog.io/@1106laura/tensorflowjsinfrontend

profile
주절주절 TMI를 쓰는 걸 좋아하는 개발 블로그 ✒️🥔

0개의 댓글