图像处理R包magick学习笔记

简介


本文主要简单介绍一下magick包,主要用于图像处理

#安装的话就直接从CRAN安装进行
install.packages("magick")
#Load the package
library(magick)
#查看支持哪些格式
str(magick_config())
## List of 21
##  $ version           :Class 'numeric_version'  hidden list of 1
##   ..$ : int [1:4] 6 9 9 9
##  $ modules           : logi FALSE
##  $ cairo             : logi TRUE
##  $ fontconfig        : logi FALSE
##  $ freetype          : logi TRUE
##  $ fftw              : logi TRUE
##  $ ghostscript       : logi TRUE
##  $ jpeg              : logi TRUE
##  $ lcms              : logi TRUE
##  $ libopenjp2        : logi FALSE
##  $ lzma              : logi TRUE
##  $ pangocairo        : logi TRUE
##  $ pango             : logi TRUE
##  $ png               : logi TRUE
##  $ rsvg              : logi TRUE
##  $ tiff              : logi TRUE
##  $ webp              : logi TRUE
##  $ wmf               : logi FALSE
##  $ x11               : logi FALSE
##  $ xml               : logi TRUE
##  $ zero-configuration: logi FALSE

可以看出大部分格式都是支持的

读取图像


读取的话可以直接从本地读取,也可以读取URL格式的图片,主要通过image_read()来读取,image_info()则可以显示图像的一些属性数据。

#读取网上随便选的图片
night_king <- image_read("https://github.com/YTLogos/Pic_blog/blob/master/ha6Cchfk38.jpg?raw=true")
image_info(night_king)
##   format width height colorspace filesize
## 1   JPEG   189    267       sRGB     6449
#通过image_write()可以讲图片以任何格式输出,比如将刚读取的图片以png格式输出。
image_write(night_king, path = "night_king.png", format = "png")

转换格式


通过image_convert()可以将图片转换为我们需要的格式,比如这里我们可以将night_king的格式转换为png格式

night_king.png <- image_convert(night_king, "png")
image_info(night_king.png)
##   format width height colorspace filesize
## 1    PNG   189    267       sRGB        0

可以看到这里的filesize为0,直到被渲染(这里涉及到ImageMagick方面,我不是很懂)。

预览


在RStudio中可以查看我们读取的图片

转换(transformations)

magick提供一系列函数对图片进行裁剪以及编辑,主要有以下函数:

  • image_crop(image, “100x150+50”):裁剪
  • image_scale(image, “200”):按宽比例进行放大缩小
  • image_scale(image, “x200”):按高比例进行放大缩小
  • image_fill(image, “blue”, “+100+200”):对特定部位着色
  • image_border(image, “red”, “20x10”):添加边框

下面我们来试试这些函数

#Example image
wolf <- image_read("https://github.com/YTLogos/Pic_blog/blob/master/4h96Df21AI.png?raw=true")
print(wolf)

#Add 20px left/right and 10px top/bottom
image_border(image_background(wolf, "hotpink"), "#000080", "20x10")

#trim margins
image_trim(wolf)

#裁剪
image_crop(wolf, "500x300+50")

#Resize
image_scale(wolf, "300")#width:300px

#Resize
image_scale(wolf, "x300")#heigth:300px

#Rotate or mirror
image_rotate(wolf, 45)

#Flip
image_flip(wolf)

#Flop
image_flop(wolf)

#Paint 
image_fill(wolf, "red", point = "+190+100", fuzz = 4000)

这个函数最难掌握,我本来是想将wolf的眼睛渲染成红色,但是不断调整point以及fuzz都没弄成,感兴趣的可以自己捣鼓捣鼓。

#Add randomness
image_blur(wolf, 10, 5)

可以通过调整参数来设置模糊度

image_noise(wolf)

#Silly filters
image_charcoal(wolf)

image_oilpaint(wolf)

image_negate(wolf)

