Debian Codegraph @

R/cvd_image.R

raw
1 #' Graphical User Interface to Check Images for Color Constraints
2 #'
3 #' A graphical user interface (GUI) to check an existing jpg/png image for (possible)
4 #' color constraints. The image will be converted to protanope vision, deuteranope vision,
5 #' and a desaturated version (monochromatic vision).
6 #' Allows a rapid check whether the colors used in the image show some
7 #' constraints with respect to color deficiency or color blindness.
8 #'
9 #' @param file If not set, an interactive GUI will be started. If \code{x} is of type
10 #' \code{character} it has to be the full path to an image of type png or jpg/jpeg.
11 #' The image will be converted and stored on disc, no GUI.
12 #' @param overwrite \code{logical}. Only used if \code{file} is provided. Allow the
13 #' function to overwrite files on disc if they exist.
14 #' @param shiny.trace \code{logical}. Can be set to \code{TRUE} for more verbose
15 #' output when the GUI is started (development flag).
16 #' @author Reto Stauffer, Claus O. Wilke, Achim Zeileis
17 #' @rdname cvd_emulator
18 #' @references Zeileis A, Fisher JC, Hornik K, Ihaka R, McWhite CD, Murrell P, Stauffer R, Wilke CO (2020).
19 #' \dQuote{colorspace: A Toolbox for Manipulating and Assessing Colors and Palettes.}
20 #' \emph{Journal of Statistical Software}, \bold{96}(1), 1--49. \doi{10.18637/jss.v096.i01}
21 #' @export
22 cvd_emulator <- function(file, overwrite = FALSE, shiny.trace = FALSE) {
23
24 # If input 'file' is missing: start interactive GUI
25 if ( missing(file) ) {
26 # Requirements for shiny application
27 stopifnot(requireNamespace("shiny"), requireNamespace("shinyjs"))
28 appDir <- system.file("cvdemulator", package = "colorspace")
29 if (appDir == "")
30 stop("Could not find cvdemulator app directory. Try re-installing `colorspace`.", call. = FALSE)
31 # Start shiny
32 options(shiny.trace = shiny.trace)
33 pal <- shiny::runApp(appDir, display.mode = "normal", quiet = TRUE )
34
35 # Do not start shiny: convert and save images on disc
36 } else {
37 is_img <- check_image_type(file)
38 if ( ! is_img$png & ! is_img$jpg )
39 stop(sprintf("Image \"%s\" is neither png nor jpg/jpeg. Stop.", file))
40 types <- c("deutan","protan","tritan","desaturate")
41 outfiles <- sprintf("%s/%s_%s", dirname(file), types,basename(file))
42 # If overwrite is FALSE: check if files exist and stop if.
43 if ( ! overwrite ) {
44 for ( ofile in outfiles ) {
45 if ( file.exists(ofile) )
46 stop(sprintf(paste("Output file \"%s\" exists.",
47 "Please remove the image manually or call",
48 "cvd_emulator(\"%s\", overwrite = TRUE)"),
49 ofile, file))
50 }
51 }
52 # Read image
53 if ( is_img$png ) {
54 in.img <- png::readPNG(file)
55 } else {
56 in.img <- jpeg::readJPEG(file)
57 }
58 # Convert and save image
59 for ( type in types ) {
60 outfile <- sprintf("%s/%s_%s",dirname(file),type,basename(file))
61 cat(sprintf("Convert %-15s -> %s\n",type,outfile))
62 out.img <- cvd_image(in.img, type, outfile)
63 }
64 }
65 }
66
67 # Check Image Type Based on suffix
68 #
69 # Checking image file type based on image file name. Used to decide
70 # which package has to be used to read an image from disc (\code{png}/\code{jpeg}).
71 #
72 # @param x, \code{string} containing (full) path to image.
73 # @return Returns a \code{list} with two elements. Each can take
74 # \code{TRUE} or \code{FALSE}. If image is of type \code{png}
75 # \code{png=TRUE}, if image is of type \code{jpg/jpeg} \code{jpg=TRUE}.
76 # If non of both, both will be \code{FALSE}. Method is not case sensitive.
77 check_image_type <- function( x ) {
78 ## Identify file type (suffix)
79 tail1 <- function(x) x[length(x)]
80 suffix <- tolower(tail1(strsplit(basename(x),"\\.")[[1]]))
81 list("png" = suffix == "png",
82 "jpg" = suffix %in% c("jpeg","jpg"))
83 }
84
85 # The convert function used
86 #' Convert Colors of an Image
87 #'
88 #' Used in \code{cvd_emulator}. Takes an image object and converts
89 #' the colors using \code{\link{deutan}}, \code{\link{protan}},
90 #' \code{\link{tritan}}, \code{\link{desaturate}} functions. The image
91 #' will be written to disc as a PNG file.
92 #'
93 #' @param img \code{character} or \code{array} as returned by \code{readPNG} and \code{readJPEG}
94 #' of size \code{height x width x depth}. The depth coordinate contains
95 #' R/G/B and alpha if given (png). In case of a single character string \code{img}
96 #' has to be the full path to an image of type png or jpg/jpeg.
97 #' @param type \code{string} name of the function which will be used to
98 #' convert the colors (\code{deutan}, \code{protan}, \code{tritan}, \code{desaturate}).
99 #' If set to \code{original} the image will be written as is.
100 #' @param file \code{string} with (full) path to resulting image. Has to
101 #' be a png image name.
102 #' @param severity numeric. Severity of the color vision defect, a number between 0 and 1.
103 #' @param linear logical. Should the color vision deficiency transformation be applied to the
104 #' linearized RGB coordinates (default)? If \code{FALSE}, the transformation is applied to the
105 #' gamma-corrected sRGB coordinates (which was the default up to version 2.0-3 of the package).
106 cvd_image <- function(img, type, file, severity = 1, linear = TRUE) {
107
108 # read image if necessary
109 if(is.character(img) && length(img) == 1L) {
110 img_type <- check_image_type(img)
111 if (!img_type$png & !img_type$jpg) stop(sprintf("Image \"%s\" is neither png nor jpg/jpeg.", img))
112 img <- if (img_type$png) png::readPNG(img) else jpeg::readJPEG(img)
113 }
114
115 # optionally save original colors
116 if (type == "original") {
117 png::writePNG(img, target = file)
118 return(TRUE)
119 }
120
121 # otherwise set up sRGB object, carry out cvd emulation, write back
122 RGB <- matrix(as.numeric(img[,,1L:3L]), ncol = 3L, dimnames = list(NULL, c("R", "G", "B")))
123 RGB <- colorspace::sRGB(RGB)
124 RGB <- do.call(type, list(col = RGB, severity = severity, linear = linear))
125 RGB <- colorspace::coords(RGB)
126 img[,,1L] <- matrix(RGB[,"R"], dim(img)[1L], dim(img)[2L])
127 img[,,2L] <- matrix(RGB[,"G"], dim(img)[1L], dim(img)[2L])
128 img[,,3L] <- matrix(RGB[,"B"], dim(img)[1L], dim(img)[2L])
129 png::writePNG(img, target = file)
130 return(TRUE)
131 }