Web+图像目标检测项目—③后端代码逻辑

后端代码逻辑

1.URL->Function

①自带的admin路由不用管
②要在URL上访问文件得用document_root,用正则表达式匹配。
③homepage URL->views.py中的homepage函数,返回页面。
④upload URL->后端处理前端请求的函数,返回数据。

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    re_path(r'media/(?P.*)$', serve, {'document_root': MEDIA_ROOT}),
    url(r'homepage', views.homepage),
    url(r'upload',views.upload),
]

2.views.py

这部分写的有点耦合(烂)了hhh,不过我奉行的是能运行就行(狗头)。

select三个任务的判断,每个分别有自己的运行逻辑,最后返回的数据要弄成Json格式返回。
@csrf_exempt
def upload(request):
    if request.method=='POST':
        file=request.FILES.get("files",None)
        file_select = request.POST.get("select", None)
        if not file:
            return render(request, "index.html")
        elif file_select == "":
            return render(request, "index.html")
        print(file, "  ", file_select)
        if file_select=="2":
            destination = open(os.path.join("/home/ubuntu/webdetect/dcdjango/upload", file.name), 'wb+')
            for chunk in file.chunks():  # 分块写入文件
                destination.write(chunk)
            destination.close()
            imgname=file.name
            img_path="/home/ubuntu/webdetect/dcdjango/upload/"+imgname
            out_put_imgname="/home/ubuntu/webdetect/dcdjango/static/exp/"+imgname
            ins = instanceSegmentation()
            ins.load_model("/home/ubuntu/remote-seg/pointrend_resnet50.pkl",confidence=0.3)
            target_classes = ins.select_target_classes(car = True,airplane=True,bus=True,train=True,truck=True,boat=True)
            result,output=ins.segmentImage(img_path, show_bboxes=True,segment_target_classes=target_classes,output_image_name=out_put_imgname)
            ctx={}
            data={}
            d1=[]
            cls_name_list=[]
            conf_list=[]
            cls_name_list=result["class_names"]
            for i in result["scores"]:
                conf_list.append(i/100)
            print(cls_name_list,conf_list)
            ctx['d1']=d1
            ctx['data']=data
            ss='/image/'
            ctx['imgs']=ss+imgname
            sstr='http://152.136.16.20:8001/static/exp/'+imgname
            print(sstr)
            rt_json={"img_url":sstr,"obj_list":cls_name_list,"conf_list":conf_list}
            return HttpResponse(json.dumps(rt_json), content_type="application/json")
        elif file_select=="0":
            destination = open(os.path.join("/home/ubuntu/webdetect/dcdjango/upload", file.name), 'wb+')
            for chunk in file.chunks():  # 分块写入文件
                destination.write(chunk)
            destination.close()
            imgname=file.name
            str1='python '
            str2='/home/ubuntu/remote-sensing-image-caption/classification/predict.py '
            str3='/home/ubuntu/webdetect/dcdjango/upload/ '
            str4=imgname
            txt_result="/home/ubuntu/webdetect/dcdjango/static/exp/labels/"+imgname[0:-4]+".txt"
            exestr1=str1+str2+str3+str4
            print(exestr1)
            r=os.system(exestr1)
            cp="cp -f /home/ubuntu/webdetect/dcdjango/upload/"+imgname+" /home/ubuntu/webdetect/dcdjango/static/exp/"
            os.system(cp)
            ctx={}
            data={}
            d1=[]
            with open(txt_result,"r") as f:
                for line in f.readlines():
                    cls_name,conf=line.split(' ')[0:2]
            print(cls_name," ",conf)
            cls_name_list=[]
            conf_list=[]
            cls_name_list.append(cls_name)
            conf_list.append(conf)
            print(cls_name_list,conf_list)
            ctx['d1']=d1
            ctx['data']=data
            ss='/image/'
            ctx['imgs']=ss+imgname
            sstr='http://152.136.16.20:8001/static/exp/'+imgname
            print(sstr)
            rt_json={"img_url":sstr,"obj_list":cls_name_list,"conf_list":conf_list}
            return HttpResponse(json.dumps(rt_json), content_type="application/json")
        elif file_select == "1":
            destination = open(os.path.join("/home/ubuntu/webdetect/dcdjango/upload", file.name), 'wb+')  # 打开特定的文件进行二进制的写操作
            # destination = open(os.path.join("C:\\Users\\liusir\\Desktop\\毕设\\论文刻盘\\毕设程序\\webdetect\\dcdjango\\upload", file.name), 'wb+')  # 打开特定的文件进行二进制的写操作
            for chunk in file.chunks():  # 分块写入文件
                destination.write(chunk)
            destination.close()
            imgname=file.name
            filename=imgname[:-4]+".txt"
            txt_path="/home/ubuntu/webdetect/dcdjango/static/exp/labels/"
            open(os.path.join(txt_path,filename), 'w').close()
            str1='python '
            str2 = '/home/ubuntu/yolov5_obb/detect.py ' 
            str4 = ' --project /home/ubuntu/webdetect/dcdjango/static'
            str3='--source /home/ubuntu/webdetect/dcdjango/upload/'+imgname
            str5=' --name exp'
            exestr=str1+str2+str3+str4+str5
            print(exestr)
            r=os.system(exestr)
            ctx={}
            data={}
            d1=[]
            d2=[]
            j=0
            obj_name=[]
            confidence=[]
            print(filename)
            obj_name,confidence=rt_textresult(os.path.join(txt_path,filename))
            print(obj_name,confidence)
            ctx['d1']=d1
            ctx['data']=data
            ss='/image/'
            ctx['imgs']=ss+imgname
            sstr='http://152.136.16.20:8001/static/exp/'+imgname
            print(sstr)
            rt_json={"img_url":sstr,"obj_list":obj_name,"conf_list":confidence}
            return HttpResponse(json.dumps(rt_json), content_type="application/json")
    return HttpResponse(rt_json)

3.处理预测的文本结果

因为预测的结果是txt,最终要通过Json形式返回,所以必须读出来并且以合适的格式方便后续处理。
比如目标检测的结果,我们只需要第一列类别索引和最后一列的confidence置信度,那么就需要进行字符串处理。		

Web+图像目标检测项目—③后端代码逻辑_第1张图片

names = ['plane', 'baseball-diamond', 'bridge', 'ground-track-field', 'small-vehicle', 
        'large-vehicle', 'ship', 'tennis-court', 'basketball-court', 'storage-tank',  
        'soccer-ball-field', 'roundabout', 'harbor', 'swimming-pool', 'helicopter', 
        'container-crane']  # class names
def homepage(request):  #URL中homepage返回页面
    return render(request,'index.html')
def rt_textresult(file_name):    #处理预测的文本结果
    obj_name=[]
    confidence=[]
    with open(file_name,"r") as f:
        for line in f.readlines():
            r0,r1,r2,r3,r4,r5,r6,r7,r8,r9=line.split(' ')[0:10]
            r0=int(r0)
            if r0<=15:
                name=names[r0]
                r9=r9[:-1]
                obj_name.append(name)
                confidence.append(r9)
    return obj_name,confidence
查看交互的数据

Web+图像目标检测项目—③后端代码逻辑_第2张图片
Web+图像目标检测项目—③后端代码逻辑_第3张图片

你可能感兴趣的:(Web+遥感图像智能解义,后端,python,深度学习,web)