文字注释


#Add some text on the image
image_annotate(wolf, "I am the King of wolf", size=25, gravity = "southeast", color="gold")

自定义text

#customize the text
image_annotate(wolf, "I am the King", size=30, color="red", boxcolor = "pink", degrees = 45, location = "+30+30")

设置字体

#Set the font times-new-roman
image_annotate(wolf, "I am the King", size=30, color="red", boxcolor = "pink", degrees = 45, location = "+30+30", font = 'times-new-roman')

管道操作


你没看错,magick支持管道操作,下面试试

library(magrittr)
wolf%>%
  image_rotate(270)%>%
  image_background("white", flatten = TRUE)%>%
  image_border("red", "10x10")%>%
  image_annotate("I am the King", color='red', size = 25, location = "+100+300")

图片向量


magick除了支持管道操作外,还支持图层叠加、拼图以及动图处理,来个经典的动态地球

earth <- image_read("https://github.com/YTLogos/Pic_blog/blob/master/a9CjAEGiC5.gif")
length(earth)
print(earth)

rev(earth) %>% 
  image_flip() %>% 
  image_annotate("This is the Earth", size = 20, color = "white")

不知什么鬼,图片竟然显示出来乱的,电脑渣的话还是别搞动画

图层


bigdata <- image_read("https://github.com/YTLogos/Pic_blog/blob/master/JclK3efbB3.jpg?raw=true")
logo <- image_read("https://github.com/YTLogos/Pic_blog/blob/master/JdjdB88CLm.png?raw=true")
frink <- image_read("https://github.com/YTLogos/Pic_blog/blob/master/E5fbmb1FIb.png?raw=true")
img <- c(bigdata, logo, frink)
img <- image_scale(img, "300x300")
image_mosaic(img)

动画


image_animate(image_scale(img, "200x200"), fps = 1, dispose = "previous")#fps控制放映速度

静图+动图


静图就用我以前绘制过的,具体可看 博客

image1 <- image_read("https://github.com/YTLogos/Pic_blog/blob/master/kLeL888DbI.png?raw=true")
dance_man <- image_read("https://github.com/YTLogos/Pic_blog/blob/master/86iEDe36lf.gif?raw=true")
dance_man <- image_scale(dance_man, "200")
#Background image
background <- image_background(image_scale(image1, "800"), "white", flatten = TRUE)
#Combine and flatten frames
frames <- image_apply(dance_man, function(frame){
  image_composite(background, frame, offset = "+500+270")
})
#Turn frames into animation
animation <- image_animate(frames, fps = 10)
print(animation)

还有一些有趣的功能这里我就不讲了,有兴趣的可以试试,还是很好玩的。

SessionInfo


sessionInfo()

## R version 3.4.1 (2017-06-30)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 15063)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=Chinese (Simplified)_China.936 
## [2] LC_CTYPE=Chinese (Simplified)_China.936   
## [3] LC_MONETARY=Chinese (Simplified)_China.936
## [4] LC_NUMERIC=C                              
## [5] LC_TIME=Chinese (Simplified)_China.936    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] magrittr_1.5 magick_1.2  
## 
## loaded via a namespace (and not attached):
##  [1] compiler_3.4.1  backports_1.1.0 rprojroot_1.2   tools_3.4.1    
##  [5] htmltools_0.3.6 curl_2.8.1      yaml_2.1.14     Rcpp_0.12.12   
##  [9] stringi_1.1.5   rmarkdown_1.6   knitr_1.17      stringr_1.2.0  
## [13] digest_0.6.12   evaluate_0.10.1
Researcher

I am a PhD student of Crop Genetics and Breeding at the Zhejiang University Crop Science Lab. My research interests covers a range of issues:Population Genetics Evolution and Ecotype Divergence Analysis of Oilseed Rape, Genome-wide Association Study (GWAS) of Agronomic Traits.

comments powered by Disqus