目標檢測應用化之web頁面(YOLO、SSD等)


在caffe源碼目錄下的examples下面有個web_demo演示代碼,其使用python搭建了Flask web服務器進行ImageNet圖像分類的演示。

首先安裝python的依賴庫:pip install -r examples/web_demo/requirements.txt

接下來,修改源碼,僅三個代碼文件:

  • app.py 這是主程序的入口
  • exifutil.py 輔助代碼,解決skimage庫不能處理exif標志的問題
  • templates/index.html 前端web頁面

解決python2中的中文問題:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

exifutil.py中刪除img = np.asarray(im).astype(np.float32) / 255.這句歸一化的代碼(視情況自行修改)。

網絡模型調用

將模型加載和前向傳播計算的相關代碼寫在另外的新增的python代碼中。如YOLO和SSD均提供了python使用模型進行測試的代碼,稍作修改即可。

結果顯示

結果框畫框代碼:

from PIL import Image, ImageDraw

def draw_rectangle(draw, coordinates, color, width=1, draw_ellipse=False):
    for i in range(width):
        rect_start = (coordinates[0] - i, coordinates[1] - i)
        rect_end = (coordinates[2] + i, coordinates[3] + i)
        if draw_ellipse:
            draw.ellipse((rect_start, rect_end), outline=color)
        else:
            draw.rectangle((rect_start, rect_end), outline=color)

def draw_rectangles(image_pil,det_result):
    # draw rectangles
    draw = ImageDraw.Draw(image_pil)
    for idx, item in enumerate(det_result):
        x, y, w, h = item[2]
        half_w = w / 2
        half_h = h / 2
        box = (int(x - half_w+1), int(y - half_h+1), int(x + half_w+1), int(y + half_h+1))
        draw_rectangle(draw,box,(0, 255, 0),width=2,draw_ellipse=True)
        draw.text((x - half_w + 5, y - half_h + 5), str(idx + 1)+" : "+item[0], fill=(0, 0, 150))
    del draw

得到模型的預測結果之后使用上述畫框代碼畫框后在flask.render_template時將畫了結果框的圖像顯示在HTML頁面上。

HTML頁面內容適配

在調用如下代碼時flask會將參數變量傳給頁面填充部分。

flask.render_template('index.html', has_result=True, result=results,
    imagesrc=new_img_base64
)

在html頁面代碼中可以使用{{ result }}的形式來獲取這些參數變量的值,並且可以使用if...else, for等語句控制html代碼的填充。此步要做的就是修改app.py和html適配的內容一致。

詳細代碼在此:https://github.com/makefile/objdet_web

效果圖


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM