A89
A89

Reputation: 109

Obtain the boundaries from a png file

I am wondering how to obtain the boundaries from this kind of image.

For example:

I was looking converting some image using

image <- as(x, 'SpatialGridDataFrame')

But it only give me special heavy images.

In this case, using this x_coord and y_coord I am be able to create a simple object.

 x_coord <- c(16.48438,  17.49512,  24.74609, 22.59277, 16.48438)
 y_coord <- c(59.736328125, 55.1220703125, 55.0341796875, 
 61.142578125, 59.736328125)
 xym <- cbind(x_coord, y_coord)
 xym

 library(sp)
 p = Polygon(xym)
 ps = Polygons(list(p),1)
 sps1 = SpatialPolygons(list(ps))
 plot(sps1)

I expect to obtain a set of x_coord and y_coord for the circle png added as example.

Upvotes: 0

Views: 144

Answers (1)

Taher A. Ghaleb
Taher A. Ghaleb

Reputation: 5240

You can use the pixsets approach (in the imager package) to identify the edges of the circle in the given image, as follows:

px <- im > 0.6 #Select pixels of the circle (i.e., those with high luminance)
plot(px)

Now, when you plot px, you get the following:

pixels

To get the coordinates of the pixels, you use the following:

coord <- where(px)
head(coord)

which gives you something like this:

#  x y cc
#1 1 1  1
#2 2 1  1
#3 3 1  1
#4 4 1  1
#5 5 1  1
#6 6 1  1

To get the boundaries, you use the following:

boundaries <- boundary(px)
boundaries.xy <- where(boundaries)
head(boundaries.xy)

which gives you the following:

#    x  y cc
#1 103 64  1
#2 102 65  1
#3 104 65  1
#4 103 66  1
#5 185 71  1
#6 184 72  1

You may even save the circle pixels as follows:

px_image <- as.cimg(px)
save.image(px_image, "px_image.jpg")

Hope it helps.

Upvotes: 1

Related Questions