7

May be it is a silly question but I don't have a lot of experience doing this. I need to get the coordinates from a polygon to create a contour in R. It is a complex polygon of about 1000 points so to input the coordinates manually is crazy. Also I need to extract the xy position of some objects inside the contour. I tried to use Illustrator and Inkscape to create an svg file that contains all the information. It looks like a good option considering that the svg file contains all the information. Is there a way to extract the coordinates from the path or polygon nods? or there is any other simpler way to do this process? I will really appreciate any help because I have to do it for around 30 images. Cheers

Eduardo Garza
  • 87
  • 1
  • 8
  • 1
    A link to a sample file or a way to recreate one would make this a whole lot easier to answer. http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Richie Cotton Apr 13 '12 at 06:41
  • Ok sorry for not giving the svg file, I copied a section of it: – Eduardo Garza Apr 13 '12 at 06:47
  • I don't know how to attach the file it has a lot of points. This is just an example, I need to get the coordinates from the polygon and then the coordinates from the text. I hope it makes sense – Eduardo Garza Apr 13 '12 at 06:51
  • 2
    you could look into package `grImport` which imports vector images and converts them into paths that R can interpret. – baptiste Apr 13 '12 at 06:58

1 Answers1

9

You can use the XML package to extract the coordinates.

# Sample data
library(RCurl)
url <- "http://upload.wikimedia.org/wikibooks/en/a/a8/XML_example_polygon.svg"
svg <- getURL(url)

# Parse the file
library(XML)
doc <- htmlParse(svg)

# Extract the coordinates, as strings
p <- xpathSApply(doc, "//polygon", xmlGetAttr, "points")

# Convert them to numbers
p <- lapply( strsplit(p, " "), function(u) 
  matrix(as.numeric(unlist(strsplit(u, ","))),ncol=2,byrow=TRUE) )
p

However, this ignores any transformation to be applied to the polygon.

Vincent Zoonekynd
  • 31,893
  • 5
  • 69
  • 78
  • Thanks it works nice, I tried to do it using the XML package but I didn't use htmlParse so I think that was the problem. – Eduardo Garza Apr 13 '12 at 08:08