臨時文件1

from flask import  Flask
from flask import request,jsonify
import json
import cv2
import base64
import numpy as np
import matplotlib.pyplot as plt
import datetime
import random
import os
import sys
import time
import copy
import torch
import argparse
import numpy as np
from PIL import Image, ImageQt
from model3 import MSFD, denormalization
from utils2 import crop_image



from pathlib import Path
import torch.backends.cudnn as cudnn
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
ROOT = "/home/kxy/czx/MSFD_INFERENCE"# os.getcwd()
print(type(ROOT))
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative
print(type(ROOT))

from models.common import DetectMultiBackend
from utils.datasets import IMG_FORMATS, VID_FORMATS, model2LoadImages2, LoadStreams
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr,
                           increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, time_sync

import logging
import logging.handlers

def init_log(logpath=os.getcwd() + "/log"):
    lg = logging.getLogger("Debug")
    log_path = logpath
    print(log_path)
    try:
        if not os.path.exists(log_path):
            os.makedirs(log_path)
    except:
        print("创建日志目录失败")
        exit(1)
    if len(lg.handlers) == 0:  # 避免重复
        # 2.创建handler(负责输出,输出到屏幕streamhandler,输出到文件filehandler)
        filename = os.path.join(log_path, datetime.datetime.now().strftime('%Y-%m-%d'))
        fh = logging.FileHandler(filename,mode="a",encoding="utf-8")#默认mode 为a模式,默认编码方式为utf-8
        sh = logging.StreamHandler()
        # 3.创建formatter:
        formatter=logging.Formatter(fmt='%(asctime)s - %(levelname)s - Model:%(filename)s - Fun:%(funcName)s - Message:%(message)s - Line:%(lineno)d')
        # 4.绑定关系:①logger绑定handler
        lg.addHandler(fh)
        lg.addHandler(sh)
        # # ②为handler绑定formatter
        fh.setFormatter(formatter)
        sh.setFormatter(formatter)
        # # 5.设置日志级别(日志级别两层关卡必须都通过,日志才能正常记录)
        lg.setLevel(logging.DEBUG)
        fh.setLevel(logging.DEBUG)
        sh.setLevel(logging.DEBUG)
    return lg
lg=init_log(logpath=os.getcwd() + "/log")

