2019-08-09 YOLO算法

**一邓夕、用到的工具**

pycharm

postman

flask框架

yaml文件

gunicorn

**二岸啡、過程**

1.最開始的時候準備好文件罢艾,拷貝到自己的電腦里臀玄。

decu文件渊额,下面有一個huojia和一個didui况木。

在huojia和didui中分別還有五個小文件垒拢,

格式是decu_anchors.txt,decu_classes.txt火惊,,cfg , .h5, .weight求类。

2.分析得到的yolo.py里面的程序,解析每一個變量的數(shù)據(jù)是什么屹耐。

3.編寫最基本的flask框架尸疆。

```

from flask import Flask, request, Response

app = Flask(__name__)

@app.route('/', methods=["GET", "POST"])

def predict():

params = json.loads(request.get_data())

paths = params['data']

return paths

if __name__ == '__main__':

app.run(processes=1, threaded=True)

```

這樣簡單的框架就出來了,params返回數(shù)據(jù)惶岭,并且取數(shù)據(jù)中的“data”寿弱,也就是圖片網(wǎng)址。

4.修改yolo按灶。

主要是后面for循環(huán)症革,取出坐標值。

注意兆衅,prob這個值小數(shù)點后數(shù)值太多地沮,如果不進行修改,那么會報錯羡亩。

所以寫成這個格式

```

"prob": float('%.7f' % score)

```

最后返回的整理一下摩疑,就變成

```

result = {"status": {"code": 200,"msg": "OK"},"head": {"method": "/predict","service": "xuehua_service","time": str(end_run - start_run)},"body": {"predictions": predictions_list}}

return result

```

這樣最后的yolo.py,在數(shù)值部分就修改差不多了畏铆。

5.文件的調(diào)用雷袋。

我們這次在flask框架,調(diào)用yolo.py中的YOLO這個類辞居。

所以我們在xuehua_flask.py中楷怒,就寫

```

from keras_yolo.yolo import YOLO

```

剛開始將yolo_huojia = YOLO()寫在了def函數(shù)里面,會發(fā)現(xiàn)運行的很慢瓦灶。

所以鸠删,我們將這個寫在外邊。

也就是

```

app = Flask(__name__)

yolo_huojia = YOLO()

yolo_didui = YOLO_DIDUI()

@app.route('/', methods=["GET", "POST"])

def predict():

```

這樣贼陶。

6.gunicorn的使用刃泡。

我們先運用了一個虛擬環(huán)境tensorflow,然后在terminal中調(diào)用虛擬環(huán)境碉怔。

```

source activate tensorflow? # 啟動虛擬環(huán)境

gunicorn -c conf/gunicorn.py xuehua_flask:app # 運行程序

```

7.yolo代碼

