Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/continuous-integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ jobs:

steps:
- uses: actions/checkout@main
- name: Set up headless display for napari (Qt needs a real X server + GL, not the offscreen plugin)
uses: pyvista/setup-headless-display-action@v3
with:
qt: true
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@main
with:
Expand Down
77 changes: 77 additions & 0 deletions docs/InteractiveGeoreferencer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
## class InteractiveGeoreferencer

A PlantCV-Geospatial data object class.

*class* **plantcv.geospatial.georeference.InteractiveGeoreferencer**(*img_dir, output_dir, mode="known_coordinates", known_coords=None, reference_image=None, transform_type="affine", interpolation_order=1, show=True*)

- **Parameters:**
- img_dir - Path to a directory containing geotifs to be georeferenced.
- output_dir - Path to a directory for writing georeferenced files to. Parent directories will be created if they do not already exist.
- mode - Specifies whether to georeference using ground control points (GCPs) with known geographical coordinates ("known_coordinates" mode) or using a reference image to match GCP location to ("reference_image" mode).
- known_coords - List of (float, float) pairs with latitude and longitude of GCPs. Only used if mode="known_coordinates". Must be in the same coordinate reference system as the input geotifs to georeference.
- reference_image - Path to the location of the geotif to be used as a reference (to match all other geotifs to). Can be located within "img_dir." Only used when mode="reference_image."
- transform_type - Type of warp used for georeferencing. See details below. Defaults to "affine."
- interpolation_order - Pixel resampling interpolation degree used when warping (0=nearest neighbor, 1=bilinear, 3=bicubic). Default is 1.
- show - Whether or not to show the napari window. Useful for testing, defaults to True.

`InteractiveGeoreferencer` is a class that is used to interactively find and select ground control points in a set of images so that georeferencing can be done automatically and in one step. When initiated (see below for examples), a napari viewer window opens with either a reference image or the first image in `img_dir`. Instructions on the side bar will tell a user how many images there are in the queue and how many GCPs need to be clicked for the selected transformation method. After clicking all GCPs for the first image, a user will click the "Next Image" button to proceed through the queue until all images have had GCPs identified.

### Attributes

* **viewer**: An interactive viewer object.

* **gcps**: Dictionary of GCP click positions per image.

### Methods

* **georeference**: (): Perform georeferencing and save new geotifs to `output_dir`.

* **close**: (): Close the viewer object window.

### Transform type options
The method of warping to fit clicked to known coordinate positions, specified by `transform_type`, has the following options:

| Option | What it does | Min. points | QGIS analog | Key difference from QGIS |
|---|---|---|---|---|
| `"affine"` | A single global 6-parameter transform (translation, rotation, scale, shear). Straight lines stay straight and parallel lines stay parallel everywhere in the image. | 3 | **Linear** | None — same 6-parameter model. (QGIS's separate **Helmert** option, a more restrictive 4-parameter similarity transform, isn't offered.) |
| `"polynomial2"` | A 2nd-order polynomial warp. Allows the image to bend/curve, correcting mild non-linear distortion that a single global affine can't. | 6 | **Polynomial 2** | None. |
| `"polynomial3"` | A 3rd-order polynomial warp. More locally flexible than `"polynomial2"`, at the cost of needing more, well-spread points to stay numerically stable. | 10 | **Polynomial 3** | None. Orders beyond 3 aren't offered — they need disproportionately more points for a fit that isn't obviously better, and become numerically unstable well before reaching them. |
| `"tps"` | A locally flexible warp: the image is triangulated between control points and each triangle gets its own small affine transform, so it bends independently near each point instead of applying one global rule. | 4 | **Thin Plate Spline (TPS)** | **This is not a true TPS.** `scikit-image` has no thin-plate-spline implementation, so this is approximated with a piecewise-affine (Delaunay-triangulated) warp instead. It shares TPS's local flexibility and exactness at control points, but produces subtle creases at triangle edges rather than one smooth bending surface. |
| `"projective"` | A perspective/homography warp (8 parameters). Straight lines stay straight, but parallel lines can converge — the right choice for true perspective distortion, like a photo taken at an angle to the ground. | 4 | **Projective** | None. |


### Examples

```python
import plantcv.geospatial as gcv
import plantcv.plantcv as pcv


# Read in an image
img = gcv.read.geotif("./grid_field.tif", bands="B,G,R,RE,N")

# Initialize an InteractiveGeoreferencer class object
viewer = gcv.georeference.InteractiveGeoreferencer(img_dir="./cropped/",
output_dir="./georef/",
mode="reference_image",
transform_type="projective",
reference_image="./cropped/earliest_timepoint.tif")

# Follow the instructions on the right side of the viewer
# You will click GCPs on each image in the folder and then click "Next Image"

```

```python
# In a new cell, run the georeferencer
# Note - this step can take quite awhile, especially if you have many images
viewer.georeference()

```

**Clicking GCPs in the second of three images:**

![Screenshot](documentation_images/GCP_click.png)


