django后端tif文件接收/切割/检测

本文介绍了如何在Django后端处理TIFF(TIF)图像,包括接收上传的TIF文件,进行图像切割操作,并执行图像检测。通过Python的图像处理库,详细阐述了实现这一流程的关键步骤和技术细节。
摘要由CSDN通过智能技术生成
import os
import json
import time
from django.conf import settings
from osgeo import gdal

# Create your views here.
from django.http import JsonResponse, response, HttpResponse, StreamingHttpResponse


def tifWA(request):
    result = []
    if request.method == 'POST':
        print("函数已触发")
        # 1、接收tif图片
        tif = request.FILES.get('file')  # 至于为什么这里的接收名称位file,我忘了。。。。
        print(tif)
        base_dir = settings.BASE_DIR  # 当前的最高级目录(dvadmin-backend)
        timestrap = str(time.time())
        upload_dir = os.path.join(base_dir, 'media', 'Tifs')  # 在主目录下新建文件夹
        print(upload_dir)

        path = os.path.join(upload_dir, tif.name)  # 把前端传过来的图片保存在新建的upload文件夹中
        print(path)
        with open(path, 'wb+') as f:
            for chunk in tif.chunks():
                f.write(chunk)
        # 2、切割tif图片
        tifPath = gdal.Open(path)
        CutTif(tifPath,timestrap)  # 把保存的tif文件的路径和时间戳(存放切割后的图片)传给切割函数
        print('切割完毕')
        # 3、检测
        path = os.path.join(base_dir, 'media', 'CutAfter', timestrap)  # 切割之后的图片存放地址
        tiftest(path,timestrap)
        # 4、返回结果
    return JsonResponse(result)


# ----切割函数----
from PIL import Image

def CutTif(in_ds,timestrap):
    # 读取原图中的每个波段,通道数从1开始,默认前三波段
    in_band1 = in_ds.GetRasterBand(1)
    in_band2 = in_ds.GetRasterBand(2)
    in_band3 = in_ds.GetRasterBand(3)

    # 获取原图的原点坐标信息
    ori_transform = in_ds.GetGeoTransform()
    top_left_x = ori_transform[0]  # 左上角x坐标
    top_left_y = ori_transform[3]  # 左上角y坐标
    w_e_pixel_resolution = ori_transform[1]  # 东西方向像素分辨率
    n_s_pixel_resolution = ori_transform[5]  # 南北方向像素分辨率

    # ##############################裁切信息设置###################################
    # ##定义切图的起始点像素位置
    offset_x = 0
    offset_y = 0
    # ##定义切图的大小(矩形框)
    block_xsize = 600  # 行
    block_ysize = 600  # 列
    count = 0
    # ##是否需要最后不足补充,进行反向裁切(裁切数量)
    im_width = in_ds.RasterXSize  # 栅格矩阵的列数
    im_height = in_ds.RasterYSize  # 栅格矩阵的行数
    num_width = int(im_width / block_ysize)
    num_height = int(im_height / block_xsize)
    if True:
        if im_width % block_ysize == 0:  # 判断是否能完整裁切
            num_width = num_width
            wb = False
        else:
            num_width += 1
            wb = True
        if im_height % block_xsize == 0:
            num_height = num_height
            hb = False
        else:
            num_height += 1
            hb = True

    # ##图像重叠区设置(暂时不考虑)####开始裁切#########
    for i in range(num_width):
        offset_x1 = offset_x + block_xsize * i
        if hb and i == num_width - 1:
            offset_x1 = im_width - block_xsize
        for j in range(num_height):
            count = count + 1

            offset_y1 = offset_y + block_ysize * j
            if wb and j == num_height - 1:
                offset_y1 = im_height - block_ysize
            out_band1 = in_band1.ReadAsArray(offset_x1, offset_y1, block_xsize, block_ysize)
            out_band2 = in_band2.ReadAsArray(offset_x1, offset_y1, block_xsize, block_ysize)
            out_band3 = in_band3.ReadAsArray(offset_x1, offset_y1, block_xsize, block_ysize)

            gtif_driver = gdal.GetDriverByName("GTiff")  # 数据类型必须有,因为要计算需要多大内存空间,但是这儿是只有GTiff吗?
            # 先创建文件夹
            base_dir = settings.BASE_DIR  # 当前的最高级目录(dvadmin-backend)
            path = os.path.join(base_dir, 'media', 'CutAfter',timestrap)   # 切割之后的图片存放地址
            if not os.path.exists(path):
                os.makedirs(path)
            # path = 'E:\吕大娟\数据集\乌兰察布市\wlcb\wlcb2020'   # 这个也让函数传入
            filename = 'image' + str(count) + '.png'  # 文件名称
            allpath = path + '\\' + filename
            out_ds = gtif_driver.Create(allpath, block_xsize, block_ysize, 3, in_band1.DataType)

            print("create new tif file succeed")

            top_left_x1 = top_left_x + offset_x1 * w_e_pixel_resolution
            top_left_y1 = top_left_y + offset_y1 * n_s_pixel_resolution

            dst_transform = (
            top_left_x1, ori_transform[1], ori_transform[2], top_left_y1, ori_transform[4], ori_transform[5])
            out_ds.SetGeoTransform(dst_transform)

            # 设置SRS属性(投影信息)
            out_ds.SetProjection(in_ds.GetProjection())

            # 写入目标文件(如果波段数有更改,这儿也需要修改)
            out_ds.GetRasterBand(1).WriteArray(out_band1)
            out_ds.GetRasterBand(2).WriteArray(out_band2)
            out_ds.GetRasterBand(3).WriteArray(out_band3)

            # 将缓存写入磁盘,直接保存到了程序所在的文件夹
            out_ds.FlushCache()
            print(f"FlushCache succeed{count}")
            del out_ds


# 检测函数
import argparse
from detect import main, parse_opt

def tiftest(path,exp):
    print('检测函数被触发')
    # a = myModle()
    # a.forward()
    # result = {}
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str,
                        default=r'D:\Desktop\windmillSystem\dvadmin-backend\runs\train\1663417314.2989476\weights\best.pt', help='model.pt path(s)')
    # parser.add_argument('--source', type=str, default='windmill/images/test', help='file/dir/URL/glob, 0 for webcam')
    parser.add_argument('--source', type=str, default=path, help='file/dir/URL/glob, 0 for webcam')
    parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
    parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
    parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    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: --class 0, or --class 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='media/DetectAfter', 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')

    opt = parser.parse_args(args=[])    # 这个参数不能拿少!!!!
    print(opt)
    time_cost = main(opt)
    return time_cost


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值