flask에 opencv tensorflow 카메라 실행 코드 배포 1

reenact_l·2023년 6월 10일
0

server

목록 보기
7/11

flask를 통한 파이썬 코드 배포 내용이다

#현재 주어진 환경
0. 카메라를 통해 수어를 인식하고 결과같을 출력하는 코드
1. 코드는 완성되어있음
2. 해당 코드를 flask로 서버에 올려야함
3. pycharm/ anaconda3 / flask 사용

  1. 완성된 코드는 github에서 clone해서 가져옴
  2. pycharm에서 conda 설치후 해당 가상환경으로 코드 실행
  3. 필요 라이브러리 설치 (tensorflow, sklearn , matplotlib, numpy, opencv, pyttsx )
  4. 참고 url
    https://www.appsloveworld.com/python/1059/how-to-install-pyttsx-in-anaconda3
    https://taksw222.tistory.com/135
    https://yong0810.tistory.com/22

가장 많이 참조 flask opencv

5.기존 코드의 경우 modules.py를 실행하는 경우 해당 코드가 실행됨

그러나 이는 컴퓨터 내에서고 우리의 문제는 이를 서버에 올려야함 그러므로 flask를 사용함

conda install flask 
or
pycharm file-setting-Project:project이름 -project interpreter에서 +버튼 누르고 필요한 lib install```

flask를 통한 웹페이지 배포를 위한 가장 기본이 되는 코드

from flask import Flask
app = Flask(name)
@app.route('/') """메인 페이지 주소"""
def home():
return 'This is Home!'
if name == 'main':
app.run()

여기서 수정을 진행함
def home(): return 'this is home'
이렇게 하면 html 메인 페이지에 this is home 만 나옴

내가 진행해야하는건 이 메인페이지에 카메라가 나오도록 만들어야함

필요한것
1. main.html
2. app.py에서 sign-language 코드 실행

진행한 것
1. main.html

  1. app.py에서의 실행코드
from flask import Flask, render_template ,Response
from MP_holistic_styled_landmarks import mp_holistic,draw_styled_landmarks
from mediapipe_detection import mediapipe_detection
from keypoints_extraction import extract_keypoints
import keras
from folder_setup import *
from visualization import prob_viz,colors
from PIL import ImageFont, ImageDraw, Image
import pyttsx3

app=Flask(__name__)

@app.route('/')

def main():
    return render_template('home.html')

def get_frames():
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
    sequence = []
    sentence = []
    threshold = 0.9
    model = keras.models.load_model('d3test3.h5')
    # model = keras.models.load_model('test_cap.h5')
    cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

mean = "수화 단어:"
with mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic:
    while cap.isOpened():
        ret, frame = cap.read()

        image, results = mediapipe_detection(frame, holistic)

        draw_styled_landmarks(image, results)

        keypoints = extract_keypoints(results)
        sequence.append(keypoints)
        sequence = sequence[-50:]
        # print(len(sequence))
        b, g, r, a = 255, 255, 255, 0
        fontpath = "GowunDodum-Regular.ttf"
        img_pil = Image.fromarray(image)
        draw = ImageDraw.Draw(img_pil)

        if len(sequence) == 50:
            res = model.predict(np.expand_dims(sequence, axis=0))[0]
            # print(np.argmax(res))

            print(actions[np.argmax(res)])
            mean = "수화 단어:" + actions[np.argmax(res)]
            s = pyttsx3.init()
            data = str(actions[np.argmax(res)])
            s.say(data)
            s.runAndWait()

            sequence.clear()
            cv2.waitKey(100)

            if res[np.argmax(res)] > threshold:
                if len(sentence) > 0:
                    if actions[np.argmax(res)] != sentence[-1]:
                        sentence.append(actions[np.argmax(res)])
                else:
                    sentence.append(actions[np.argmax(res)])

            if len(sentence) > 2:
                sentence = sentence[-2:]

            # image = prob_viz(res, actions, image, colors)

        draw.rectangle([(0, 0), (550, 40)], fill=(96, 96, 96, 0), outline=(255, 51, 51), width=2)
        draw.rectangle([(0, 50), (400, 100)], fill=(96, 96, 96, 0), outline=(255, 51, 51), width=2)
        draw.ellipse((1180, 20, 1270, 95), fill=(96, 96, 96, 0), outline=(255, 51, 51), width=2)

        draw.text((10, 10), "이전 단어 목록: " + ' '.join(sentence), font=ImageFont.truetype(fontpath, 20),
                  fill=(b, g, r, a))
        draw.text((10, 50), mean, font=ImageFont.truetype(fontpath, 40), fill=(b, g, r, a))
        draw.text((1200, 30), str(len(sequence)), font=ImageFont.truetype(fontpath, 40), fill=(b, g, r, a))
        image = np.array(img_pil)

        cv2.imshow('Korean Sign-language', image)

        if cv2.waitKey(10) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()
    """def video_feed():
		return Response(get_frames())"""
   	if __name__ == '__main__':
		app.run(debug=True)

실행결과


서버 업로드는 된거 같은데 들어가보면 무한 업로드 중..
내가 가진 컴퓨터가 카메라가 없어서 그런건지 잘 모르겠음...

profile
icantdoanything

0개의 댓글