**Source Code:** [Here](https://github.com/danforthcenter/plantcv-geospatial/blob/main/plantcv/geospatial/georeference/interactive_georeferencer.py)
16 changes: 16 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,18 @@ All notable changes to this project will be documented below.

* v0.1dev: object = **geospatial.GEO**(*input_array, filename, wavelengths, default_wavelengths, crs, transform*)

#### geospatial.georeference.InteractiveGeoreferencer

* v0.1dev: viewer = **geospatial.create_shapes.InteractiveGeoreferencer**(*img_dir, output_dir, mode="known_coordinates", known_coords=None, reference_image=None, transform_type="affine", interpolation_order=1, show=True*)

#### geospatial.georeference.InteractiveGeoreferencer.georeference

* v0.1dev: **geospatial.create_shapes.InteractiveGeoreferencer.georeference**()

#### geospatial.georeference.InteractiveGeoreferencer.close

* v0.1dev: **geospatial.create_shapes.InteractiveGeoreferencer.close**()

#### geospatial.Image

* v0.1dev: object = **geospatial.Image**(*input_array, filename*)
Expand All @@ -101,3 +113,7 @@ All notable changes to this project will be documented below.
#### geospatial.subtract_dsm

* v0.1dev: chm = **geospatial.subtract_dsm**(*dsm1, dsm0*)

#### geospatial.write_geotif

* v0.1dev: **geospatial.write_geotif**(*path, img, transform=None, crs=None, nodata=None*)
Binary file added docs/documentation_images/GCP_click.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
30 changes: 30 additions & 0 deletions docs/write_geotif.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
## Save GeoTIFF data

Save out a new or modified data array to a GeoTIFF file.

**geospatial.write_geotif**(*path, img, transform=None, crs=None, nodata=None*)

- **Parameters:**
- path - Path and filename for saving the new GeoTIFF.
- img - Either a numpy array, [GEO or DSM](image_classes.md) object containing data to be saved.
- transform - Affine transformation matrix that converts array coordinates to geospatial coordinates.
- crs - Coordinate reference system.
- nodata - No data value.

- **Context:**
- This function is useful for saving modified geospatial objects as new files after [resizing](resize.md) or georeferencing.

- **Example use:**

```python
import plantcv.geospatial as gcv

# Read geotif in
ortho = gcv.read.geotif(filename="./data/example_img.tif", bands="B,G,R,RE,NIR")
resized = gcv.resize(img=ortho, size=(2000, 2000))
gcv.write_geotif(path="./outputs/resized_img.tif", img=resized)


```

**Source Code:** [Here](https://github.com/danforthcenter/plantcv-geospatial/blob/main/plantcv/geospatial/write_geotif.py)
2 changes: 2 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@ nav:
- Convert points to/from geojson: convert_points.md
- Convert polygons to/from geojson: convert_shapes.md
- Field Layout: Field_layout.md
- Georeference Orthomosaics: InteractiveGeoreferencer.md
- ROIs from polygon centers: center_grid_rois.md
- Shape creation tools:
- Grid from plot coordinates : shapes_grid_from_coords.md
- Automatic Grid : shapes_grid.md
- Interactive shape creation: InteractiveShapes.md
- Subtract DSMs to create a canopy height model: subtract_dsm.md
- Save a GeoTIFF to a new file: write_geotif.md
markdown_extensions:
- toc:
permalink: True
Expand Down
6 changes: 5 additions & 1 deletion plantcv/geospatial/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
from plantcv.geospatial import convert
from plantcv.geospatial import analyze
from plantcv.geospatial import create_shapes
from plantcv.geospatial import georeference
from plantcv.geospatial.center_grid_rois import center_grid_rois
from plantcv.geospatial.images import Image, GEO, DSM
from plantcv.geospatial.resize import resize
from plantcv.geospatial.subtract_dsm import subtract_dsm
from plantcv.geospatial.write_geotif import write_geotif

# Auto versioning
__version__ = version("plantcv-geospatial")
Expand All @@ -20,11 +22,13 @@
"read",
"analyze",
"create_shapes",
"georeference",
"center_grid_rois",
"convert",
"Image",
"GEO",
"DSM",
"resize",
"subtract_dsm"
"subtract_dsm",
"write_geotif"
]
30 changes: 30 additions & 0 deletions plantcv/geospatial/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import fiona
import cv2
import os
import rasterio


def _histogram_stats(masked_array, bins, histrange):
Expand Down Expand Up @@ -353,3 +354,32 @@ def _check_field_parameters(arglist, argnames):
areNone = [val is None for val in arglist]
noneArgs = [val for i, val in enumerate(argnames) if areNone[i]]
fatal_error("Got None for " + str(noneArgs) + ", specify as a kwarg or add to field_layout object")


def _read_raster(path):
"""
Helper function to read a raster file's data

Parameters:
-----------
path : str
Path to a raster file readable by rasterio

Returns:
--------
array : numpy.ndarray
Array data.
crs : rasterio.crs.CRS or None
Coordinate reference system.
transform : affine.Affine
Existing geotransform.
nodata : float or None
Nodata value from the file's metadata.
"""
with rasterio.open(path) as src:
array = src.read()
crs = src.crs
transform = src.transform
nodata = src.nodata
array = np.moveaxis(array, 0, -1)
return array, crs, transform, nodata
3 changes: 3 additions & 0 deletions plantcv/geospatial/georeference/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from plantcv.geospatial.georeference.interactive_georeferencer import InteractiveGeoreferencer

__all__ = ["InteractiveGeoreferencer"]
Loading
Loading