| 7 | from django.utils.translation import gettext_lazy as _ |
| 8 | |
| 9 | def detect(orthophoto, model, classes=None, crop=None, progress_callback=None): |
| 10 | import os |
| 11 | import subprocess |
| 12 | import shutil |
| 13 | import tempfile |
| 14 | from webodm import settings |
| 15 | from django.contrib.gis.geos import GEOSGeometry |
| 16 | |
| 17 | try: |
| 18 | from geodeep import detect as gdetect, models |
| 19 | models.cache_dir = os.path.join(settings.MEDIA_CACHE, "detection_models") |
| 20 | except ImportError: |
| 21 | return {'error': "GeoDeep library is missing"} |
| 22 | |
| 23 | try: |
| 24 | if crop is not None: |
| 25 | # Make a VRT with the crop area |
| 26 | |
| 27 | gdalwarp_bin = shutil.which("gdalwarp") |
| 28 | if gdalwarp_bin is None: |
| 29 | return {'error': 'Cannot find gdalwarp'} |
| 30 | |
| 31 | tmpdir = os.path.join(settings.MEDIA_TMP, os.path.basename(tempfile.mkdtemp('_objdetect', dir=settings.MEDIA_TMP))) |
| 32 | |
| 33 | crop_geojson = os.path.join(tmpdir, "crop.geojson") |
| 34 | ortho_vrt = os.path.join(tmpdir, "orthophoto.vrt") |
| 35 | with open(crop_geojson, "w", encoding="utf-8") as f: |
| 36 | f.write(GEOSGeometry(crop).geojson) |
| 37 | p = subprocess.Popen([gdalwarp_bin, "-cutline", crop_geojson, |
| 38 | '--config', 'GDALWARP_DENSIFY_CUTLINE', 'NO', |
| 39 | '-crop_to_cutline', '-of', 'VRT', |
| 40 | orthophoto, ortho_vrt], cwd=tmpdir, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 41 | out, err = p.communicate() |
| 42 | out = out.decode('utf-8').strip() |
| 43 | err = err.decode('utf-8').strip() |
| 44 | if p.returncode != 0: |
| 45 | return {'error': f'Error calling gdalwarp: {str(err)}'} |
| 46 | |
| 47 | orthophoto = ortho_vrt |
| 48 | |
| 49 | return {'output': gdetect(orthophoto, model, output_type='geojson', classes=classes, max_threads=settings.WORKERS_MAX_THREADS, progress_callback=progress_callback)} |
| 50 | except Exception as e: |
| 51 | return {'error': str(e)} |
| 52 | |
| 53 | class TaskObjDetect(TaskView): |
| 54 | def post(self, request, pk=None): |