Skip to content
Advertisement

Python count amount of cells forming a line with random shape in an array

  1. Context: I work with satellite images that I filter to transform to arrays of 1s and 0s, based on the presence of snow (0 for snow, 1 for non-snow). My code creates an array of NaNs, searches for each snow pixel if at least one of the neighbor is non-snow (in a cross patter, cells painted red in the picture below), and inputs “1” in the nan array. Once I do that for my entire matrix I end up with lines where a line cell = 1, rest are nans. enter image description here
  2. Problem: I end up with a matrix with several lines inside. What I count as a line is at least two cell equal to 1, in the direct neighborhoods. Meaning that for each line cell, if any of the 8 surrounding cells has a 1 inside, they are forming a line (figure below shows the boundary between snow (purple) and non-snow cells (yellow). enter image description here
  3. What I have: I wrote an algorithm that counts the amount of cells in a line and records its starting/ending cells (see figure below, amount of cells through which the red line passes) so I can filter my lines by size at the end. enter image description here
  4. What I want: my code works but is extremely slow. I coded it the best way I could but O was wondering if there was a way to be more efficient ?

Ps: Sorry about the clanky explanation, it is hard for me to explain clearly. The code will show you how it works, and the figures generated should make it clearer.

Some code to generate a “lines” matrix:

JavaScript

Advertisement

Answer

There’s an idea in image processing, which is find to a group of pixels which is contiguous, or a connected component. Once you break the image up into connected components, you can find the size of each component, and filter out small ones.

There’s a fast way of doing this in the scipy package, called scipy.ndimage.label which you could apply like this:

JavaScript

Output:

output of connected component algo

This solution is not exactly the thing you asked for – but it’s similar enough that it may work for your application.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement