diff --git a/Batch Processing-Altum.ipynb b/Batch Processing-Altum.ipynb new file mode 100644 index 00000000..122d4fee --- /dev/null +++ b/Batch Processing-Altum.ipynb @@ -0,0 +1,433 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Batch Processing Example\n", + "\n", + "In this example, we use the `micasense.imageset` class to load a set of directories of images into a list of `micasense.capture` objects, and we iterate over that list saving out each image as an aligned stack of images as separate bands in a single tiff file each. Next, we use the metadata from the original captures to write out a log file of the captures and their locations. Finally, we use `exiftool` from the command line to inject that metadata into the processed images, allowing us to stitch those images using commercial software such as Pix4D or Agisoft.\n", + "\n", + "Note: for this example to work, the images must have a valid RigRelatives tag. This requires RedEdge version of at least 3.4.0 or any version of Altum. If your images don't meet that spec, you can also follow this support ticket to add the RigRelatives tag to them: https://support.micasense.com/hc/en-us/articles/360006368574-Modifying-older-collections-for-Pix4Dfields-support" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%load_ext autoreload\n", + "%autoreload 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Load Images into ImageSet" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from ipywidgets import FloatProgress, Layout\n", + "from IPython.display import display\n", + "import micasense.imageset as imageset\n", + "import micasense.capture as capture\n", + "import os, glob\n", + "import multiprocessing\n", + "\n", + "panelNames = None\n", + "useDLS = True\n", + "\n", + "# imagePath = os.path.expanduser(os.path.join('~', 'Downloads', 'AltumSampleImages'))\n", + "imagePath = os.path.join('E:\\\\AutomodalityDS\\\\Photogrammetry', 'Multispectral\\\\MicaSense_Altum_example', '0000SET_Processed\\\\RAW')\n", + "print('Image Path:', imagePath)\n", + "panelNames = glob.glob(os.path.join(imagePath, 'IMG_0000_*.tif'))\n", + "panelCap = capture.Capture.from_filelist(panelNames)\n", + "\n", + "outputPath = os.path.join(imagePath, '..', 'Stacks')\n", + "thumbnailPath = os.path.join(outputPath, '..', 'Thumbnails')\n", + "\n", + "overwrite = True # can be set to set to False to continue interrupted processing\n", + "generateThumbnails = True\n", + "\n", + "# Allow this code to align both radiance and reflectance images; bu excluding\n", + "# a definition for panelNames above, radiance images will be used\n", + "# For panel images, efforts will be made to automatically extract the panel information\n", + "# but if the panel/firmware is before Altum 1.3.5, RedEdge 5.1.7 the panel reflectance\n", + "# will need to be set in the panel_reflectance_by_band variable.\n", + "# Note: radiance images will not be used to properly create NDVI/NDRE images below.\n", + "if panelNames is not None:\n", + " panelCap = capture.Capture.from_filelist(panelNames)\n", + "else:\n", + " panelCap = None\n", + "\n", + "if panelCap is not None:\n", + " if panelCap.panel_albedo() is not None and not any(v is None for v in panelCap.panel_albedo()):\n", + " panel_reflectance_by_band = panelCap.panel_albedo()\n", + " else:\n", + " #panel_reflectance_by_band = [0.67, 0.69, 0.68, 0.61, 0.67] #RedEdge band_index order\n", + " panel_reflectance_by_band = [0.491, 0.49, 0.488, 0.488, 0.486] #Altum band_index order\n", + " \n", + " panel_irradiance = panelCap.panel_irradiance(panel_reflectance_by_band) \n", + " img_type = \"reflectance\"\n", + "else:\n", + " if useDLS:\n", + " img_type='reflectance'\n", + " else:\n", + " img_type = \"radiance\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "## This progress widget is used for display of the long-running process\n", + "f = FloatProgress(min=0, max=1, layout=Layout(width='100%'), description=\"Loading\")\n", + "display(f)\n", + "def update_f(val):\n", + " if (val - f.value) > 0.005 or val == 1: #reduces cpu usage from updating the progressbar by 10x\n", + " f.value=val\n", + "\n", + "%time imgset = imageset.ImageSet.from_directory(imagePath, progress_callback=update_f)\n", + "update_f(1.0)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "scrolled": false + }, + "outputs": [], + "source": [ + "import math\n", + "import numpy as np\n", + "from mapboxgl.viz import *\n", + "from mapboxgl.utils import df_to_geojson, create_radius_stops, scale_between\n", + "from mapboxgl.utils import create_color_stops\n", + "import pandas as pd\n", + "\n", + "data, columns = imgset.as_nested_lists()\n", + "df = pd.DataFrame.from_records(data, index='timestamp', columns=columns)\n", + "\n", + "#Insert your mapbox token here\n", + "token = 'pk.eyJ1IjoibWljYXNlbnNlIiwiYSI6ImNqYWx5dWNteTJ3cWYzMnBicmZid3g2YzcifQ.Zrq9t7GYocBtBzYyT3P4sw'\n", + "color_property = 'dls-yaw'\n", + "num_color_classes = 8\n", + "\n", + "min_val = df[color_property].min()\n", + "max_val = df[color_property].max()\n", + "\n", + "import jenkspy\n", + "breaks = jenkspy.jenks_breaks(df[color_property], nb_class=num_color_classes)\n", + "\n", + "color_stops = create_color_stops(breaks,colors='YlOrRd')\n", + "geojson_data = df_to_geojson(df,columns[3:],lat='latitude',lon='longitude')\n", + "\n", + "viz = CircleViz(geojson_data, access_token=token, color_property=color_property,\n", + " color_stops=color_stops,\n", + " center=[df['longitude'].median(),df['latitude'].median()], \n", + " zoom=16, height='600px',\n", + " style='mapbox://styles/mapbox/satellite-streets-v9')\n", + "viz.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Define which warp method to use\n", + "For newer data sets with RigRelatives tags (images captured with RedEdge version 3.4.0 or greater with a valid calibration load, see https://support.micasense.com/hc/en-us/articles/360005428953-Updating-RedEdge-for-Pix4Dfields), we can use the RigRelatives for a simple alignment.\n", + "\n", + "For sets without those tags, or sets that require a RigRelatives optimization, we can go through the Alignment.ipynb notebook and get a set of `warp_matrices` that we can use here to align." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from numpy import array\n", + "from numpy import float32\n", + "\n", + "# Set warp_matrices to none to align using RigRelatives\n", + "# Or\n", + "# Use the warp_matrices derived from the Alignment Tutorial for this RedEdge set without RigRelatives\n", + "#warp_matrices = [array([[ 1.0022864e+00, -2.5218755e-03, -7.8898020e+00],\n", + "# [ 2.3614739e-03, 1.0036649e+00, -1.3134377e+01],\n", + "# [-1.7785899e-06, 1.1343118e-06, 1.0000000e+00]], dtype=float32), array([[1., 0., 0.],\n", + "# [0., 1., 0.],\n", + "# [0., 0., 1.]], dtype=float32), array([[ 9.9724638e-01, -1.5535230e-03, 1.2301294e+00],\n", + "# [ 8.6745428e-04, 9.9738181e-01, -1.6499169e+00],\n", + "# [-8.2816513e-07, -3.4488804e-07, 1.0000000e+00]], dtype=float32), array([[ 1.0007139e+00, -8.4427800e-03, 1.6312805e+01],\n", + "# [ 6.2834378e-03, 9.9977130e-01, -1.6011697e+00],\n", + "# [-1.9520389e-06, -6.3762940e-07, 1.0000000e+00]], dtype=float32), array([[ 9.9284178e-01, 9.2155562e-04, 1.6069822e+01],\n", + "# [-3.2895457e-03, 9.9262553e-01, -5.0333548e-01],\n", + "# [-1.5845577e-06, -1.7680986e-06, 1.0000000e+00]], dtype=float32)]\n", + "warp_matrices = None" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Align images and save each capture to a layered tiff file" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import exiftool\n", + "import datetime\n", + "## This progress widget is used for display of the long-running process\n", + "f2 = FloatProgress(min=0, max=1, layout=Layout(width='100%'), description=\"Saving\")\n", + "display(f2)\n", + "def update_f2(val):\n", + " f2.value=val\n", + "\n", + "if not os.path.exists(outputPath):\n", + " os.makedirs(outputPath)\n", + "if generateThumbnails and not os.path.exists(thumbnailPath):\n", + " os.makedirs(thumbnailPath)\n", + "\n", + "# Save out geojson data so we can open the image capture locations in our GIS\n", + "with open(os.path.join(outputPath,'imageSet.json'),'w') as f:\n", + " f.write(str(geojson_data))\n", + " \n", + "try:\n", + " irradiance = panel_irradiance+[0]\n", + "except NameError:\n", + " irradiance = None\n", + "\n", + "start = datetime.datetime.now()\n", + "for i,capture in enumerate(imgset.captures):\n", + " outputFilename = capture.uuid+'.tif'\n", + " thumbnailFilename = capture.uuid+'.jpg'\n", + " fullOutputPath = os.path.join(outputPath, outputFilename)\n", + " fullThumbnailPath= os.path.join(thumbnailPath, thumbnailFilename)\n", + " if (not os.path.exists(fullOutputPath)) or overwrite:\n", + " if(len(capture.images) == len(imgset.captures[0].images)):\n", + " capture.create_aligned_capture(irradiance_list=irradiance, warp_matrices=warp_matrices)\n", + " capture.save_capture_as_stack(fullOutputPath)\n", + " if generateThumbnails:\n", + " capture.save_capture_as_rgb(fullThumbnailPath)\n", + " capture.clear_image_data()\n", + " update_f2(float(i)/float(len(imgset.captures)))\n", + "update_f2(1.0)\n", + "end = datetime.datetime.now()\n", + "\n", + "print(\"Saving time: {}\".format(end-start))\n", + "print(\"Alignment+Saving rate: {:.2f} images per second\".format(float(len(imgset.captures))/float((end-start).total_seconds())))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Extract Metadata from Captures list and save to log.csv" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def decdeg2dms(dd):\n", + " is_positive = dd >= 0\n", + " dd = abs(dd)\n", + " minutes,seconds = divmod(dd*3600,60)\n", + " degrees,minutes = divmod(minutes,60)\n", + " degrees = degrees if is_positive else -degrees\n", + " return (degrees,minutes,seconds)\n", + "\n", + "header = \"SourceFile,\\\n", + "GPSDateStamp,GPSTimeStamp,\\\n", + "GPSLatitude,GpsLatitudeRef,\\\n", + "GPSLongitude,GPSLongitudeRef,\\\n", + "GPSAltitude,GPSAltitudeRef,\\\n", + "FocalLength,\\\n", + "XResolution,YResolution,ResolutionUnits\\n\"\n", + "\n", + "lines = [header]\n", + "for capture in imgset.captures:\n", + " #get lat,lon,alt,time\n", + " outputFilename = capture.uuid+'.tif'\n", + " fullOutputPath = os.path.join(outputPath, outputFilename)\n", + " lat,lon,alt = capture.location()\n", + " #write to csv in format:\n", + " # IMG_0199_1.tif,\"33 deg 32' 9.73\"\" N\",\"111 deg 51' 1.41\"\" W\",526 m Above Sea Level\n", + " latdeg, latmin, latsec = decdeg2dms(lat)\n", + " londeg, lonmin, lonsec = decdeg2dms(lon)\n", + " latdir = 'North'\n", + " if latdeg < 0:\n", + " latdeg = -latdeg\n", + " latdir = 'South'\n", + " londir = 'East'\n", + " if londeg < 0:\n", + " londeg = -londeg\n", + " londir = 'West'\n", + " resolution = capture.images[0].focal_plane_resolution_px_per_mm\n", + "\n", + " linestr = '\"{}\",'.format(fullOutputPath)\n", + " linestr += capture.utc_time().strftime(\"%Y:%m:%d,%H:%M:%S,\")\n", + " linestr += '\"{:d} deg {:d}\\' {:.2f}\"\" {}\",{},'.format(int(latdeg),int(latmin),latsec,latdir[0],latdir)\n", + " linestr += '\"{:d} deg {:d}\\' {:.2f}\"\" {}\",{},{:.1f} m Above Sea Level,Above Sea Level,'.format(int(londeg),int(lonmin),lonsec,londir[0],londir,alt)\n", + " linestr += '{}'.format(capture.images[0].focal_length)\n", + " linestr += '{},{},mm'.format(resolution,resolution)\n", + " linestr += '\\n' # when writing in text mode, the write command will convert to os.linesep\n", + " lines.append(linestr)\n", + "\n", + "fullCsvPath = os.path.join(outputPath,'_tif_exif_log.csv')\n", + "with open(fullCsvPath, 'w') as csvfile: #create CSV\n", + " csvfile.writelines(lines)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Use Exiftool from the command line to write metadata to images" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import subprocess\n", + "\n", + "if os.environ.get('exiftoolpath') is not None:\n", + " exiftool_cmd = os.path.normpath(os.environ.get('exiftoolpath'))\n", + "else:\n", + " exiftool_cmd = 'exiftool'\n", + " \n", + "cmd = '{} -csv=\"{}\" -overwrite_original {}'.format(exiftool_cmd, fullCsvPath, outputPath)\n", + "print(cmd)\n", + "subprocess.check_call(cmd)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Wirte EXIF metadata to RGB images" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def decdeg2dms(dd):\n", + " is_positive = dd >= 0\n", + " dd = abs(dd)\n", + " minutes,seconds = divmod(dd*3600,60)\n", + " degrees,minutes = divmod(minutes,60)\n", + " degrees = degrees if is_positive else -degrees\n", + " return (degrees,minutes,seconds)\n", + "\n", + "header = \"SourceFile,\\\n", + "GPSDateStamp,GPSTimeStamp,\\\n", + "GPSLatitude,GpsLatitudeRef,\\\n", + "GPSLongitude,GPSLongitudeRef,\\\n", + "GPSAltitude,GPSAltitudeRef,\\\n", + "FocalLength,\\\n", + "XResolution,YResolution,ResolutionUnits\\n\"\n", + "\n", + "lines = [header]\n", + "for capture in imgset.captures:\n", + " #get lat,lon,alt,time\n", + " outputFilename = capture.uuid+'.jpg'\n", + " fullOutputPath = os.path.join(thumbnailPath, outputFilename)\n", + " lat,lon,alt = capture.location()\n", + " #write to csv in format:\n", + " # IMG_0199_1.tif,\"33 deg 32' 9.73\"\" N\",\"111 deg 51' 1.41\"\" W\",526 m Above Sea Level\n", + " latdeg, latmin, latsec = decdeg2dms(lat)\n", + " londeg, lonmin, lonsec = decdeg2dms(lon)\n", + " latdir = 'North'\n", + " if latdeg < 0:\n", + " latdeg = -latdeg\n", + " latdir = 'South'\n", + " londir = 'East'\n", + " if londeg < 0:\n", + " londeg = -londeg\n", + " londir = 'West'\n", + " resolution = capture.images[0].focal_plane_resolution_px_per_mm\n", + "\n", + " linestr = '\"{}\",'.format(fullOutputPath)\n", + " linestr += capture.utc_time().strftime(\"%Y:%m:%d,%H:%M:%S,\")\n", + " linestr += '\"{:d} deg {:d}\\' {:.2f}\"\" {}\",{},'.format(int(latdeg),int(latmin),latsec,latdir[0],latdir)\n", + " linestr += '\"{:d} deg {:d}\\' {:.2f}\"\" {}\",{},{:.1f} m Above Sea Level,Above Sea Level,'.format(int(londeg),int(lonmin),lonsec,londir[0],londir,alt)\n", + " linestr += '{}'.format(capture.images[0].focal_length)\n", + " linestr += '{},{},mm'.format(resolution,resolution)\n", + " linestr += '\\n' # when writing in text mode, the write command will convert to os.linesep\n", + " lines.append(linestr)\n", + "\n", + "fullCsvPath = os.path.join(thumbnailPath,'_jpg_exif_log.csv')\n", + "with open(fullCsvPath, 'w') as csvfile: #create CSV\n", + " csvfile.writelines(lines)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import subprocess\n", + "\n", + "if os.environ.get('exiftoolpath') is not None:\n", + " exiftool_cmd = os.path.normpath(os.environ.get('exiftoolpath'))\n", + "else:\n", + " exiftool_cmd = 'exiftool'\n", + " \n", + "cmd = '{} -csv=\"{}\" -overwrite_original {}'.format(exiftool_cmd, fullCsvPath, thumbnailPath)\n", + "print(cmd)\n", + "subprocess.check_call(cmd)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.10" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +}