HDserver-dahua

# -*- coding: utf-8 -*-
from flask import Flask, request
import base64
import numpy as np
import json
from PIL import Image
import PIL.Image
from mmdet.apis import init_detector, inference_detector
import mmcv
import cv2

config_file = '/home/hdkj/mmdetection/configs/faster_rcnn_r50_fpn_1x.py'
checkpoint_file = '/home/hdkj/mmdetection/work_dirs/faster_rcnn_r50_fpn_1x/drinks0511/epoch_12.pth'
model = init_detector(config_file, checkpoint_file, device='cuda:0')

app = Flask("my-app")
@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/decimage', methods=['POST'])
def getimage():
    image_base64 = request.json['image']
    score_thr = request.json['score_thr']
    img = base64.b64decode(image_base64)
    img = np.fromstring(img, np.uint8)
    img = cv2.imdecode(img, cv2.IMREAD_COLOR)
    result1 = inference_detector(model, img)
    data = show(img, result1, model.CLASSES)
    bboxes = data[0]
    labels = data[1]
    result = get_bboxes(bboxes, labels, model.CLASSES, score_thr)
    json_result = json.dumps(result)
    return json_result


# def load_image_file(file, mode='RGB'):
#     """
#     Loads an image file (.jpg, .png, etc) into a numpy array
#
#     :param file: image file name or file object to load
#     :param mode: format to convert the image to. Only 'RGB' (8-bit RGB, 3 channels) and 'L' (black and white) are supported.
#     :return: image contents as numpy array
#     """
#     im = PIL.Image.open(file)
#     if mode:
#         im = im.convert(mode)
#     return np.array(im)


def show(img, result, class_names):
    assert isinstance(class_names, (tuple, list))
    img = mmcv.imread(img)
    img = img.copy()
    if isinstance(result, tuple):
        bbox_result, segm_result = result
    else:
        bbox_result, segm_result = result, None
    bboxes = np.vstack(bbox_result)
    # draw bounding boxes
    labels = [
        np.full(bbox.shape[0], i, dtype=np.int32)
        for i, bbox in enumerate(bbox_result)
    ]
    labels = np.concatenate(labels)
    return bboxes, labels


def get_bboxes(bboxes, labels, class_names, score_thr=0):
    assert bboxes.ndim == 2
    assert labels.ndim == 1
    assert bboxes.shape[0] == labels.shape[0]
    assert bboxes.shape[1] == 4 or bboxes.shape[1] == 5

    if score_thr > 0:
        assert bboxes.shape[1] == 5
        scores = bboxes[:, -1]
        inds = scores > score_thr
        bboxes = bboxes[inds, :]
        labels = labels[inds]

    dict_list = []
    for bbox, label in zip(bboxes, labels):
        bbox_int = bbox.astype(np.int32)
        label_text = class_names[
            label] if class_names is not None else 'cls {}'.format(label)
        label_text1 = class_names[
            label] if class_names is not None else 'cls {}'.format(label)
        if len(bbox) > 4:
            label_text += '|{:.02f}'.format(bbox[-1])
        obj_dict = {}
        obj_dict['similarity'] = label_text
        obj_dict['name'] = label_text1
        obj_dict['xmin'] = str(bbox_int[0])
        obj_dict['ymax'] = str(bbox_int[1])
        obj_dict['xmax'] = str(bbox_int[2])
        obj_dict['ymin'] = str(bbox_int[3])
        dict_list.append(obj_dict)
    print(dict_list)
    return dict_list

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5004)

 

你可能感兴趣的:(人工智能)