img_threshold_value=0.0001
pixel_threshold_value=0.0001
x_nums=1
y_nums=1
overlap_pix=16
def parse_args():
    parser = argparse.ArgumentParser(description='Fabric Anomaly Detection')
    #蒸餾
    parser.add_argument("--img_path", type=str, default="./")
    parser.add_argument('--save_path', type=str, default="./result")
    parser.add_argument("--model_path", type=str, default='model_s.pth')
    parser.add_argument("--model_path2", type=str, default='model_t.pth')
    parser.add_argument('--backbone', type=str, default='tf_efficientnet_b6')
    parser.add_argument('--img_resize', type=int, default=512)
    parser.add_argument('--img_cropsize', type=int, default=512)
    #yolov5
    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'best.pt', help='model path(s)')
    parser.add_argument('--source', type=str, default=ROOT / 'data/images/bus2.jpg', help='file/dir/URL/glob, 0 for webcam')
    parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
    parser.add_argument('--conf-thres', type=float, default=0.5, help='confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.5, help='NMS IoU threshold')
    parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
    parser.add_argument('--view-img', action='store_true', help='show results')
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
    parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
    parser.add_argument('--augment', action='store_true', help='augmented inference')
    parser.add_argument('--visualize', action='store_true', help='visualize features')
    parser.add_argument('--update', action='store_true', help='update all models')
    parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
    parser.add_argument('--name', default='exp', help='save results to project/name')
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
    parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
    parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
    parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    parser.add_argument('--device', default=device, help='')
    opt = parser.parse_args()
    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand
    print_args(FILE.stem, opt)
    return opt
opt = parse_args()
os.makedirs(opt.save_path, exist_ok=True)
#蒸餾算法
model = MSFD(opt) 
#yolov5
device=opt.device
model2 = DetectMultiBackend(opt.weights, device=device, dnn=opt.dnn, data=opt.data)
stride, names, pt, jit, onnx, engine = model2.stride, model2.names, model2.pt, model2.jit, model2.onnx, model2.engine
imgsz = check_img_size(opt.imgsz, s=stride)  # check image size
half = opt.half
# Half
half &= (pt or jit or onnx or engine) and device.type != 'cpu'  # FP16 supported on limited backends with CUDA
if pt or jit:
    model2.model.half() if half else model2.model.float()
model2.warmup(imgsz=(1, 3, *imgsz), half=half)  # warmup

app = Flask(__name__)
@app.route("/")
def index():
    return "Hello"

@app.route('/postdata', methods=['POST'])
def postdata():
    try:
        if not request.get_data() :
            #print("Error: failed to receive data")
            resSets= {
                'code': "1"
            }
            return jsonify(resSets)
        data = json.loads(request.get_data())
        if not ('id' in data):
            resSets= {
                'code': "1"
            }
            return jsonify(resSets)

        list1=""
        list2=""
        result1="0"
        result2="0"
        global   img_threshold_value
        global pixel_threshold_value
        global x_nums
        global y_nums
        global overlap_pix
        if ('img1' in data) and('img2' in data):

            image_list1 = data['img1']
            image_list2 = data['img2']
            img_file = str(data["id"])
            #img1
            image1 = base64.b64decode(image_list1)
            img_array1 = np.frombuffer(image1, np.uint8)
            img_get1 = cv2.imdecode(img_array1, cv2.IMREAD_COLOR)
            image2 = base64.b64decode(image_list2)
            img_array2 = np.frombuffer(image2, np.uint8)
            img_get2 = cv2.imdecode(img_array2, cv2.IMREAD_COLOR)

            sta_t =time.time()
            img = model.load_image_overlap(img_get1,img_get2,x_nums,y_nums,overlap_pix)
            dataset = model2LoadImages2(img_get1, img_size=imgsz, stride=stride, auto=pt,x_nums=x_nums,y_nums=y_nums,overlap_pix=overlap_pix)
            dataset2 = model2LoadImages2(img_get2, img_size=imgsz, stride=stride, auto=pt,x_nums=x_nums,y_nums=y_nums,overlap_pix=overlap_pix)
            print("time cost:"+str(time.time()-sta_t)) 
            # sta_t =time.time()
            result = model.inference(img, img_file,img_threshold_value,pixel_threshold_value,0,overlap_pix)
            result_yolo=model2.inference(dataset,model2,device,half,opt.augment,opt.conf_thres,opt.iou_thres, opt.classes, opt.agnostic_nms, opt.max_det,opt.save_crop,names,x_nums,y_nums,overlap_pix)
            result_yolo2=model2.inference(dataset2,model2,device,half,opt.augment,opt.conf_thres,opt.iou_thres, opt.classes, opt.agnostic_nms, opt.max_det,opt.save_crop,names,x_nums,y_nums,overlap_pix)
            # print(result_yolo)
            # print("time cost:"+str(time.time()-sta_t))
            # print("score:"+result[2]) 
            result1=result[1]
            list1=result[3]
            if(not(result_yolo=="")):
                result1="0"
                list1+=","+result_yolo
            result2=result[4]
            list2=result[6]
            if(not(result_yolo2=="")):
                result2="0"
                list2+=","+result_yolo2
            resSets={
                "code":"0",
                "id":str(data["id"]),
                "result1":result1,
                "result2":result2,
                "list1":list1,
                "list2":list2
                # ,"time":datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
            }
            return jsonify(resSets)
        elif ('img1' in data) :
            image_list1 = data['img1']
            img_file = str(data["id"])
            #img1
            image1 = base64.b64decode(image_list1)
            img_array1 = np.frombuffer(image1, np.uint8)
            img_get1 = cv2.imdecode(img_array1, cv2.IMREAD_COLOR)
            sta_t =time.time()
            img1 = model.load_image_overlap(img_get1,None,x_nums,y_nums,overlap_pix)
            dataset = model2LoadImages2(img_get1, img_size=imgsz, stride=stride, auto=pt,x_nums=x_nums,y_nums=y_nums,overlap_pix=overlap_pix)
            print("time cost:"+str(time.time()-sta_t))
            # img1 = model.load_image(img_get1,x_nums,y_nums)
            # sta_t =time.time()
            result = model.inference(img1, img_file,img_threshold_value,pixel_threshold_value,1,overlap_pix)
            result_yolo=model2.inference(dataset,model2,device,half,opt.augment,opt.conf_thres,opt.iou_thres, opt.classes, opt.agnostic_nms, opt.max_det,opt.save_crop,names,x_nums,y_nums,overlap_pix)

            # print("time cost:"+str(time.time()-sta_t))
            result1=result[1]
            list1=result[3]
            resSets = {
                'code': "2",
                "id":str(data["id"]),
                "result1":result1,
                "list1":list1
            }
            return jsonify(resSets)
        elif ('img2' in data) :

            image_list2 = data['img2']
            img_file = str(data["id"])
            #img2
            image2 = base64.b64decode(image_list2)
            img_array2 = np.frombuffer(image2, np.uint8)
            img_get2 = cv2.imdecode(img_array2, cv2.IMREAD_COLOR)
            
            img2 = model.load_image_overlap(img_get2,None,x_nums,y_nums,overlap_pix)
            dataset2 = model2LoadImages2(img_get2, img_size=imgsz, stride=stride, auto=pt,x_nums=x_nums,y_nums=y_nums,overlap_pix=overlap_pix)
            result = model.inference(img2, img_file,img_threshold_value,pixel_threshold_value,1,overlap_pix)
            result_yolo2=model2.inference(dataset2,model2,device,half,opt.augment,opt.conf_thres,opt.iou_thres, opt.classes, opt.agnostic_nms, opt.max_det,opt.save_crop,names,x_nums,y_nums,overlap_pix)
            result2=result[1]
            list2=result[3]
            resSets = {
                'code': "3",
                "id":str(data["id"]),
                "result2":result2,
                "list2":list2
            }
            return jsonify(resSets)
        else:
            resSets= {
                'code': "1"
            }
            return jsonify(resSets)
    except Exception as e:
        lg.error(e)
 
@app.route('/postparameter', methods=['POST'])
def postparameter():
    try:
        global   img_threshold_value
        global pixel_threshold_value
        if not request.get_data():
            #print("Error: failed to receive parameter")
            resSets= {
                'code': "1"
            }
            return jsonify(resSets)
        para = json.loads(request.get_data())
        "img_threshold" in para
        if ("pixel_threshold" in para) and ("img_threshold" in para):
            pixel_threshold_value = para['pixel_threshold']
            img_threshold_value = para['img_threshold']
            resSets = {
                'code': "0",
                'pixel_threshold':str(pixel_threshold_value),
                'img_threshold':str(img_threshold_value)
            }
            return jsonify(resSets)
        elif ("pixel_threshold" in para):
            para1 = para['pixel_threshold']
            resSets = {
                'code': "2",
                'pixel_threshold':str(pixel_threshold_value)
            }
            return jsonify(resSets)
        elif ("img_threshold" in para):
            img_threshold_value = para['img_threshold']
            resSets = {
                'code': "3",
                'pixel_threshold':str(img_threshold_value)
            }
            return jsonify(resSets)
        else:
            #print("Error: receive no  parameter")
            resSets = {
                'code': "1"
            }
            return jsonify(resSets)
    except Exception as e:
        lg.error(e)

 
 
if __name__=="__main__":

    app.run(host="0.0.0.0", port=8090)
上一篇:jq 实现指定html导出pdf


下一篇:iOS开发之SQLite--C语言接口规范(三)——Binding Values To Prepared Statements