```

# -*- coding: utf-8 -*-

"""

Class definition of YOLO_v3 style detection model on image and video

"""

import colorsys

from timeit import default_timer as timer

import numpy as np

from keras import backend as K

from keras.models import load_model

from keras.layers import Input

from PIL import Image, ImageFont, ImageDraw

from keras_yolo.yolo3.model import yolo_eval, yolo_body, tiny_yolo_body

from keras_yolo.yolo3.utils import letterbox_image

import os

from keras.utils import multi_gpu_model

from io import BytesIO

import requests

import time

import yaml

class YOLO(object):

? ? curPath = os.path.dirname(os.path.realpath(__file__))

? ? yamlpath = os.path.join(curPath, "../conf/params.yaml")

? ? f = open(yamlpath, 'r', encoding='utf-8')

? ? cfg = f.read()

? ? # print(cfg)

? ? d = yaml.load(cfg, Loader=yaml.FullLoader)

? ? _defaults = {

? ? ? ? "model_path": d.get("model_path"),

? ? ? ? "anchors_path": d.get("anchors_path"),

? ? ? ? "classes_path": d.get("classes_path"),

? ? ? ? "score" : int(d.get("score")),

? ? ? ? "iou" : float(d.get("iou")),

? ? ? ? "model_image_size" : eval(d.get("model_image_size")),

? ? ? ? "gpu_num" : int(d.get("gpu_num"))

? ? }


? ? @classmethod

? ? def get_defaults(cls, n):

? ? ? ? if n in cls._defaults:

? ? ? ? ? ? return cls._defaults[n]

? ? ? ? else:

? ? ? ? ? ? return "Unrecognized attribute name '" + n + "'"

? ? def __init__(self, **kwargs):

? ? ? ? self.__dict__.update(self._defaults) # set up default values

? ? ? ? self.__dict__.update(kwargs) # and update with user overrides

? ? ? ? self.class_names = self._get_class()

? ? ? ? self.anchors = self._get_anchors()

? ? ? ? self.sess = K.get_session()

? ? ? ? self.boxes, self.scores, self.classes = self.generate()

? ? def _get_class(self):

? ? ? ? classes_path = os.path.expanduser(self.classes_path)

? ? ? ? with open(classes_path) as f:

? ? ? ? ? ? class_names = f.readlines()

? ? ? ? class_names = [c.strip() for c in class_names]

? ? ? ? return class_names

? ? def _get_anchors(self):

? ? ? ? anchors_path = os.path.expanduser(self.anchors_path)

? ? ? ? with open(anchors_path) as f:

? ? ? ? ? ? anchors = f.readline()

? ? ? ? anchors = [float(x) for x in anchors.split(',')]

? ? ? ? return np.array(anchors).reshape(-1, 2)

? ? def generate(self):

? ? ? ? model_path = os.path.expanduser(self.model_path)

? ? ? ? assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'

? ? ? ? # Load model, or construct model and load weights.

? ? ? ? num_anchors = len(self.anchors)

? ? ? ? num_classes = len(self.class_names)

? ? ? ? is_tiny_version = num_anchors==6 # default setting

? ? ? ? try:

? ? ? ? ? ? self.yolo_model = load_model(model_path, compile=False)

? ? ? ? except:

? ? ? ? ? ? self.yolo_model = tiny_yolo_body(Input(shape=(None,None,3)), num_anchors//2, num_classes) \

? ? ? ? ? ? ? ? if is_tiny_version else yolo_body(Input(shape=(None,None,3)), num_anchors//3, num_classes)

? ? ? ? ? ? self.yolo_model.load_weights(self.model_path) # make sure model, anchors and classes match

? ? ? ? else:

? ? ? ? ? ? assert self.yolo_model.layers[-1].output_shape[-1] == \

? ? ? ? ? ? ? ? num_anchors/len(self.yolo_model.output) * (num_classes + 5), \

? ? ? ? ? ? ? ? 'Mismatch between model and given anchor and class sizes'

? ? ? ? print('{} model, anchors, and classes loaded.'.format(model_path))

? ? ? ? # Generate colors for drawing bounding boxes.

? ? ? ? hsv_tuples = [(x / len(self.class_names), 1., 1.)

? ? ? ? ? ? ? ? ? ? ? for x in range(len(self.class_names))]

? ? ? ? self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))

? ? ? ? self.colors = list(

? ? ? ? ? ? map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),

? ? ? ? ? ? ? ? self.colors))

? ? ? ? np.random.seed(10101)? # Fixed seed for consistent colors across runs.

? ? ? ? np.random.shuffle(self.colors)? # Shuffle colors to decorrelate adjacent classes.

? ? ? ? np.random.seed(None)? # Reset seed to default.

? ? ? ? # Generate output tensor targets for filtered bounding boxes.

? ? ? ? self.input_image_shape = K.placeholder(shape=(2, ))

? ? ? ? if self.gpu_num>=2:

? ? ? ? ? ? self.yolo_model = multi_gpu_model(self.yolo_model, gpus=self.gpu_num)

? ? ? ? boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors,

? ? ? ? ? ? ? ? len(self.class_names), self.input_image_shape,

? ? ? ? ? ? ? ? score_threshold=self.score, iou_threshold=self.iou)

? ? ? ? return boxes, scores, classes

? ? def detect_image(self, paths):

? ? ? ? predictions_list = []

? ? ? ? t = time.time()

? ? ? ? start_run = int(round(t*1000))

? ? ? ? classes = []

? ? ? ? for path in paths:

? ? ? ? ? ? bytes_io_obj = BytesIO()

? ? ? ? ? ? bytes_io_obj.write(requests.get(path).content)

? ? ? ? ? ? image = Image.open(bytes_io_obj)

? ? ? ? ? ? if self.model_image_size != (None, None):

? ? ? ? ? ? ? ? assert self.model_image_size[0]%32 == 0, 'Multiples of 32 required'

? ? ? ? ? ? ? ? assert self.model_image_size[1]%32 == 0, 'Multiples of 32 required'

? ? ? ? ? ? ? ? boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))

? ? ? ? ? ? else:

? ? ? ? ? ? ? ? new_image_size = (image.width - (image.width % 32),

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? image.height - (image.height % 32))

? ? ? ? ? ? ? ? boxed_image = letterbox_image(image, new_image_size)

? ? ? ? ? ? image_data = np.array(boxed_image, dtype='float32')

? ? ? ? ? ? image_data /= 255.

? ? ? ? ? ? image_data = np.expand_dims(image_data, 0)? # Add batch dimension.

? ? ? ? ? ? out_boxes, out_scores, out_classes = self.sess.run(

? ? ? ? ? ? ? ? [self.boxes, self.scores, self.classes],

? ? ? ? ? ? ? ? feed_dict={

? ? ? ? ? ? ? ? ? ? self.yolo_model.input: image_data,

? ? ? ? ? ? ? ? ? ? self.input_image_shape: [image.size[1], image.size[0]],

? ? ? ? ? ? ? ? ? ? # K.learning_phase(): 0

? ? ? ? ? ? ? ? })

? ? ? ? ? ? for i, c in reversed(list(enumerate(out_classes))):

? ? ? ? ? ? ? ? box = out_boxes[i]

? ? ? ? ? ? ? ? score = out_scores[i]

? ? ? ? ? ? ? ? top, left, bottom, right = box

? ? ? ? ? ? ? ? top = max(0, np.floor(top + 0.5).astype('int32'))

? ? ? ? ? ? ? ? left = max(0, np.floor(left + 0.5).astype('int32'))

? ? ? ? ? ? ? ? bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))

? ? ? ? ? ? ? ? right = min(image.size[0], np.floor(right + 0.5).astype('int32'))

? ? ? ? ? ? ? ? classes.append({"prob": float('%.7f' % score), "cat": str(c), "bbox": {"ymax": int(bottom), "xmax": int(right), "ymin": int(top), "xmin":int(left) }})

? ? ? ? ? ? predict_dict = {"classes":classes, "uri":path}

? ? ? ? ? ? predictions_list.append(predict_dict)

? ? ? ? t = time.time()

? ? ? ? end_run = int(round(t * 1000))

? ? ? ? result = {"status": {"code": 200,"msg": "OK"},"head": {"method": "/predict","service": "xuehua_service","time": str(end_run - start_run)},"body": {"predictions": predictions_list}}

? ? ? ? return result

? ? def close_session(self):

? ? ? ? self.sess.close()

```

