[R-sig-Geo] Assign a unique ID number to each patch in a raster

Ben Tupper btupper at bigelow.org
Fri Jan 27 01:19:09 CET 2017


Hi,

I think you are asking for connected component labeling. raster::clump() expects your features to be like islands surrounded by NA or 0 background. There might be more Raster* centric ways to do it, but you could use plain old vanilla image processing using the very good imager package ( https://cran.r-project.org/web/packages/imager/ <https://cran.r-project.org/web/packages/imager/> ).  The steps below show in color your actual values with the connected component IDs labeled on each cell.  I used the 8-connected labeling but 4-connected is also available.

library(raster)
library(imager)

set.seed(10)
nc <- 8
nr <- 8
MIN <- 1
MAX <- 4
LUT <- c("orange", "green", "darkgoldenrod", "cornflowerblue")

r <- raster(ncols=nc, nrows=nr)
r[] <- round(runif(ncell(r),MIN, MAX),digits=0)
cc <- r

img <- imager::as.cimg(as.matrix(r))
labeled <- imager::label(img, high_connectivity = TRUE)
cc[] <- as.matrix(labeled)

plot(r, col = LUT)
txt <- cc[]
xy <- raster::xyFromCell(cc, 1:raster::ncell(cc))
text(xy[,1], xy[,2], txt )


Cheers,
Ben 
> On Jan 26, 2017, at 4:48 PM, Nelly Reduan <nell.redu at hotmail.fr> wrote:
> 
> Hello,
> I would like to assign a unique ID number to each patch (a patch is composed of a set of adjacent cells) as shown in this figure:
>  <2328.png>
> 
> I tested the clump function (package raster) by applying an eight adjacent cells rule but this function mixes all cell values into single patch. 
> 
> Here is a code example to create a raster. The raster contains values ranged from 1 to 9.
> r <- raster(ncols=12, nrows=12)
> r[] <- round(runif(ncell(r),1,9),digits=0)
> plot(r)
> 
> Is there a way to assign a unique ID number to grouping cells that form a patch for each class (i.e., values 1, 2, 3, 4, 5, 6, 7, 8, 9) ?
> 
> Thanks a lot for your time
> Nell
> 
> 
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org <mailto:R-sig-Geo at r-project.org>
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo <https://stat.ethz.ch/mailman/listinfo/r-sig-geo>
Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org




	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list