I want to use a raster to stratify an image using different texture. I have a raster image (ndvi_2019) for which I want to extract random coordinates as points from each classes. First, I want to form these create these classes I want to extract these coordinates by classing the values in the ndvi raster object as below;

class 1= <0
class 2= 0:0.1
class 3= 0.1:0.2
class 4 = >0.2

The assumption is that the classification forms the different strata which can then indicate different strata.

ndvi_2019<- (choma_clip[[4]]- choma_clip[[3]])/(choma_clip[[4]]+choma_clip[[3]]) 
r<- ndvi_2019


r<- setValues(r, rnorm(ncell(r)))
pts<- spsample(as(extent(r@extent, "SpatialPolygons"), 30, type="random")) class1<- r/r <0 
class2<- r/r[r== 0:0.1]]
class3<- r/r[[r== 0.1:0.2]]
class4 <- r/r>0.2

enter image description here

  • I am using r. I would appreciate answers in qgis too. – Brave Mar 29 '19 at 11:23
  • I am using r. r<- ndvi_2019 r<- setValues(r, rnorm(ncell(r))) pts<- spsample(as(extent(r@extent, "SpatialPolygons"), 30, type="random")) class1<- r/r <0 class2<- r/r[r== 0:0.1]]; class3<- r/r[[r== 0.1:0.2]] ; class4 <- r/r>0.2 – Brave Mar 29 '19 at 11:29

I don't think you need to create new objects if all you want to do is sample points in a raster according to a criteria. You can simply filter the cells you want using the which() function.

Using the raster library, you can call the values(r) function to get a list of values, or just use r[] (where r is the raster object.)

The which() function will tell you which cells fit each criteria. Once you have that list, you can sample() on it to get a sample. Lastly, the coordinates() function will return the coordinates for each cell of the raster object you've selected. The coordinates(r) function will return coordinates of all cells, so you have to use the square brackets to define which rows you want (the sampled rows), as well as both columns (x and y).

numPts <- 30 # Or however many points you want

r <- raster("path/to/your/raster")
sampledCoords1 <- coordinates(r)[sample(which(r[]<0), numPts),1:2]
sampledCoords2 <- coordinates(r)[sample(which((r[]>=0)&(r[]<0.1)), numPts),1:2]
sampledCoords3 <- coordinates(r)[sample(which((r[]>=0.1)&(r[]<0.2)), numPts),1:2]
sampledCoords4 <- coordinates(r)[sample(which(r[]>=0.2), numPts),1:2]
  • 1
    Note: xyFromCell(r,index) is probably quicker than subsetting from all coordinates(r) – Spacedman Mar 29 '19 at 15:50
  • @Mike N, Thank you again. This was so helpful. I noted for sure that pixel values for higher values >=0 .2 were more less than the sample. Adjusting sample size has worked now. – Brave Mar 30 '19 at 12:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.