inflearn logo
강의

Course

Instructor

Deep Learning Web Service Project 1 - Basics. Object Detect Defective Product Identification

밑에 분들하고 비슷한 에러네요...

1043

smallchange5037

2 asked

0

아이오닉 웹앱 클라이언트 챕터에서

웹앱 웹서비스 테스트를 수행하고 있는데요.

아이오닉 로컬호스트에서는 실행이 잘되는데,

플라스크 실행해서 플라스크 서버를 들어가면 문제가 생깁니다.

크롬으로 플라스크 서버 192.168.0.10:5000을 입력해서 들어가면, 

(저는 이상하게 0.0.0.0으로 app run을 해도 192.168.0.10:5000으로 호스트가 뜹니다.)

Method Not Allowed

The method is not allowed for the requested URL.

이런 메세지가 나오구요.

@app.route('/dnn/yolo'methods=['POST'])

위 코드를

@app.route('/dnn/yolo'methods=['GET''POST'])

으로 바꾸면, key error 'model'이 나오는데요...

뭔가 틀렸나싶어 예제코드를 아무리 붙여봐도 안되는데.ㅠㅠ

뭐가 잘못되었는지를 모르겠습니다...

flask 버전을 1.1.1로 바꿔도 안되고...

브라우저를 웨일이나 인터넷익스플로러로 해도 안되고...

몇시간째 헤매고 있네요..ㅠ

key error 모델에러는 다음과 같이 나구요..

werkzeug.exceptions.BadRequestKeyError

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'model'

Traceback (most recent call last)

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'model'
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.

To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

아래는 flask main.py 코드입니다.

from flask import FlaskrequestResponsejsonify
import base64
from flask_cors import CORS
import numpy as np
import cv2
from PIL import Image
from io import BytesIO

confthres=0.5
nmsthres=0.1

app = Flask(__name__)
CORS(app)

@app.route('/dnn/yolo'methods=['GET''POST'])

def main():
    model = request.form['model']
    if model == 'apple':
        labelsPath="./model/classes.names"   
        configpath="./model/apple-train-yolo.cfg" 
        weightspath="./model/apple-train-yolo_final.weights"  
    else:       
        labelsPath="./model/coco.names"   
        configpath="./model/yolov3.cfg" 
        weightspath="./model/yolov3.weights"  

    print("[INFO] loading "model.upper(), " models...")
    LABELS = open(labelsPath).read().strip().split("\n")
    net = cv2.dnn.readNetFromDarknet(configpathweightspath

    file = request.form['image']
    starter = file.find(',')
    image_data = file[starter+1:]
    image_data = bytes(image_dataencoding="ascii")
    img = Image.open(BytesIO(base64.b64decode(image_data))) 
    #img = cv2.imread('./dog.jpg')
    npimg=np.array(img)
    image=npimg.copy()
    image=cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
    (HW) = image.shape[:2]

    ln = net.getLayerNames()
    ln = [ln[i[0] - 1for i in net.getUnconnectedOutLayers()]

    blob = cv2.dnn.blobFromImage(image1 / 255.0, (416416),
                                 swapRB=Truecrop=False)
    net.setInput(blob)
    layerOutputs = net.forward(ln)

    boxes = []
    confidences = []
    classes = []
    results = [] 

    for output in layerOutputs:
        for detection in output:
            scores = detection[5:]
            classID = np.argmax(scores)
            confidence = scores[classID]

            if confidence > confthres:
                box = detection[0:4] * np.array([WHWH])
                (centerXcenterYwidthheight) = box.astype("int")

                x = int(centerX - (width / 2))
                y = int(centerY - (height / 2))

                boxes.append([xyint(width), int(height)])
                confidences.append(float(confidence))
                classes.append({ 'id'int(classID), 'name'LABELS[classID] })

    idxs = cv2.dnn.NMSBoxes(boxesconfidencesconfthres,
                            nmsthres)

    if len(idxs) > 0:
        for i in idxs.flatten():
            results.append({ 'class'classes[i], 'confidence'confidences[i], 'bbox'boxes[i] })

    return jsonify(results)

# start flask app
if __name__ == '__main__':
    app.run(debug=Truehost='0.0.0.0')

IONIC 구글-앱-엔진 pwa flask

Answer 1

0

nomad

안녕하세요?

답변이 늦어졌네요.

일단 192...는 현재 실행 중인 장치의 내부망 주소입니다. 그러므로 그 아이피에서 실행되는 것은 정상입니다.

post방식을 사용하지 안고 get방식을 사용하면 파라미터로 model값을 보내줘야합니다.

예제에 있는 내용데로 실행해 보세요.

감사합니다. 

노션 학습 자료 권한 요청

0

17

1

part2강의 문의사항입니다.

0

19

2

데스크톱과 노트북 연결

0

26

1

노션 : 파트3번 링크와 권한 , 파트4번 권한요청, 파트 5번도 미리 요청 드립니다.

0

27

4

antigravity 대신 cursor를 활용해도 되나요?

0

26

1

뉴스 검색 분류 한도초과

0

36

2

완성자료

0

25

2

노션 링크

0

52

3

노션 권한요청하였습니다 언제쯤 볼수있나요

0

45

2

5번 강의 1분까지 완료 후 오류가 뜹니다

0

34

2

노션 접속 권한 요청드립니다.

0

33

2

윈도우 사용자 환경설정

0

34

2

5-4-1. VCP 스캐너 만들기 프롬프트 질문

0

33

1

코드 다운로드

0

420

3

다른 모델을 웹페이지에 적용

0

421

0

동시 요청

0

340

0

from flask import Flask, request, Resopnse, jsonify 여기서 에러가 나와요..!

0

355

1

에러 뜨면서 안되는데 어떻게 해야할까요

0

314

1

바운딩박스 조정

0

455

1

궁금한사항 올립니다.

0

300

2

400 Bad Request 발생합니다.

0

468

1

flask Method Not Allowed The method is not allowed for the requested URL오류발생

0

1159

2

app.yaml파일에 관해서

0

214

2

python main.py실행하면 아무런 반응이 없습니다.

0

650

3