# Calculating distance between point and selected pixel in R?

I would like to obtain the distance between a point and a selection of pixel on raster image. Here the process:

I read my JPEG image and extract colors I want:

`````` img.raster<-stack(***)

names(img.raster) <- c('r','g','b')

img.a<-img.raster[]

img.a[] =0

img.a[img.raster\$r<70 & img.raster\$g<70 & img.raster\$b<255] <- 255

img.c<-img.raster[]

img.c[] =0

img.c[img.raster\$r>70 & img.raster\$g>82 & img.raster\$b>65] <- 255

img.b<-img.raster[]

img.b[] =0

img.b[img.raster\$r>65 & img.raster\$r<160

& img.raster\$g>70 & img.raster\$g<255

& img.raster\$b>0 & img.raster\$b<65] <- 255
``````

Then I recreate my final image and thus img.c is red, img.b is green and img.a is blue:

``````      final_image = stack(img.c, img.b, img.a)
``````

I am trying to calculate the distance between a point of coord (x,y) and all the pixels I extracted of the img.a. (in green in the following picture): But if I calculate the distance between the point (xy) and img.a by using:

xy <- c(590,61)

d <- distanceFromPoints(img.a, xy)

I obtain the distance between all pixels (means the green and white).

Do you know how to select only the pixel I extracted on img.a ?

## 1 Answer

You can define a function to select pixel values and then transform that raster into points in order to use pointDistance() function. Here is a piece of the code I have used: my raster is a dem and my selected point proceed from a shp (you can make it easily from a point like your xy <- c(590,61)). Then I select just get raster cells above 450m. Finally, I use that pointDistance function to add the value of distance to the SpatialPointsDataFrame created by subseting raster.

``````library(rgdal)

r <- raster("./DEM/DEM.tif") #read raster
shpA <- readOGR("./PA", "PA")[1,] #read shapefile of and get one point

#raster to points (>450)
rpoints <- rasterToPoints(r, fun=function(x){x>450}, spatial=TRUE)

rpoints\$pdist <- pointDistance(shpA, rpoints)
rpoints

> > rpoints
>     class       : SpatialPointsDataFrame
>     features    : 33615
>     extent      : 511046.5, 513250.5, 4648854, 4651485  (xmin, xmax, ymin, ymax)
>     coord. ref. : +proj=utm +zone=29 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
>     variables   : 2
>     names       :              DEM,            pdist
>     min values  : 450.001007080078, 1289.01733845496
>     max values  : 548.039978027344, 3042.91320760357

#plots
plot(r)
plot(rpoints, add = TRUE)
plot(shpA, add=TRUE)
`````` 