Last active
September 24, 2021 14:32
-
-
Save kumeS/46f606b1b30a510d52072e4638250b6a to your computer and use it in GitHub Desktop.
GoogleImage2Array & display.4dArray
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
GoogleImage2Array <- function(Query, wh=64, Save=FALSE, color=T){ | |
url <- URLencode(paste0("https://www.google.co.jp/search?q=", Query, "&btnG=Google+Search&tbs=0&safe=off&tbm=isch")) | |
imgsrc <- xml2::read_html(url) %>% | |
rvest::html_nodes(xpath = '//img') %>% | |
rvest::html_attr('src') %>% | |
.[startsWith(., "https://")] | |
#アレイデータを格納する変数 | |
Dat <- NULL | |
for(n in 1:length(imgsrc)){ | |
#n <- 1 | |
#URLを取り出す | |
imgsrc00 <- imgsrc[n] | |
#ローカルに保存する場合には、TRUEにする | |
if(Save){ | |
download.file(imgsrc00, | |
paste0("Image_", formatC(n, width = 3, flag = "0"),".jpg"), mode = "wb") | |
} | |
#画像読み込み | |
if(color){ | |
Img <- EBImage::readImage(imgsrc00, type="jpg") | |
}else{ | |
Img <- EBImage::readImage(imgsrc00, type="jpg") | |
Img <- EBImage::Image(Img, colormode = "gray", dim = c(dim(Img)[-3], 1)) | |
} | |
#EBImage::display(Img, method="raster") | |
#リサイズ | |
ImgR <- EBImage::resize(Img, w = wh, h=wh) | |
#str(ImgR) | |
ImgRArray <- array(ImgR, dim=dim(ImgR)) | |
#str(ImgRArray) | |
Dat[[n]] <- ImgRArray | |
} | |
#listからアレイに変換 | |
Tensor <- base::aperm(base::simplify2array(Dat), c(4, 1, 2, 3)) | |
#str(Tensor) | |
#出力 | |
return(Tensor) | |
} | |
#アレイデータを可視化する関数 | |
display.4dArray <- function(x, Query=NULL, Save=TRUE){ | |
par(mfrow=c(4,5), mar=rep(0, 4)) | |
for(n in 1:dim(x)[1]){ | |
#n <- 1 | |
plot(t(as.raster(x[n,,,], max=max(x[n,,,])))) | |
} | |
if(!is.null(Query)){ | |
if(Save){ quartz.save(paste0("Image_", Query, ".png"), type = "png") } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment