Skip to content

Reclassify and Numpy

  • blog

I have previously written about automatically edge detecting. Using OpenCV is a nice way of quickly running the edge detect and getting some information back about the image. You can read about the Canny edge detection algorithm here

Here is how Wikipedia details the process of the canny edge detection (if you didn’t click the link)

“5 different steps:

  1. Apply Gaussian filter to smooth the image in order to remove the noise
  2. Find the intensity gradients of the image
  3. Apply non-maximum suppression to get rid of spurious response to edge detection
  4. Apply double threshold to determine potential edges
  5. Track edge by hysteresis: Finalize the detection of edges by suppressing all the other edges that are weak and not connected to strong edges.”

Above is a result of an edge detection; notice that the edges are 0 black or 72 white. If I classify the data and apply a colour scale to it some ‘noise’ appears; instead of getting edge or not an edge, I actually get edge and a series of values for not an edge.

image2

In ArcGIS you can solve this using the reclassify function, but you do need the spatial analyst extension. There are also ways in QGIS with toolboxes from Grass or Saga it seems. (it is quite an old question, so I welcome any corrections on a way to do this).

However, I think that reclassifying a raster is a good opportunity to investigate the powerful NumPy arrays in Python. A really good starting point is here.

NumPy

NumPy is ideal if you are working with raster data. Essentially you need to get your data into a NumPy array. Once you have this cracked you can reuse it. Do something to that array (this is your “raster calculator” to borrow a GIS term) and then convert that array back again into a raster (again, once you have this cracked you can repeat this).

Here is the code. You will need gdal as well as NumPy. All this code is doing is reading the raster into an array, using NumPy to reclassify it and then saving the raster out again – see the green comments. In the example below I am setting everything in the raster less than 10, to 0 and everything greater or equal to 10, to 1.

image3

Final result?

image4

Conclusion

This code could be added to the automatic edge detecting

after download and reclassify the image (assuming you know the values you are classifiying). What can I say… give it a go!

Code has been added to edge detection on GitHub