8.flask框架代碼

```

from flask import Flask, request, Response

from keras_yolo.yolo import YOLO

from keras_yolo.yolo_didui import YOLO_DIDUI

import json

app = Flask(__name__)

yolo_huojia = YOLO()

yolo_didui = YOLO_DIDUI()

@app.route('/', methods=["GET", "POST"])

def predict():

? ? b = ''

? ? global yolo_huojia, yolo_didui

? ? params = json.loads(request.get_data())

? ? paths = params['data']

? ? model_type = params['model_type']

? ? if 0 == model_type:

? ? ? ? b = yolo_huojia.detect_image(paths=paths)

? ? if 1 == model_type:

? ? ? ? b = yolo_didui.detect_image(paths=paths)

? ? return Response(json.dumps(b), mimetype='application/json')

if __name__ == '__main__':

? ? app.run(processes=1, threaded=True)

```

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末烘贴,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子撮胧,更是在濱河造成了極大的恐慌桨踪,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,542評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件芹啥,死亡現(xiàn)場離奇詭異锻离,居然都是意外死亡铺峭,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,596評論 3 385
  • 文/潘曉璐 我一進店門纳账,熙熙樓的掌柜王于貴愁眉苦臉地迎上來逛薇,“玉大人捺疼,你說我怎么就攤上這事疏虫。” “怎么了啤呼?”我有些...
    開封第一講書人閱讀 158,021評論 0 348
  • 文/不壞的土叔 我叫張陵卧秘,是天一觀的道長。 經(jīng)常有香客問我官扣,道長翅敌,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,682評論 1 284
  • 正文 為了忘掉前任惕蹄,我火速辦了婚禮蚯涮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘卖陵。我一直安慰自己遭顶,他們只是感情好,可當我...
    茶點故事閱讀 65,792評論 6 386
  • 文/花漫 我一把揭開白布泪蔫。 她就那樣靜靜地躺著棒旗,像睡著了一般。 火紅的嫁衣襯著肌膚如雪撩荣。 梳的紋絲不亂的頭發(fā)上铣揉,一...
    開封第一講書人閱讀 49,985評論 1 291
  • 那天,我揣著相機與錄音餐曹,去河邊找鬼逛拱。 笑死,一個胖子當著我的面吹牛台猴,可吹牛的內(nèi)容都是我干的朽合。 我是一名探鬼主播,決...
    沈念sama閱讀 39,107評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼卿吐,長吁一口氣:“原來是場噩夢啊……” “哼旁舰!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起嗡官,我...
    開封第一講書人閱讀 37,845評論 0 268
  • 序言:老撾萬榮一對情侶失蹤箭窜,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后衍腥,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體磺樱,經(jīng)...
    沈念sama閱讀 44,299評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡纳猫,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,612評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了竹捉。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片芜辕。...
    茶點故事閱讀 38,747評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖块差,靈堂內(nèi)的尸體忽然破棺而出侵续,到底是詐尸還是另有隱情,我是刑警寧澤憨闰,帶...
    沈念sama閱讀 34,441評論 4 333
  • 正文 年R本政府宣布状蜗,位于F島的核電站,受9級特大地震影響鹉动,放射性物質(zhì)發(fā)生泄漏轧坎。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 40,072評論 3 317
  • 文/蒙蒙 一泽示、第九天 我趴在偏房一處隱蔽的房頂上張望缸血。 院中可真熱鬧,春花似錦械筛、人聲如沸捎泻。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,828評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽族扰。三九已至,卻和暖如春定欧,著一層夾襖步出監(jiān)牢的瞬間渔呵,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,069評論 1 267
  • 我被黑心中介騙來泰國打工砍鸠, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留扩氢,地道東北人。 一個月前我還...
    沈念sama閱讀 46,545評論 2 362
  • 正文 我出身青樓爷辱,卻偏偏與公主長得像录豺,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子饭弓,可洞房花燭夜當晚...
    茶點故事閱讀 43,658評論 2 350

推薦閱讀更多精彩內(nèi)容