이재빈

Core Cloud 전처리 프레임 수신 및 예측모듈 작성

import socket
import cv2
import numpy as np
from multiprocessing import Queue
from labeling_module import LabelingModule
#socket에서 수신한 버퍼를 반환함.
def recvall(sock, count):
# 바이트 문자열
buf = b''
while count:
newbuf = sock.recv(count)
if not newbuf: return None
buf += newbuf
count -= len(newbuf)
return buf
if __name__ == "__main__":
lm.predict_process.start()
HOST='127.0.0.1'
PORT=9999
#TCP 사용
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print('Socket created')
#서버의 아이피와 포트번호 지정
s.bind((HOST,PORT))
print('Socket bind complete')
# 클라이언트의 접속을 기다린다. (클라이언트 연결을 10개까지 받는다)
s.listen(10)
print('Socket now listening')
#연결, conn에는 소켓 객체, addr은 소켓에 바인드 된 주소
conn,addr=s.accept()
while True:
# client에서 받은 stringData의 크기 (==(str(len(stringData))).encode().ljust(16))
length = recvall(conn, 16)
stringData = recvall(conn, int(length))
data = np.fromstring(stringData, dtype = 'uint8')
#data를 디코딩한다.
cropped = cv2.imdecode(data, cv2.IMREAD_COLOR)
cropped = cv2.resize(cropped, (48,48)) #Crop Image Resize
lm.new_tensor(cropped) # Predict result
lm.predict_process.join() # thread join
\ No newline at end of file
# plaidml
# import plaidml.keras
# plaidml.keras.install_backend()
# packages
from keras.models import load_model
from keras.preprocessing import image
# import queue
import numpy as np
from queue import Full, Empty
from multiprocessing import Process, Queue
class LabelingModule:
def __init__(self):
# self.model1 = load_model('svhn_model.h5')
self.model2 = load_model('svhn_model.h5')
self.image_queue = Queue(maxsize=3000)
self.label_queue = Queue(maxsize=10)
self.signal_queue = Queue()
self.predict_process = Process(target=_predict, \
args=(self.model2, self.image_queue, self.label_queue, self.signal_queue))
def run(self):
self.predict_process.start()
def close(self):
self.image_queue.close()
self.label_queue.close()
def new_tensor(self, tensor):
try:
self.image_queue.put(tensor)
except Full:
print('[LabelingModule] image_queue is full')
def new_image(self, filename):
tensor = self._img_to_tensor(filename)
try:
self.image_queue.put(tensor)
except Full:
print('[LabelingModule] image_queue is full')
def _img_to_tensor(self, filename):
img = image.load_img(filename, target_size=(48, 48))
img_tensor = image.img_to_array(img)
img_tensor = np.squeeze(img_tensor)
img_tensor /= 255.
img_tensor = img_tensor - img_tensor.mean()
return img_tensor
def _predict(model, input_queue, output_queue, signal_queue):
print('predict process started.')
while True:
try:
signal = signal_queue.get_nowait()
if signal == 'stop':
break
except Empty:
pass
tensor = input_queue.get(timeout=-1)
dat = model.predict(np.array([tensor]))
o1 = np.argmax(dat[0])
o2 = np.argmax(dat[1])
o3 = np.argmax(dat[2])
o4 = np.argmax(dat[3])
o5 = np.argmax(dat[4])
o6 = np.argmax(dat[5])
output = [o1, o2, o3, o4, o5, o6]
print('[LabelingModule] predict result :', output)