Created
August 12, 2018 19:43
-
-
Save JEFworks/25f229e52d6d633e5c3a771e9ab9f38b to your computer and use it in GitHub Desktop.
Flickr API usage in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Use flickr API to get 20 public images for flowers | |
data1 = paste0(readLines('https://api.flickr.com/services/feeds/photos_public.gne?tags=lilacs'), collapse="") | |
data2 = paste0(readLines('https://api.flickr.com/services/feeds/photos_public.gne?tags=cherryblossoms'), collapse="") | |
data3 = paste0(readLines('https://api.flickr.com/services/feeds/photos_public.gne?tags=marigolds'), collapse="") | |
data4 = paste0(readLines('https://api.flickr.com/services/feeds/photos_public.gne?tags=daffodils'), collapse="") | |
dataLines = c( | |
strsplit(data1, "<entry>")[[1]][-1], | |
strsplit(data2, "<entry>")[[1]][-1], | |
strsplit(data3, "<entry>")[[1]][-1], | |
strsplit(data4, "<entry>")[[1]][-1] | |
) | |
## Get image urls | |
urls = unlist(lapply(dataLines, function(x) substr(x, | |
gregexpr("img src="", x)[[1]][1]+nchar("img src=""), | |
gregexpr("g" width="", x)[[1]][1]))) | |
## Plot original images | |
library(jpeg) | |
library(rvest) | |
par(mfrow=c(5,4), mar=rep(0,4), bg='white') | |
imgs <- lapply(urls, function(session) { | |
webpage <- html_session(session) | |
url <- webpage$url | |
## Download image from url | |
z <- tempfile() | |
download.file(url, z, mode="wb") | |
img <- readJPEG(z) | |
file.remove(z) # cleanup | |
## Round RGB values to minimize number of total possible colors | |
img = round(img, digits = 1) | |
plot.new() | |
lim <- par() | |
rasterImage(img, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4]) | |
return(img) | |
}) | |
## Get all possible colors | |
all.colors <- unlist(lapply(seq(0, 1, by=0.1), function(r) { | |
lapply(seq(0, 1, by=0.1), function(g) { | |
lapply(seq(0, 1, by=0.1), function(b) { | |
foo <- rgb2hsv(r,g,b)[1,1] # order by hue | |
names(foo) <- rgb(r,g,b) | |
return(foo) | |
}) | |
}) | |
})) | |
## Sort | |
all.colors <- names(sort(all.colors)) | |
## Get distribution of colors for all images | |
cols <- do.call(cbind, lapply(imgs, function(img) { | |
## Convert from numbers to colors | |
colors <- sapply(1:nrow(img), function(x) { | |
sapply(1:ncol(img), function(y) { | |
rgb(img[x,y,1], img[x,y,2], img[x,y,3]) | |
}) | |
}) | |
## Color frequency | |
common.colors <- table(colors) | |
col <- rep(0, length(all.colors)) | |
names(col) <- all.colors | |
col[names(common.colors)] <- common.colors | |
#col[names(common.colors)] <- 1 | |
return(col) | |
})) | |
## Visualize distribution | |
par(mfrow=c(1,1), mar=rep(0,4), bg='white') | |
barplot(prop.table(cols, 2), col=rownames(cols), axes=FALSE, border=NA) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment