Image Filtering

The following examples assume the input raster contains numeric greyscale values. If a raw colour image is used, the filters below will need to be applied separately to the red, green and blue components before recombining in a composite image.

A 3x3 mean filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Passes a 3x3 mean filter over a raster.
version(1.0);

# Change the directory below to correspond to your file location.
baseDir = "/Users/jwo/landscript/examples/data/";

# Open image file.
image = open(baseDir&"greyImage.srf");
filteredImage = new(image);

# Do the filtering and save the raster.
filteredImage = (image[-1,-1] + image[-1,0] + image[1,0] +
                 image[-1,0]  + image[0,0]  + image[1,0] + 
                 image[1,-1]  + image[1,0]  + image[1,1])/9;
save(filteredImage,baseDir&"filteredImage.srf");

A 5x5 median filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Passes a 5x5 median filter over a raster. Useful for removing noise from images.
version(1.0);

# Change the directory below to correspond to your file location.
baseDir = "/Users/jwo/landscript/examples/data/";

# Open image file.
image = open(baseDir&"greyImage.srf");
filteredImage = new(image);

# Do the filtering and save the raster.
filteredImage = median(image[-2,-2],image[-2,-1],image[-2,0],image[-2,1],image[-2,2],
                       image[-1,-2],image[-1,-1],image[-1,0],image[-1,1],image[-1,2],
                       image[ 0,-2],image[ 0,-1],image[ 0,0],image[ 0,1],image[ 0,2],
                       image[ 1,-2],image[ 1,-1],image[ 1,0],image[ 1,1],image[ 1,2],
                       image[ 2,-2],image[ 2,-1],image[ 2,0],image[ 2,1],image[ 2,2]);
save(filteredImage,baseDir&"filteredImage.srf");

A 3x3 edge detection filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Passes a 3x3 edge detection filter over a raster.
version(1.0);

# Change the directory below to correspond to your file location.
baseDir = "/Users/jwo/landscript/examples/data/";

# Open image file.
image = open(baseDir&"greyImage.srf");
filteredImage = new(image);

# Do the filtering and save the raster.
filteredImage = abs(-image[-1,-1] - image[-1,0] - image[1,0] 
                    -image[-1,0] +8*image[0,0]  - image[1,0]  
                    -image[1,-1]  - image[1,0]  - image[1,1]);

filteredImage = ifelse(filteredImage >255,255,filteredImage);

save(filteredImage,baseDir&"filteredImage.srf");