|
R/ |
183 | 105 | 0 | 105 | 0.0 | 0.00% |
|
R/ |
187 | 105 | 0 | 105 | 0.0 | 0.00% |
|
R/ |
184 | 77 | 0 | 77 | 0.0 | 0.00% |
|
R/ |
105 | 77 | 0 | 77 | 0.0 | 0.00% |
|
R/ |
163 | 65 | 0 | 65 | 0.0 | 0.00% |
|
R/ |
150 | 60 | 0 | 60 | 0.0 | 0.00% |
|
R/ |
124 | 58 | 0 | 58 | 0.0 | 0.00% |
|
R/ |
67 | 38 | 0 | 38 | 0.0 | 0.00% |
|
R/ |
51 | 27 | 0 | 27 | 0.0 | 0.00% |
|
R/ |
61 | 26 | 0 | 26 | 0.0 | 0.00% |
|
R/ |
93 | 25 | 0 | 25 | 0.0 | 0.00% |
|
R/ |
75 | 23 | 0 | 23 | 0.0 | 0.00% |
|
R/ |
54 | 22 | 0 | 22 | 0.0 | 0.00% |
|
R/ |
65 | 20 | 0 | 20 | 0.0 | 0.00% |
|
R/ |
43 | 19 | 0 | 19 | 0.0 | 0.00% |
|
R/ |
56 | 19 | 0 | 19 | 0.0 | 0.00% |
|
R/ |
43 | 16 | 0 | 16 | 0.0 | 0.00% |
|
R/ |
34 | 6 | 0 | 6 | 0.0 | 0.00% |
|
R/ |
17 | 4 | 0 | 4 | 0.0 | 0.00% |
|
src/ |
778 | 564 | 25 | 539 | 630.9 | 4.43% |
|
R/ |
149 | 69 | 10 | 59 | 10.7 | 14.49% |
|
src/ |
57 | 21 | 7 | 14 | 20086.4 | 33.33% |
|
R/ |
89 | 37 | 14 | 23 | 13.6 | 37.84% |
|
R/ |
34 | 12 | 5 | 7 | 28.1 | 41.67% |
|
R/ |
135 | 64 | 29 | 35 | 0.9 | 45.31% |
|
R/ |
48 | 33 | 15 | 18 | 28.2 | 45.45% |
|
R/ |
29 | 8 | 4 | 4 | 3.5 | 50.00% |
|
R/ |
172 | 78 | 42 | 36 | 0.7 | 53.85% |
|
R/ |
423 | 251 | 136 | 115 | 13.5 | 54.18% |
|
R/ |
142 | 72 | 42 | 30 | 1.7 | 58.33% |
|
src/ |
1170 | 745 | 443 | 302 | 21.4 | 59.46% |
|
R/ |
112 | 73 | 45 | 28 | 22.2 | 61.64% |
|
R/ |
371 | 219 | 142 | 77 | 128.8 | 64.84% |
|
R/ |
203 | 100 | 65 | 35 | 2.5 | 65.00% |
|
R/ |
51 | 24 | 16 | 8 | 4.7 | 66.67% |
|
R/ |
28 | 9 | 6 | 3 | 100.4 | 66.67% |
|
R/ |
68 | 46 | 31 | 15 | 90.3 | 67.39% |
|
R/ |
118 | 41 | 28 | 13 | 1.4 | 68.29% |
|
R/ |
158 | 90 | 65 | 25 | 2.2 | 72.22% |
|
R/ |
80 | 31 | 23 | 8 | 19.0 | 74.19% |
|
src/ |
82 | 40 | 31 | 9 | 1532.7 | 77.50% |
|
R/ |
176 | 92 | 73 | 19 | 23.0 | 79.35% |
|
R/ |
219 | 102 | 83 | 19 | 6.9 | 81.37% |
|
R/ |
434 | 172 | 143 | 29 | 15.3 | 83.14% |
|
R/ |
396 | 254 | 221 | 33 | 324.6 | 87.01% |
|
R/ |
171 | 70 | 61 | 9 | 3.0 | 87.14% |
|
R/ |
419 | 211 | 184 | 27 | 16.0 | 87.20% |
|
R/ |
150 | 62 | 56 | 6 | 177.8 | 90.32% |
|
R/ |
197 | 99 | 90 | 9 | 897.8 | 90.91% |
|
R/ |
159 | 89 | 81 | 8 | 7.1 | 91.01% |
|
R/ |
135 | 72 | 66 | 6 | 22.2 | 91.67% |
|
R/ |
131 | 40 | 37 | 3 | 8.1 | 92.50% |
|
R/ |
43 | 27 | 26 | 1 | 52.1 | 96.30% |
|
R/ |
74 | 34 | 33 | 1 | 164.9 | 97.06% |
|
R/ |
304 | 161 | 157 | 4 | 16.2 | 97.52% |
|
R/ |
123 | 60 | 59 | 1 | 9.1 | 98.33% |
|
src/ |
93 | 54 | 54 | 0 | 67.9 | 100.00% |
|
R/ |
74 | 40 | 40 | 0 | 5.7 | 100.00% |
|
R/ |
162 | 19 | 19 | 0 | 2.0 | 100.00% |
|
R/ |
37 | 7 | 7 | 0 | 8.0 | 100.00% |
| Total | 9749 | 5084 | 2714 | 2370 | 217.4 | 53.38% |
| 1 | #'@title Add Overlay | |
| 2 | #' | |
| 3 | #'@description Takes an RGB array/filename and composites an image overlay over | |
| 4 | #'the full image. For pixel-positioned sprite, label, glyph, or billboard | |
| 5 | #'overlays, use [render_sprite_overlay()]. | |
| 6 | #' | |
| 7 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 8 | #'@param image_overlay Default `NULL`. 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 9 | #'This image will be resized to the dimensions of `image` if it does not match | |
| 10 | #'exactly, unless `rescale_original = TRUE`. | |
| 11 | #'@param rescale_original Default `FALSE`. If `TRUE`, function will resize the original image to match | |
| 12 | #'the overlay. | |
| 13 | #'@param convert_overlay_colorspace Default `TRUE`. Whether to convert the overlay's colorspace | |
| 14 | #'to match the underlying image. | |
| 15 | #'@param alpha Default `NA`, using overlay's alpha channel. Otherwise, this sets the alpha transparency | |
| 16 | #'by multiplying the existing alpha channel by this value (between 0 and 1). | |
| 17 | #'@param filename Default `NULL`. File to save the image to. If `NULL` and `preview = FALSE`, | |
| 18 | #'returns an RGB array. | |
| 19 | #'@param preview Default `FALSE`. If `TRUE`, it will display the image in addition | |
| 20 | #'to returning it. | |
| 21 | #'@return A `rayimg` RGBA array. | |
| 22 | #'@import grDevices | |
| 23 | #'@export | |
| 24 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 25 | #'#Plot the dragon | |
| 26 | #'plot_image(dragon) | |
| 27 | #'#Add an overlay of a red semi-transparent circle: | |
| 28 | #'circlemat = generate_2d_disk(min(dim(dragon)[1:2])) | |
| 29 | #'circlemat = circlemat/max(circlemat) | |
| 30 | #' | |
| 31 | #'#Create RGBA image, with a transparency of 0.5 | |
| 32 | #'rgba_array = array(1, dim=c(nrow(circlemat),ncol(circlemat),4)) | |
| 33 | #'rgba_array[,,1] = circlemat | |
| 34 | #'rgba_array[,,2] = 0 | |
| 35 | #'rgba_array[,,3] = 0 | |
| 36 | #'dragon_clipped = dragon | |
| 37 | #'dragon_clipped[dragon_clipped > 1] = 1 | |
| 38 | #'render_image_overlay(dragon_clipped, image_overlay = rgba_array, | |
| 39 | #' alpha=0.5, preview = TRUE) | |
| 40 | #' | |
| 41 | #' # Read photo, convert to ACEScg with CAT (scene) | |
| 42 | #' photo = ray_read_image(sunset_image, normalize = FALSE) | |
| 43 | #' photo_aces = render_convert_colorspace( | |
| 44 | #' photo, | |
| 45 | #' to_mats = CS_ACESCG, | |
| 46 | #' adapt_white = TRUE | |
| 47 | #' ) | |
| 48 | #' tmp_txt = tempfile(fileext = ".png") | |
| 49 | #' render_text_image( | |
| 50 | #' "Sunset", | |
| 51 | #' size = 60, | |
| 52 | #' filename = tmp_txt, | |
| 53 | #' color = "#c300ff", | |
| 54 | #' background_alpha = 0 | |
| 55 | #' ) | |
| 56 | #' # Read logo (display-referred), convert primaries only (no CAT) | |
| 57 | #' logo = ray_read_image(tmp_txt, normalize = FALSE) # sRGB/D65 | |
| 58 | #' logo_aces = render_convert_colorspace( | |
| 59 | #' logo, | |
| 60 | #' to_mats = CS_ACESCG, | |
| 61 | #' adapt_white = FALSE | |
| 62 | #' ) | |
| 63 | #' | |
| 64 | #' # Composite in ACEScg, then display (plot_image converts to sRGB/D65 + OETF) | |
| 65 | #' # Here, we also turn overlay conversion in [render_image_overlay()] off, | |
| 66 | #' # to show what happens when you don't account for the colorspace difference. | |
| 67 | #' # By default [render_image_overlay()] will do this for you. | |
| 68 | #' comp1 = render_image_overlay( | |
| 69 | #' photo_aces, | |
| 70 | #' logo_aces, | |
| 71 | #' convert_overlay_colorspace = FALSE | |
| 72 | #' ) |> | |
| 73 | #' render_title(title_text = "#c300ff: Match", | |
| 74 | #' title_bar_color = "white", title_color = "#c300ff", title_bar_alpha=1) | |
| 75 | #' comp2 = render_image_overlay( | |
| 76 | #' photo_aces, | |
| 77 | #' logo, | |
| 78 | #' convert_overlay_colorspace = FALSE | |
| 79 | #' ) |> | |
| 80 | #' render_title(title_text = "#c300ff: Incorrect", | |
| 81 | #' title_bar_color = "white", title_color = "#c300ff", title_bar_alpha=1) | |
| 82 | #' | |
| 83 | #' plot_image_grid(list(comp1, comp2), dim = c(1, 2)) | |
| 84 | render_image_overlay = function( | |
| 85 | image, | |
| 86 | image_overlay = NULL, | |
| 87 | rescale_original = FALSE, | |
| 88 | convert_overlay_colorspace = TRUE, | |
| 89 | alpha = NA, | |
| 90 | filename = NULL, | |
| 91 | preview = FALSE | |
| 92 | ) { | |
| 93 | 3x | render_image_overlay_impl( |
| 94 | 3x | image = image, |
| 95 | 3x | image_overlay = image_overlay, |
| 96 | 3x | rescale_original = rescale_original, |
| 97 | 3x | convert_overlay_colorspace = convert_overlay_colorspace, |
| 98 | 3x | alpha = alpha, |
| 99 | 3x | filename = filename, |
| 100 | 3x | preview = preview |
| 101 | ) | |
| 102 | } | |
| 103 | ||
| 104 | #'@title Add Sprite Overlay | |
| 105 | #' | |
| 106 | #'@description Places an image overlay at a pixel location without resizing it to | |
| 107 | #'the full destination image. This is intended for sprite-like or billboard-like | |
| 108 | #'overlays such as labels, icons, glyphs, and screen-space annotations. | |
| 109 | #' | |
| 110 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 111 | #'@param image_overlay Default `NULL`. 3-layer RGB/4-layer RGBA array, `rayimg` | |
| 112 | #'class, or filename of the sprite overlay. | |
| 113 | #'@param convert_overlay_colorspace Default `TRUE`. Whether to convert the overlay's colorspace | |
| 114 | #'to match the underlying image. | |
| 115 | #'@param alpha Default `NA`, using overlay's alpha channel. Otherwise, this sets the alpha transparency | |
| 116 | #'by multiplying the existing alpha channel by this value (between 0 and 1). | |
| 117 | #'@param overlay_coords Default `c(1, 1)`. Pixel coordinate `c(x, y)` used to | |
| 118 | #'position the overlay. `x` increases from left to right and `y` from top to | |
| 119 | #'bottom, starting at 1. | |
| 120 | #'@param overlay_dims Default `NULL`. Dimensions for the overlay in pixels. If | |
| 121 | #'provided, the overlay is resized with `render_resized()` before compositing. | |
| 122 | #'@param overlay_anchor Default `"nw"`. Which corner of the overlay is placed at | |
| 123 | #'`overlay_coords` when no numeric justification is supplied. Options: `"nw"`, | |
| 124 | #'`"ne"`, `"sw"`, `"se"`. | |
| 125 | #'@param overlay_just Default `NULL`. Optional numeric `c(hjust, vjust)` | |
| 126 | #'justification used to place the overlay relative to `overlay_coords`. If set, | |
| 127 | #'the overlay's left/top pixel is computed as | |
| 128 | #'`round(x - hjust * overlay_width)` and | |
| 129 | #'`round(y - vjust * overlay_height)`. | |
| 130 | #'@param hjust Default `NULL`. Optional horizontal justification. Overrides the | |
| 131 | #'first value of `overlay_just`. | |
| 132 | #'@param vjust Default `NULL`. Optional vertical justification. Overrides the | |
| 133 | #'second value of `overlay_just`. | |
| 134 | #'@param preserve_channels Default `TRUE`. If `TRUE`, RGB input images return | |
| 135 | #'RGB output and RGBA input images return RGBA output. | |
| 136 | #'@param filename Default `NULL`. File to save the image to. If `NULL` and | |
| 137 | #'`preview = FALSE`, returns an image array. | |
| 138 | #'@param preview Default `FALSE`. If `TRUE`, it will display the image in addition | |
| 139 | #'to returning it. | |
| 140 | #' | |
| 141 | #'@return A `rayimg` array. | |
| 142 | #'@export | |
| 143 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 144 | #'dragon_clipped = dragon | |
| 145 | #'dragon_clipped[dragon_clipped > 1] = 1 | |
| 146 | #' | |
| 147 | #'# Render a transparent dragon emoji and center it on a pixel with hjust/vjust: | |
| 148 | #'dragon_emoji = render_text_image( | |
| 149 | #' "\U0001F409", | |
| 150 | #' size = 80, | |
| 151 | #' background_alpha = 0, | |
| 152 | #' use_ragg = TRUE, | |
| 153 | #' trim = TRUE, | |
| 154 | #' trim_padding = 8 | |
| 155 | #') | |
| 156 | #'render_sprite_overlay( | |
| 157 | #' dragon_clipped, | |
| 158 | #' image_overlay = dragon_emoji, | |
| 159 | #' overlay_coords = c(ncol(dragon_clipped) / 2, nrow(dragon_clipped) / 2), | |
| 160 | #' hjust = 0.5, | |
| 161 | #' vjust = 0.5, | |
| 162 | #' preview = TRUE | |
| 163 | #') | |
| 164 | #' | |
| 165 | #'# The same justification can be supplied as overlay_just = c(hjust, vjust): | |
| 166 | #'render_sprite_overlay( | |
| 167 | #' dragon_clipped, | |
| 168 | #' image_overlay = dragon_emoji, | |
| 169 | #' overlay_coords = c(ncol(dragon_clipped), nrow(dragon_clipped)), | |
| 170 | #' overlay_just = c(1, 1), | |
| 171 | #' preview = TRUE | |
| 172 | #') | |
| 173 | render_sprite_overlay = function( | |
| 174 | image, | |
| 175 | image_overlay = NULL, | |
| 176 | convert_overlay_colorspace = TRUE, | |
| 177 | alpha = NA, | |
| 178 | overlay_coords = c(1, 1), | |
| 179 | overlay_dims = NULL, | |
| 180 | overlay_anchor = "nw", | |
| 181 | overlay_just = NULL, | |
| 182 | hjust = NULL, | |
| 183 | vjust = NULL, | |
| 184 | preserve_channels = TRUE, | |
| 185 | filename = NULL, | |
| 186 | preview = FALSE | |
| 187 | ) { | |
| 188 | 19x | render_image_overlay_impl( |
| 189 | 19x | image = image, |
| 190 | 19x | image_overlay = image_overlay, |
| 191 | 19x | rescale_original = FALSE, |
| 192 | 19x | convert_overlay_colorspace = convert_overlay_colorspace, |
| 193 | 19x | alpha = alpha, |
| 194 | 19x | overlay_coords = overlay_coords, |
| 195 | 19x | overlay_dims = overlay_dims, |
| 196 | 19x | overlay_anchor = overlay_anchor, |
| 197 | 19x | overlay_just = overlay_just, |
| 198 | 19x | hjust = hjust, |
| 199 | 19x | vjust = vjust, |
| 200 | 19x | preserve_channels = preserve_channels, |
| 201 | 19x | filename = filename, |
| 202 | 19x | preview = preview |
| 203 | ) | |
| 204 | } | |
| 205 | ||
| 206 | #' @keywords internal | |
| 207 | render_image_overlay_impl = function( | |
| 208 | image, | |
| 209 | image_overlay = NULL, | |
| 210 | rescale_original = FALSE, | |
| 211 | convert_overlay_colorspace = TRUE, | |
| 212 | alpha = NA, | |
| 213 | overlay_coords = NULL, | |
| 214 | overlay_dims = NULL, | |
| 215 | overlay_anchor = "nw", | |
| 216 | overlay_just = NULL, | |
| 217 | hjust = NULL, | |
| 218 | vjust = NULL, | |
| 219 | preserve_channels = FALSE, | |
| 220 | filename = NULL, | |
| 221 | preview = FALSE | |
| 222 | ) { | |
| 223 | 22x | if (is.null(image_overlay)) { |
| 224 | ! | stop("Need to pass in image to image_overlay argument.") |
| 225 | } | |
| 226 | ||
| 227 | 22x | original_channels = { |
| 228 | 22x | image_dim = dim(image) |
| 229 | 22x | if (is.null(image_dim)) { |
| 230 | 22x | NA_integer_ |
| 231 | 21x | } else if (length(image_dim) == 2) { |
| 232 | ! | 1L |
| 233 | } else { | |
| 234 | 21x | image_dim[3] |
| 235 | } | |
| 236 | } | |
| 237 | ||
| 238 | # Load as rayimg (RGBA + attrs) | |
| 239 | 22x | image = ray_read_image( |
| 240 | 22x | image, |
| 241 | 22x | convert_to_array = TRUE, |
| 242 | 22x | reset_camera_settings = TRUE |
| 243 | ) | |
| 244 | 22x | image_colorspace = attr(image, "colorspace") |
| 245 | 22x | image_whitepoint = attr(image, "white_current") |
| 246 | 22x | image_overlay = ray_read_image( |
| 247 | 22x | image_overlay, |
| 248 | 22x | convert_to_array = TRUE, |
| 249 | 22x | reset_camera_settings = TRUE |
| 250 | ) | |
| 251 | 22x | if (convert_overlay_colorspace) { |
| 252 | 9x | image_overlay = render_convert_colorspace( |
| 253 | 9x | image_overlay, |
| 254 | 9x | to_mats = image_colorspace |
| 255 | ) | |
| 256 | } | |
| 257 | ||
| 258 | 22x | img_type = attr(image, "filetype") |
| 259 | 22x | over_type = attr(image_overlay, "filetype") |
| 260 | ||
| 261 | 22x | if (!is.null(overlay_dims)) { |
| 262 | ! | stopifnot(length(overlay_dims) >= 2) |
| 263 | ! | overlay_dims = as.integer(round(overlay_dims[1:2])) |
| 264 | ! | stopifnot(all(overlay_dims > 0)) |
| 265 | ! | image_overlay = render_resized(image_overlay, dims = overlay_dims) |
| 266 | } | |
| 267 | 22x | placement_mode = !is.null(overlay_coords) || |
| 268 | 22x | !is.null(overlay_dims) || |
| 269 | 22x | !is.null(overlay_just) || |
| 270 | 22x | !is.null(hjust) || |
| 271 | 22x | !is.null(vjust) |
| 272 | 22x | if (rescale_original) { |
| 273 | ! | target_dims = if (is.null(overlay_dims)) { |
| 274 | ! | dim(image_overlay)[1:2] |
| 275 | } else { | |
| 276 | ! | overlay_dims |
| 277 | } | |
| 278 | ! | if (!all(dim(image)[1:2] == target_dims)) { |
| 279 | ! | image = render_resized(image, dims = target_dims) |
| 280 | } | |
| 281 | 22x | } else if (!placement_mode) { |
| 282 | 3x | if (!all(dim(image)[1:2] == dim(image_overlay)[1:2])) { |
| 283 | 1x | image_overlay = render_resized(image_overlay, dims = dim(image)) |
| 284 | } | |
| 285 | } | |
| 286 | 22x | is_matrix_image = length(dim(image)) == 2 |
| 287 | 22x | is_matrix_image_overlay = length(dim(image_overlay)) == 2 |
| 288 | 22x | process_image = function(image_input) { |
| 289 | 44x | is_matrix_image = length(dim(image_input)) == 2 |
| 290 | 44x | if (is_matrix_image) { |
| 291 | ! | image_tmp = array(image_input, dim = c(dim(image_input), 4)) |
| 292 | ! | image_tmp[,, 4] = 1 |
| 293 | } else { | |
| 294 | 44x | if (dim(image_input)[3] == 2) { |
| 295 | #Greyscale with alpha | |
| 296 | ! | image_tmp = array(image_input[,, 1], dim = c(dim(image_input)[1:2], 4)) |
| 297 | ! | image_tmp[,, 4] = image_input[,, 2] |
| 298 | 44x | } else if (dim(image_input)[3] == 3) { |
| 299 | #RGB | |
| 300 | ! | image_tmp = array(1, dim = c(dim(image_input)[1:2], 4)) |
| 301 | ! | image_tmp[,, 4] = 1 |
| 302 | } else { | |
| 303 | 44x | image_tmp = image_input |
| 304 | } | |
| 305 | } | |
| 306 | 44x | return(image_tmp) |
| 307 | } | |
| 308 | 22x | image = process_image(image) |
| 309 | 22x | image_overlay = process_image(image_overlay) |
| 310 | ||
| 311 | 22x | if (!is.na(alpha)) { |
| 312 | 8x | stopifnot(alpha >= 0, alpha <= 1) |
| 313 | 8x | image_overlay[,, 4] = image_overlay[,, 4] * alpha |
| 314 | } | |
| 315 | ||
| 316 | 22x | Cb = image[,, 1:3] |
| 317 | 22x | Ab = image[,, 4] |
| 318 | ||
| 319 | # Place overlay on a blank canvas at the requested location, cropping to bounds | |
| 320 | 22x | if (is.null(overlay_coords)) { |
| 321 | 3x | overlay_coords = c(1, 1) |
| 322 | } | |
| 323 | 22x | stopifnot(length(overlay_coords) >= 2) |
| 324 | 22x | if (any(!is.finite(overlay_coords))) { |
| 325 | ! | stop("`overlay_coords` must be finite.") |
| 326 | } | |
| 327 | 22x | overlay_size = dim(image_overlay)[1:2] |
| 328 | 22x | use_overlay_just = !is.null(overlay_just) || |
| 329 | 22x | !is.null(hjust) || |
| 330 | 22x | !is.null(vjust) |
| 331 | 22x | if (use_overlay_just) { |
| 332 | 8x | if (is.null(overlay_just)) { |
| 333 | 7x | overlay_just = c(0, 0) |
| 334 | } | |
| 335 | 8x | if (!is.numeric(overlay_just) || length(overlay_just) < 2) { |
| 336 | ! | stop("`overlay_just` must be a numeric vector of length 2 or greater.") |
| 337 | } | |
| 338 | 8x | overlay_just = overlay_just[1:2] |
| 339 | 8x | if (!is.null(hjust)) { |
| 340 | 7x | if (!is.numeric(hjust) || length(hjust) != 1 || !is.finite(hjust)) { |
| 341 | ! | stop("`hjust` must be a finite numeric scalar.") |
| 342 | } | |
| 343 | 7x | overlay_just[1] = hjust |
| 344 | } | |
| 345 | 8x | if (!is.null(vjust)) { |
| 346 | 7x | if (!is.numeric(vjust) || length(vjust) != 1 || !is.finite(vjust)) { |
| 347 | ! | stop("`vjust` must be a finite numeric scalar.") |
| 348 | } | |
| 349 | 7x | overlay_just[2] = vjust |
| 350 | } | |
| 351 | 8x | if (any(!is.finite(overlay_just))) { |
| 352 | ! | stop("`overlay_just` must be finite.") |
| 353 | } | |
| 354 | 8x | start_col = as.integer(round( |
| 355 | 8x | overlay_coords[1] - overlay_just[1] * overlay_size[2] |
| 356 | )) | |
| 357 | 8x | start_row = as.integer(round( |
| 358 | 8x | overlay_coords[2] - overlay_just[2] * overlay_size[1] |
| 359 | )) | |
| 360 | } else { | |
| 361 | 14x | valid_anchors = c("nw", "ne", "sw", "se") |
| 362 | 14x | overlay_anchor = tolower(overlay_anchor) |
| 363 | 14x | if (!(overlay_anchor %in% valid_anchors)) { |
| 364 | ! | stop( |
| 365 | ! | "`overlay_anchor` must be one of: ", |
| 366 | ! | paste(valid_anchors, collapse = ", ") |
| 367 | ) | |
| 368 | } | |
| 369 | 14x | overlay_coords = as.integer(round(overlay_coords[1:2])) |
| 370 | 14x | start_row = overlay_coords[2] |
| 371 | 14x | start_col = overlay_coords[1] |
| 372 | 14x | if (overlay_anchor %in% c("sw", "se")) { |
| 373 | 6x | start_row = overlay_coords[2] - overlay_size[1] + 1 |
| 374 | } | |
| 375 | 14x | if (overlay_anchor %in% c("ne", "se")) { |
| 376 | 6x | start_col = overlay_coords[1] - overlay_size[2] + 1 |
| 377 | } | |
| 378 | } | |
| 379 | 22x | end_row = start_row + overlay_size[1] - 1 |
| 380 | 22x | end_col = start_col + overlay_size[2] - 1 |
| 381 | 22x | target_rows = seq(start_row, end_row) |
| 382 | 22x | target_cols = seq(start_col, end_col) |
| 383 | 22x | rows_in_bounds = target_rows >= 1 & target_rows <= dim(image)[1] |
| 384 | 22x | cols_in_bounds = target_cols >= 1 & target_cols <= dim(image)[2] |
| 385 | 22x | overlay_canvas = array(0, dim = dim(image)) |
| 386 | 22x | if (any(rows_in_bounds) && any(cols_in_bounds)) { |
| 387 | 22x | dest_rows = target_rows[rows_in_bounds] |
| 388 | 22x | dest_cols = target_cols[cols_in_bounds] |
| 389 | 22x | src_rows = which(rows_in_bounds) |
| 390 | 22x | src_cols = which(cols_in_bounds) |
| 391 | 22x | overlay_canvas[dest_rows, dest_cols, ] = image_overlay[ |
| 392 | 22x | src_rows, |
| 393 | 22x | src_cols, |
| 394 | , | |
| 395 | 22x | drop = FALSE |
| 396 | ] | |
| 397 | } | |
| 398 | 22x | image_overlay = overlay_canvas |
| 399 | ||
| 400 | 22x | Cf = image_overlay[,, 1:3] |
| 401 | 22x | Af = image_overlay[,, 4] |
| 402 | ||
| 403 | 22x | Af3 = array(Af, dim = c(dim(Af), 3)) |
| 404 | 22x | Ab3 = array(Ab, dim = c(dim(Ab), 3)) |
| 405 | ||
| 406 | 22x | Ao = pmin(pmax(Af + Ab * (1 - Af), 0), 1) |
| 407 | 22x | num = Cf * Af3 + Cb * Ab3 * array(1 - Af, dim = c(dim(Af), 3)) |
| 408 | ||
| 409 | 22x | eps = 1e-8 |
| 410 | 22x | Co_lin = num / array(pmax(Ao, eps), dim = c(dim(Ao), 3)) |
| 411 | ||
| 412 | # ensure fully transparent pixels are black | |
| 413 | 22x | if (any(Ao <= eps)) { |
| 414 | ! | m = Ao <= eps |
| 415 | ! | Co_lin[,, 1][m] = 0 |
| 416 | ! | Co_lin[,, 2][m] = 0 |
| 417 | ! | Co_lin[,, 3][m] = 0 |
| 418 | } | |
| 419 | ||
| 420 | 22x | composite_image = array(1, dim = dim(image)) |
| 421 | 22x | composite_image[,, 4] = Ao |
| 422 | 22x | composite_image[,, 1:3] = Co_lin |
| 423 | ||
| 424 | 22x | composite_image = ray_read_image( |
| 425 | 22x | composite_image, |
| 426 | 22x | assume_colorspace = image_colorspace, |
| 427 | 22x | assume_white = image_whitepoint, |
| 428 | 22x | source_linear = TRUE |
| 429 | ) | |
| 430 | 22x | if (isTRUE(preserve_channels) && identical(original_channels, 3L)) { |
| 431 | 14x | composite_image = composite_image[,, 1:3, drop = FALSE] |
| 432 | } | |
| 433 | 22x | handle_image_output(composite_image, filename = filename, preview = preview) |
| 434 | } |
| 1 | #'@title Matrix/Array Interpolation | |
| 2 | #' | |
| 3 | #'@description Given a series of X and Y coordinates and an array/matrix, interpolates the Z coordinate | |
| 4 | #'using bilinear interpolation. | |
| 5 | #' | |
| 6 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 7 | #'@param x X indices (or fractional index) to interpolate. | |
| 8 | #'@param y Y indices (or fractional index) to interpolate. | |
| 9 | #' | |
| 10 | #'@return Either a vector of values (if image is a matrix) or a list of interpolated values | |
| 11 | #'from each layer. | |
| 12 | #'@export | |
| 13 | #' | |
| 14 | #'@examples | |
| 15 | #'#if(interactive()){ | |
| 16 | #'#Interpolate a matrix | |
| 17 | #'interpolate_array(volcano,c(10,10.1,11),c(30,30.5,33)) | |
| 18 | #'#Interpolate a 3-layer array (returns list for each channel) | |
| 19 | #'interpolate_array(dragon,c(10,10.1,11),c(30,30.5,33)) | |
| 20 | #'#end} | |
| 21 | interpolate_array = function(image, x, y) { | |
| 22 | 14x | image = ray_read_image(image) #Always output RGBA array |
| 23 | #Check if file or image before below: | |
| 24 | 14x | is_matrix = length(dim(image)) == 2 |
| 25 | 14x | xy = matrix(c(x, y), nrow = length(x), ncol = 2) |
| 26 | ||
| 27 | 14x | if (is_matrix) { |
| 28 | 2x | return(apply(xy, 1, (function(x) rayinterp2(image, x[1], x[2])))) |
| 29 | } | |
| 30 | #Load and rotate images if image | |
| 31 | 12x | output = list() |
| 32 | 12x | if (dim(image)[3] == 2) { |
| 33 | 4x | output$grey = apply( |
| 34 | 4x | xy, |
| 35 | 4x | 1, |
| 36 | 4x | (function(x) rayinterp2(image[,, 1], x[1], x[2])) |
| 37 | ) | |
| 38 | 4x | output$alpha = apply( |
| 39 | 4x | xy, |
| 40 | 4x | 1, |
| 41 | 4x | (function(x) rayinterp2(image[,, 2], x[1], x[2])) |
| 42 | ) | |
| 43 | 8x | } else if (dim(image)[3] == 3) { |
| 44 | 4x | output$red = apply(xy, 1, (function(x) rayinterp2(image[,, 1], x[1], x[2]))) |
| 45 | 4x | output$green = apply( |
| 46 | 4x | xy, |
| 47 | 4x | 1, |
| 48 | 4x | (function(x) rayinterp2(image[,, 2], x[1], x[2])) |
| 49 | ) | |
| 50 | 4x | output$blue = apply( |
| 51 | 4x | xy, |
| 52 | 4x | 1, |
| 53 | 4x | (function(x) rayinterp2(image[,, 3], x[1], x[2])) |
| 54 | ) | |
| 55 | 4x | } else if (dim(image)[3] == 4) { |
| 56 | 4x | output$red = apply(xy, 1, (function(x) rayinterp2(image[,, 1], x[1], x[2]))) |
| 57 | 4x | output$green = apply( |
| 58 | 4x | xy, |
| 59 | 4x | 1, |
| 60 | 4x | (function(x) rayinterp2(image[,, 2], x[1], x[2])) |
| 61 | ) | |
| 62 | 4x | output$blue = apply( |
| 63 | 4x | xy, |
| 64 | 4x | 1, |
| 65 | 4x | (function(x) rayinterp2(image[,, 3], x[1], x[2])) |
| 66 | ) | |
| 67 | 4x | output$alpha = apply( |
| 68 | 4x | xy, |
| 69 | 4x | 1, |
| 70 | 4x | (function(x) rayinterp2(image[,, 4], x[1], x[2])) |
| 71 | ) | |
| 72 | } | |
| 73 | 12x | return(output) |
| 74 | } |
| 1 | #' Apply exposure compensation and ISO gain | |
| 2 | #' | |
| 3 | #' @param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 4 | #' @param exposure Default `0`. Exposure compensation in stops; applied directly to RGB values. | |
| 5 | #' @param iso Default `NA`. ISO gain to apply directly to RGB values. `NA` applies no ISO gain | |
| 6 | #' and preserves the current informational ISO metadata. | |
| 7 | #' @param auto Default `FALSE`. If `TRUE`, automatically add the exposure needed to | |
| 8 | #' place a luminance percentile at 1.0 for LDR display/output. `exposure` | |
| 9 | #' is then treated as an additional compensation value. | |
| 10 | #' @param percentile Default `0.99`. Luminance percentile used when `auto = TRUE`. | |
| 11 | #' Must be greater than 0 and less than or equal to 1. Use `1` for max luminance. | |
| 12 | #' @param verbose Default `FALSE`. If `TRUE` and `auto = TRUE`, print the | |
| 13 | #' automatically computed exposure adjustment. | |
| 14 | #' @param filename Default `NA`. Output path. | |
| 15 | #' @param preview Default `FALSE`. If `TRUE`, display the image. | |
| 16 | #' @param ... Additional args passed to [plot_image()] (when `preview=TRUE`) | |
| 17 | #' or to [ray_write_image()] (when `filename` is given). | |
| 18 | #' | |
| 19 | #' @return A `rayimg` RGBA array. | |
| 20 | #' @export | |
| 21 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 22 | #' # LDR/sRGB (auto): decodes to linear, applies EV, records camera metadata | |
| 23 | #' render_exposure(dragon, exposure = +1, preview = TRUE) | |
| 24 | #' # Force linear/HDR behavior | |
| 25 | #' render_exposure(dragon * 2, exposure = -1, preview = TRUE) | |
| 26 | render_exposure = function( | |
| 27 | image, | |
| 28 | exposure = 0, | |
| 29 | iso = NA, | |
| 30 | auto = FALSE, | |
| 31 | percentile = 0.99, | |
| 32 | verbose = FALSE, | |
| 33 | filename = NA, | |
| 34 | preview = FALSE, | |
| 35 | ... | |
| 36 | ) { | |
| 37 | 12x | img = ray_read_image(image) |
| 38 | 12x | exposure = rayimg_exposure_value(exposure) |
| 39 | 12x | if (length(iso) != 1L) { |
| 40 | ! | stop("render_exposure(): 'iso' must be a single positive number or NA.") |
| 41 | } | |
| 42 | 12x | iso_supplied = !is.na(iso) |
| 43 | 12x | if (iso_supplied) { |
| 44 | 8x | iso_to_apply = rayimg_iso_value(iso) |
| 45 | 8x | iso_metadata = iso_to_apply |
| 46 | } else { | |
| 47 | 4x | iso_to_apply = 100 |
| 48 | 4x | iso_metadata = rayimg_iso_value(attr(img, "iso", exact = TRUE)) |
| 49 | } | |
| 50 | 12x | if (!is.logical(auto) || length(auto) != 1L || is.na(auto)) { |
| 51 | ! | stop("render_exposure(): 'auto' must be TRUE or FALSE.") |
| 52 | } | |
| 53 | if ( | |
| 54 | 12x | !is.numeric(percentile) || |
| 55 | 12x | length(percentile) != 1L || |
| 56 | 12x | is.na(percentile) || |
| 57 | 12x | !is.finite(percentile) || |
| 58 | 12x | percentile <= 0 || |
| 59 | 12x | percentile > 1 |
| 60 | ) { | |
| 61 | ! | stop("render_exposure(): 'percentile' must be a number in (0, 1].") |
| 62 | } | |
| 63 | 12x | if (!is.logical(verbose) || length(verbose) != 1L || is.na(verbose)) { |
| 64 | ! | stop("render_exposure(): 'verbose' must be TRUE or FALSE.") |
| 65 | } | |
| 66 | ||
| 67 | 12x | current_exposure = rayimg_exposure_value(attr(img, "exposure", exact = TRUE)) |
| 68 | 12x | auto_exposure = 0 |
| 69 | 12x | target_luminance = NA_real_ |
| 70 | 12x | if (auto) { |
| 71 | 6x | img_values = unclass(img) |
| 72 | 6x | d = dim(img_values) |
| 73 | 6x | if (length(d) == 2L) { |
| 74 | 1x | luminance_values = as.numeric(img_values) |
| 75 | } else { | |
| 76 | 5x | channels = d[3L] |
| 77 | 5x | color_channels = if (channels %in% c(2L, 4L)) { |
| 78 | ! | seq_len(channels - 1L) |
| 79 | } else { | |
| 80 | 5x | seq_len(channels) |
| 81 | } | |
| 82 | 5x | if (length(color_channels) == 1L) { |
| 83 | ! | luminance_values = as.numeric(img_values[,, color_channels]) |
| 84 | } else { | |
| 85 | 5x | rgb_values = img_values[,, color_channels, drop = FALSE] |
| 86 | 5x | if (length(color_channels) >= 3L) { |
| 87 | 5x | rgb_values = rgb_values[,, seq_len(3L), drop = FALSE] |
| 88 | 5x | cs = attr(img, "colorspace", exact = TRUE) |
| 89 | 5x | luma_weights = if ( |
| 90 | 5x | is.list(cs) && |
| 91 | 5x | is.matrix(cs$rgb_to_xyz) && |
| 92 | 5x | all(dim(cs$rgb_to_xyz) >= c(2L, 3L)) |
| 93 | ) { | |
| 94 | 5x | as.numeric(cs$rgb_to_xyz[2L, seq_len(3L)]) |
| 95 | } else { | |
| 96 | ! | c(0.2126, 0.7152, 0.0722) |
| 97 | } | |
| 98 | 5x | luminance_values = |
| 99 | 5x | rgb_values[,, 1L] * |
| 100 | 5x | luma_weights[1L] + |
| 101 | 5x | rgb_values[,, 2L] * luma_weights[2L] + |
| 102 | 5x | rgb_values[,, 3L] * luma_weights[3L] |
| 103 | } else { | |
| 104 | ! | luminance_values = as.numeric(rgb_values) |
| 105 | } | |
| 106 | } | |
| 107 | } | |
| 108 | 6x | luminance_values = luminance_values[is.finite(luminance_values)] |
| 109 | 6x | if (length(luminance_values)) { |
| 110 | 6x | target_luminance = as.numeric(stats::quantile( |
| 111 | 6x | luminance_values, |
| 112 | 6x | probs = percentile, |
| 113 | 6x | names = FALSE |
| 114 | )) | |
| 115 | 6x | current_scale = iso_to_apply / 100 |
| 116 | 6x | if (target_luminance > 0 && current_scale > 0) { |
| 117 | 6x | auto_exposure = -log2(target_luminance * current_scale) |
| 118 | 6x | exposure = exposure + auto_exposure |
| 119 | } | |
| 120 | } | |
| 121 | 6x | if (verbose) { |
| 122 | 1x | message(sprintf( |
| 123 | 1x | "Auto exposure: %+.3f EV (luminance p%.3g: %.6g, ISO: %.6g)", |
| 124 | 1x | auto_exposure, |
| 125 | 1x | percentile, |
| 126 | 1x | target_luminance, |
| 127 | 1x | iso_to_apply |
| 128 | )) | |
| 129 | } | |
| 130 | } | |
| 131 | 12x | scale = (2^exposure) * (iso_to_apply / 100) |
| 132 | 12x | out_values = unclass(img) |
| 133 | 12x | if (!isTRUE(all.equal(scale, 1))) { |
| 134 | 12x | d = dim(out_values) |
| 135 | 12x | if (length(d) == 2L) { |
| 136 | 1x | out_values = out_values * scale |
| 137 | } else { | |
| 138 | 11x | channels = d[3L] |
| 139 | 11x | color_channels = if (channels %in% c(2L, 4L)) { |
| 140 | 1x | seq_len(channels - 1L) |
| 141 | } else { | |
| 142 | 10x | seq_len(channels) |
| 143 | } | |
| 144 | 11x | out_values[,, color_channels] = out_values[,, color_channels] * scale |
| 145 | } | |
| 146 | } | |
| 147 | ||
| 148 | 12x | out = rayimg( |
| 149 | 12x | out_values, |
| 150 | 12x | filetype = attr(img, "filetype", exact = TRUE), |
| 151 | 12x | source_linear = attr(img, "source_linear", exact = TRUE), |
| 152 | 12x | colorspace = attr(img, "colorspace", exact = TRUE), |
| 153 | 12x | white_current = attr(img, "white_current", exact = TRUE), |
| 154 | 12x | exposure = current_exposure + exposure, |
| 155 | 12x | iso = iso_metadata |
| 156 | ) | |
| 157 | 12x | out = ray_read_image(out) |
| 158 | 12x | handle_image_output(out, filename = filename, preview = preview) |
| 159 | } |
| 1 | #' @title Render Alpha Outline | |
| 2 | #' | |
| 3 | #' @description Creates a colored RGBA outline or halo from an image alpha | |
| 4 | #' channel or a supplied mask. When `image` is supplied, the original image is | |
| 5 | #' composited over the outline by default. | |
| 6 | #' | |
| 7 | #' @param image Default `NULL`. Image whose alpha channel will be used as the | |
| 8 | #' mask. If `mask` is supplied, `image` is only used for metadata. | |
| 9 | #' @param mask Default `NULL`. Optional logical or numeric matrix to use as the | |
| 10 | #' outline mask instead of `image` alpha. | |
| 11 | #' @param expand Default `0`. Number of pixels to expand the mask. | |
| 12 | #' @param edge_softness Default `0.1`. Width of the softened halo edge | |
| 13 | #' transition, in pixels. | |
| 14 | #' @param blur Default `0`. Gaussian blur standard deviation applied to the | |
| 15 | #' final outline alpha. | |
| 16 | #' @param gap_fill Default `1`. Maximum alpha gap width, in pixels, to bridge | |
| 17 | #' in the expanded outline alpha. This fills border-connected breaks and notches | |
| 18 | #' caused by discrete distance quantization. Set to `0` to disable. | |
| 19 | #' @param gap_fill_alpha_threshold Default `0.25`. Alpha threshold used to | |
| 20 | #' classify border gaps. Gap filling only modifies pixels below this threshold | |
| 21 | #' that are connected to the image exterior; enclosed interior holes surrounded | |
| 22 | #' by pixels at or above this threshold are left unchanged. | |
| 23 | #' @param color Default `"black"`. Outline color. | |
| 24 | #' @param alpha Default `1`. Overall outline alpha multiplier. | |
| 25 | #' @param pad Default `0`. Padding in pixels before computing the outline. If | |
| 26 | #' `NULL`, padding is computed from `expand`, `edge_softness`, and `blur`. | |
| 27 | #' @param composite Default `TRUE`. If `TRUE` and `image` is supplied, composite | |
| 28 | #' the outline below the original image. Set to `FALSE` to return the outline | |
| 29 | #' alone. | |
| 30 | #' @param filename Default `NULL`. File to save the image to. If `NULL` and | |
| 31 | #' `preview = FALSE`, returns the output image. | |
| 32 | #' @param preview Default `FALSE`. If `TRUE`, display the outline image. | |
| 33 | #' | |
| 34 | #' @return A `rayimg` RGBA output image with a `padding` attribute. | |
| 35 | #' @export | |
| 36 | #' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 37 | #'txt = render_text_image("\U0001F409", size = 120, background_alpha = 0) | |
| 38 | #'render_alpha_outline(txt, expand = 2, blur = 1, color = "purple") |> | |
| 39 | #' plot_image() | |
| 40 | #' | |
| 41 | #' #Make a rainbow outline | |
| 42 | #'render_alpha_outline(txt, expand = 2, blur = 0.1, color = "darkgreen") |> | |
| 43 | #' render_alpha_outline(expand = 2, blur = 0.1, color = "yellow") |> | |
| 44 | #' render_alpha_outline(expand = 2, blur = 0.1, color = "orange") |> | |
| 45 | #' render_alpha_outline(expand = 2, blur = 0.1, color = "red") |> | |
| 46 | #' render_alpha_outline(expand = 2, blur = 0.1, color = "purple") |> | |
| 47 | #' render_alpha_outline(expand = 2, blur = 0.1, color = "blue") |> | |
| 48 | #' plot_image() | |
| 49 | render_alpha_outline = function( | |
| 50 | image = NULL, | |
| 51 | mask = NULL, | |
| 52 | expand = 0, | |
| 53 | edge_softness = 0.1, | |
| 54 | blur = 0, | |
| 55 | gap_fill = 1, | |
| 56 | gap_fill_alpha_threshold = 0.25, | |
| 57 | color = "black", | |
| 58 | alpha = 1, | |
| 59 | pad = 0, | |
| 60 | composite = TRUE, | |
| 61 | filename = NULL, | |
| 62 | preview = FALSE | |
| 63 | ) { | |
| 64 | 9x | image_supplied = !is.null(image) |
| 65 | 9x | if (!image_supplied && is.null(mask)) { |
| 66 | ! | stop("Either `image` or `mask` must be provided.") |
| 67 | } | |
| 68 | 9x | if (!is.numeric(expand) || length(expand) != 1 || !is.finite(expand)) { |
| 69 | ! | stop("`expand` must be a finite numeric scalar.") |
| 70 | } | |
| 71 | if ( | |
| 72 | 9x | !is.numeric(edge_softness) || |
| 73 | 9x | length(edge_softness) != 1 || |
| 74 | 9x | !is.finite(edge_softness) |
| 75 | ) { | |
| 76 | ! | stop("`edge_softness` must be a finite numeric scalar.") |
| 77 | } | |
| 78 | 9x | if (!is.numeric(blur) || length(blur) != 1 || !is.finite(blur)) { |
| 79 | ! | stop("`blur` must be a finite numeric scalar.") |
| 80 | } | |
| 81 | 9x | if (!is.numeric(gap_fill) || length(gap_fill) != 1 || !is.finite(gap_fill)) { |
| 82 | ! | stop("`gap_fill` must be a finite numeric scalar.") |
| 83 | } | |
| 84 | if ( | |
| 85 | 9x | !is.numeric(gap_fill_alpha_threshold) || |
| 86 | 9x | length(gap_fill_alpha_threshold) != 1 || |
| 87 | 9x | !is.finite(gap_fill_alpha_threshold) |
| 88 | ) { | |
| 89 | ! | stop("`gap_fill_alpha_threshold` must be a finite numeric scalar.") |
| 90 | } | |
| 91 | 9x | if (!is.numeric(alpha) || length(alpha) != 1 || !is.finite(alpha)) { |
| 92 | ! | stop("`alpha` must be a finite numeric scalar.") |
| 93 | } | |
| 94 | 9x | if (!is.logical(composite) || length(composite) != 1 || is.na(composite)) { |
| 95 | ! | stop("`composite` must be `TRUE` or `FALSE`.") |
| 96 | } | |
| 97 | ||
| 98 | 9x | expand = max(0, expand) |
| 99 | 9x | edge_softness = max(.Machine$double.eps, edge_softness) |
| 100 | 9x | blur = max(0, blur) |
| 101 | 9x | gap_fill = as.integer(round(max(0, gap_fill))) |
| 102 | 9x | if (gap_fill_alpha_threshold < 0 || gap_fill_alpha_threshold > 1) { |
| 103 | ! | stop("`gap_fill_alpha_threshold` must be in [0,1].") |
| 104 | } | |
| 105 | 9x | alpha = min(max(alpha, 0), 1) |
| 106 | 9x | if (is.null(pad)) { |
| 107 | ! | pad = ceiling(expand + edge_softness + 3 * blur) |
| 108 | } | |
| 109 | 9x | pad = normalize_render_padding(pad) |
| 110 | ||
| 111 | 9x | if (!is.null(mask) && (is.null(dim(mask)) || length(dim(mask)) != 2)) { |
| 112 | ! | stop("`mask` must be a matrix.") |
| 113 | } | |
| 114 | 9x | if (!image_supplied) { |
| 115 | 7x | image = array(0, dim = c(nrow(mask), ncol(mask), 4)) |
| 116 | } | |
| 117 | 9x | source_image = ray_read_image(image, convert_to_array = TRUE) |
| 118 | 9x | padded_source = render_padding( |
| 119 | 9x | source_image, |
| 120 | 9x | pad = pad, |
| 121 | 9x | color = "black", |
| 122 | 9x | alpha = 0 |
| 123 | ) | |
| 124 | ||
| 125 | 9x | if (is.null(mask)) { |
| 126 | 2x | alpha_mask = unclass(padded_source[,, 4]) |
| 127 | } else { | |
| 128 | 7x | alpha_mask = render_padding(mask, pad = pad, color = "black") |
| 129 | 7x | alpha_mask = unclass(alpha_mask) |
| 130 | } | |
| 131 | 9x | alpha_mask[alpha_mask > 0] = 1 |
| 132 | 9x | alpha_mask[alpha_mask <= 0] = 0 |
| 133 | ||
| 134 | 9x | if (expand > 0) { |
| 135 | 7x | booldistance = render_boolean_distance(alpha_mask) |
| 136 | 7x | inner = expand - edge_softness |
| 137 | 7x | outer = expand + edge_softness |
| 138 | 7x | halo_alpha = matrix( |
| 139 | 7x | 0, |
| 140 | 7x | nrow = nrow(alpha_mask), |
| 141 | 7x | ncol = ncol(alpha_mask) |
| 142 | ) | |
| 143 | 7x | halo_alpha[booldistance <= inner] = 1 |
| 144 | 7x | band = booldistance > inner & booldistance < outer |
| 145 | 7x | halo_alpha[band] = (outer - booldistance[band]) / (outer - inner) |
| 146 | } else { | |
| 147 | 2x | halo_alpha = alpha_mask |
| 148 | } | |
| 149 | 9x | if (gap_fill > 0 && expand > 0) { |
| 150 | 6x | halo_alpha = fill_alpha_gaps( |
| 151 | 6x | halo_alpha, |
| 152 | 6x | max_gap = gap_fill, |
| 153 | 6x | alpha_threshold = gap_fill_alpha_threshold |
| 154 | ) | |
| 155 | } | |
| 156 | ||
| 157 | 9x | halo_color = convert_color(color, single = TRUE) |
| 158 | 9x | halo_image = array(0, dim = c(dim(alpha_mask), 4)) |
| 159 | 9x | halo_image[,, 1] = halo_color[1] |
| 160 | 9x | halo_image[,, 2] = halo_color[2] |
| 161 | 9x | halo_image[,, 3] = halo_color[3] |
| 162 | 9x | halo_image[,, 4] = halo_alpha * alpha |
| 163 | ||
| 164 | 9x | halo_image = rayimg( |
| 165 | 9x | halo_image, |
| 166 | 9x | filetype = attr(padded_source, "filetype"), |
| 167 | 9x | source_linear = attr(padded_source, "source_linear"), |
| 168 | 9x | colorspace = attr(padded_source, "colorspace"), |
| 169 | 9x | white_current = attr(padded_source, "white_current"), |
| 170 | 9x | exposure = attr(padded_source, "exposure", exact = TRUE), |
| 171 | 9x | iso = attr(padded_source, "iso", exact = TRUE) |
| 172 | ) | |
| 173 | ||
| 174 | 9x | if (blur > 0) { |
| 175 | ! | halo_image = render_convolution( |
| 176 | ! | halo_image, |
| 177 | ! | kernel = generate_2d_gaussian( |
| 178 | ! | sd = blur, |
| 179 | ! | dim = 31, |
| 180 | ! | width = 30 |
| 181 | ), | |
| 182 | ! | include_alpha = TRUE, |
| 183 | ! | preview = FALSE |
| 184 | ) | |
| 185 | ! | halo_image[,, 1] = halo_color[1] |
| 186 | ! | halo_image[,, 2] = halo_color[2] |
| 187 | ! | halo_image[,, 3] = halo_color[3] |
| 188 | } | |
| 189 | 9x | attr(halo_image, "padding") = pad |
| 190 | 9x | if (composite && image_supplied) { |
| 191 | 1x | if (!all(dim(padded_source)[1:2] == dim(halo_image)[1:2])) { |
| 192 | ! | stop( |
| 193 | ! | "`image` and `mask` must have matching dimensions when ", |
| 194 | ! | "`composite = TRUE`." |
| 195 | ) | |
| 196 | } | |
| 197 | 1x | halo_image = composite_alpha_outline_image( |
| 198 | 1x | halo_image = halo_image, |
| 199 | 1x | source_image = padded_source |
| 200 | ) | |
| 201 | 1x | attr(halo_image, "padding") = pad |
| 202 | } | |
| 203 | 9x | handle_image_output(halo_image, filename = filename, preview = preview) |
| 204 | } | |
| 205 | ||
| 206 | #' @title Composite Alpha Outline Image | |
| 207 | #' | |
| 208 | #' @description Internal helper that composites the original source image over | |
| 209 | #' the generated outline using source-over alpha compositing. The outline is the | |
| 210 | #' backdrop and the source image is the foreground. Colors are treated as | |
| 211 | #' straight, non-premultiplied alpha, using | |
| 212 | #' `Ao = Af + Ab * (1 - Af)` and | |
| 213 | #' `Co = (Cf * Af + Cb * Ab * (1 - Af)) / Ao`. Fully transparent output pixels | |
| 214 | #' are forced to black to avoid carrying arbitrary color values. | |
| 215 | #' @param halo_image RGBA outline image used as the compositing backdrop. | |
| 216 | #' @param source_image RGBA source image, padded to the same dimensions as | |
| 217 | #' `halo_image`, used as the compositing foreground. | |
| 218 | #' @return A `rayimg` RGBA image containing the source composited over the | |
| 219 | #' outline. | |
| 220 | #' | |
| 221 | #' @keywords internal | |
| 222 | composite_alpha_outline_image = function(halo_image, source_image) { | |
| 223 | 1x | halo_array = unclass(halo_image) |
| 224 | 1x | source_array = unclass(source_image) |
| 225 | ||
| 226 | 1x | Cf = source_array[,, 1:3] |
| 227 | 1x | Af = source_array[,, 4] |
| 228 | 1x | Cb = halo_array[,, 1:3] |
| 229 | 1x | Ab = halo_array[,, 4] |
| 230 | ||
| 231 | 1x | Af3 = array(Af, dim = c(dim(Af), 3)) |
| 232 | 1x | Ab3 = array(Ab, dim = c(dim(Ab), 3)) |
| 233 | 1x | Ao = pmin(pmax(Af + Ab * (1 - Af), 0), 1) |
| 234 | 1x | num = Cf * Af3 + Cb * Ab3 * array(1 - Af, dim = c(dim(Af), 3)) |
| 235 | ||
| 236 | 1x | eps = 1e-8 |
| 237 | 1x | Co = num / array(pmax(Ao, eps), dim = c(dim(Ao), 3)) |
| 238 | 1x | if (any(Ao <= eps)) { |
| 239 | 1x | transparent = Ao <= eps |
| 240 | 1x | Co[,, 1][transparent] = 0 |
| 241 | 1x | Co[,, 2][transparent] = 0 |
| 242 | 1x | Co[,, 3][transparent] = 0 |
| 243 | } | |
| 244 | ||
| 245 | 1x | output = array(0, dim = dim(halo_array)) |
| 246 | 1x | output[,, 1:3] = Co |
| 247 | 1x | output[,, 4] = Ao |
| 248 | 1x | rayimg( |
| 249 | 1x | output, |
| 250 | 1x | filetype = attr(halo_image, "filetype"), |
| 251 | 1x | source_linear = attr(halo_image, "source_linear"), |
| 252 | 1x | colorspace = attr(halo_image, "colorspace"), |
| 253 | 1x | white_current = attr(halo_image, "white_current"), |
| 254 | 1x | exposure = attr(halo_image, "exposure", exact = TRUE), |
| 255 | 1x | iso = attr(halo_image, "iso", exact = TRUE) |
| 256 | ) | |
| 257 | } | |
| 258 | ||
| 259 | #' @title Fill Border Alpha Gaps | |
| 260 | #' | |
| 261 | #' @description Internal post-process for small distance-transform | |
| 262 | #' quantization artifacts on outline edges. The algorithm first calls | |
| 263 | #' `find_border_alpha_gaps()` to mark only low-alpha pixels connected to the | |
| 264 | #' image exterior. It then scans horizontal, vertical, and diagonal directions. | |
| 265 | #' For each gap width up to `max_gap`, `offset_alpha()` samples the alpha values | |
| 266 | #' on opposite sides of each candidate gap. A candidate pixel is raised to the | |
| 267 | #' weaker of the two neighboring alpha values, and only if that pixel was marked | |
| 268 | #' as border-connected. This bridges edge notches while leaving enclosed | |
| 269 | #' interior holes unchanged. | |
| 270 | #' @param alpha Numeric alpha matrix. | |
| 271 | #' @param max_gap Default `1`. Maximum low-alpha run width, in pixels, to bridge. | |
| 272 | #' @param alpha_threshold Default `0.25`. Alpha threshold used to decide which | |
| 273 | #' pixels are low-alpha border gaps. | |
| 274 | #' @return Numeric alpha matrix with eligible border gaps filled. | |
| 275 | #' | |
| 276 | #' @keywords internal | |
| 277 | fill_alpha_gaps = function(alpha, max_gap = 1, alpha_threshold = 0.25) { | |
| 278 | 10x | max_gap = as.integer(round(max_gap)) |
| 279 | 10x | if (max_gap <= 0) { |
| 280 | ! | return(alpha) |
| 281 | } | |
| 282 | 10x | alpha = pmin(pmax(alpha, 0), 1) |
| 283 | 10x | border_gap = find_border_alpha_gaps(alpha, alpha_threshold) |
| 284 | 10x | if (!any(border_gap)) { |
| 285 | 2x | return(alpha) |
| 286 | } | |
| 287 | 8x | directions = list( |
| 288 | 8x | c(0L, 1L), |
| 289 | 8x | c(1L, 0L), |
| 290 | 8x | c(1L, 1L), |
| 291 | 8x | c(1L, -1L) |
| 292 | ) | |
| 293 | 8x | for (direction in directions) { |
| 294 | 32x | for (gap_width in seq_len(max_gap)) { |
| 295 | 40x | for (left_distance in seq_len(gap_width)) { |
| 296 | 48x | right_distance = gap_width + 1L - left_distance |
| 297 | 48x | left_alpha = offset_alpha( |
| 298 | 48x | alpha, |
| 299 | 48x | row_offset = -left_distance * direction[1], |
| 300 | 48x | col_offset = -left_distance * direction[2] |
| 301 | ) | |
| 302 | 48x | right_alpha = offset_alpha( |
| 303 | 48x | alpha, |
| 304 | 48x | row_offset = right_distance * direction[1], |
| 305 | 48x | col_offset = right_distance * direction[2] |
| 306 | ) | |
| 307 | 48x | candidate_alpha = pmin(left_alpha, right_alpha) |
| 308 | 48x | alpha[border_gap] = pmax(alpha[border_gap], candidate_alpha[border_gap]) |
| 309 | } | |
| 310 | } | |
| 311 | } | |
| 312 | 8x | pmin(pmax(alpha, 0), 1) |
| 313 | } | |
| 314 | ||
| 315 | #' @title Find Border Alpha Gaps | |
| 316 | #' | |
| 317 | #' @description Internal helper that classifies which low-alpha pixels are part | |
| 318 | #' of the exterior border region. Pixels below `alpha_threshold` are considered | |
| 319 | #' low alpha. The algorithm starts from low-alpha pixels on the image boundary | |
| 320 | #' and performs an 8-connected flood fill through other low-alpha pixels. | |
| 321 | #' Low-alpha regions enclosed by pixels at or above `alpha_threshold` are not | |
| 322 | #' reached, so they are protected from `fill_alpha_gaps()`. | |
| 323 | #' @param alpha Numeric alpha matrix. | |
| 324 | #' @param alpha_threshold Default `0.25`. Pixels below this alpha are considered | |
| 325 | #' low-alpha gap pixels. | |
| 326 | #' @return Logical matrix marking low-alpha pixels connected to the image | |
| 327 | #' exterior. | |
| 328 | #' | |
| 329 | #' @keywords internal | |
| 330 | find_border_alpha_gaps = function(alpha, alpha_threshold = 0.25) { | |
| 331 | 10x | alpha_threshold = min(max(alpha_threshold, 0), 1) |
| 332 | 10x | low_alpha = alpha < alpha_threshold |
| 333 | 10x | border_gap = matrix(FALSE, nrow = nrow(alpha), ncol = ncol(alpha)) |
| 334 | 10x | if (!any(low_alpha)) { |
| 335 | ! | return(border_gap) |
| 336 | } | |
| 337 | ||
| 338 | 10x | border = matrix(FALSE, nrow = nrow(alpha), ncol = ncol(alpha)) |
| 339 | 10x | border[1, ] = TRUE |
| 340 | 10x | border[nrow(alpha), ] = TRUE |
| 341 | 10x | border[, 1] = TRUE |
| 342 | 10x | border[, ncol(alpha)] = TRUE |
| 343 | 10x | border_indices = which(low_alpha & border) |
| 344 | 10x | if (length(border_indices) == 0) { |
| 345 | 2x | return(border_gap) |
| 346 | } | |
| 347 | ||
| 348 | 8x | nr = nrow(alpha) |
| 349 | 8x | nc = ncol(alpha) |
| 350 | 8x | queue = integer(length(alpha)) |
| 351 | 8x | queue[seq_along(border_indices)] = border_indices |
| 352 | 8x | queue_start = 1L |
| 353 | 8x | queue_end = length(border_indices) |
| 354 | 8x | border_gap[border_indices] = TRUE |
| 355 | ||
| 356 | 37x | while (queue_start <= queue_end) { |
| 357 | 29x | idx = queue[queue_start] |
| 358 | 29x | queue_start = queue_start + 1L |
| 359 | 29x | row = ((idx - 1L) %% nr) + 1L |
| 360 | 29x | col = ((idx - 1L) %/% nr) + 1L |
| 361 | ||
| 362 | 29x | row_min = max(1L, row - 1L) |
| 363 | 29x | row_max = min(nr, row + 1L) |
| 364 | 29x | col_min = max(1L, col - 1L) |
| 365 | 29x | col_max = min(nc, col + 1L) |
| 366 | 29x | for (neighbor_row in row_min:row_max) { |
| 367 | 55x | for (neighbor_col in col_min:col_max) { |
| 368 | 128x | if (neighbor_row == row && neighbor_col == col) { |
| 369 | 29x | next |
| 370 | } | |
| 371 | 99x | neighbor_idx = neighbor_row + (neighbor_col - 1L) * nr |
| 372 | 99x | if (low_alpha[neighbor_idx] && !border_gap[neighbor_idx]) { |
| 373 | 2x | queue_end = queue_end + 1L |
| 374 | 2x | queue[queue_end] = neighbor_idx |
| 375 | 2x | border_gap[neighbor_idx] = TRUE |
| 376 | } | |
| 377 | } | |
| 378 | } | |
| 379 | } | |
| 380 | 8x | border_gap |
| 381 | } | |
| 382 | ||
| 383 | #' @title Offset Alpha Matrix | |
| 384 | #' | |
| 385 | #' @description Internal shift helper used by `fill_alpha_gaps()`. It returns a | |
| 386 | #' same-size alpha matrix shifted by integer row and column offsets, filling | |
| 387 | #' newly exposed pixels with zero instead of wrapping. This lets the gap-filling | |
| 388 | #' scan compare pixels a fixed distance away on opposite sides of a candidate | |
| 389 | #' gap. | |
| 390 | #' @param alpha Numeric alpha matrix. | |
| 391 | #' @param row_offset Integer row offset. Positive values sample from rows below | |
| 392 | #' each output pixel. | |
| 393 | #' @param col_offset Integer column offset. Positive values sample from columns | |
| 394 | #' to the right of each output pixel. | |
| 395 | #' @return Numeric alpha matrix with the same dimensions as `alpha`. | |
| 396 | #' | |
| 397 | #' @keywords internal | |
| 398 | offset_alpha = function(alpha, row_offset, col_offset) { | |
| 399 | 96x | nr = nrow(alpha) |
| 400 | 96x | nc = ncol(alpha) |
| 401 | 96x | output = matrix(0, nrow = nr, ncol = nc) |
| 402 | ||
| 403 | 96x | row_start = max(1L, 1L - row_offset) |
| 404 | 96x | row_end = min(nr, nr - row_offset) |
| 405 | 96x | col_start = max(1L, 1L - col_offset) |
| 406 | 96x | col_end = min(nc, nc - col_offset) |
| 407 | 96x | if (row_start > row_end || col_start > col_end) { |
| 408 | 48x | return(output) |
| 409 | } | |
| 410 | 48x | dest_rows = row_start:row_end |
| 411 | 48x | dest_cols = col_start:col_end |
| 412 | ||
| 413 | 48x | output[dest_rows, dest_cols] = alpha[ |
| 414 | 48x | dest_rows + row_offset, |
| 415 | 48x | dest_cols + col_offset, |
| 416 | 48x | drop = FALSE |
| 417 | ] | |
| 418 | 48x | output |
| 419 | } |
| 1 | #'@title Render Convolution FFT | |
| 2 | #' | |
| 3 | #'@description Takes an image and applies a convolution operation to it, using | |
| 4 | #'a user-supplied or built-in kernel. This function uses a fast Fourier transform and | |
| 5 | #'does the convolution in the frequency domain, so it should be faster for much larger kernels. | |
| 6 | #' | |
| 7 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 8 | #'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead. | |
| 9 | #'@param kernel Default `gaussian`. By default, an 11x11 Gaussian kernel with a mean | |
| 10 | #'of `0` and a standard deviation of `1`, running from `-kernel_extent` to `kernel_extent`. | |
| 11 | #'If numeric, this will be the standard deviation of the normal distribution. If a | |
| 12 | #'matrix, it will be used directly as the convolution kernel (but resized always to be an odd number | |
| 13 | #'of columns and rows). | |
| 14 | #'@param kernel_dim Default `c(11, 11)`. The dimension of the `gaussian` kernel. Ignored | |
| 15 | #'if user specifies their own kernel. | |
| 16 | #'@param kernel_extent Default `3`. Extent over which to calculate the kernel. | |
| 17 | #'@param absolute Default `TRUE`. Whether to take the absolute value of the convolution. | |
| 18 | #'@param pad Default `50`. Amount to pad the image to remove edge effects. | |
| 19 | #'@param include_alpha Default `FALSE`. Whether to include the alpha channel in the convolution. | |
| 20 | #'@param preview Default `FALSE`. Whether to plot the convolved image, or just to return the values. | |
| 21 | #'@return A `rayimg` RGBA array. | |
| 22 | #'@export | |
| 23 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 24 | #'#Perform a convolution with the default gaussian kernel | |
| 25 | #'plot_image(dragon) | |
| 26 | #'#Perform a convolution with the default gaussian kernel | |
| 27 | #'render_convolution_fft(dragon, kernel=0.1, preview = TRUE) | |
| 28 | #'#Increase the width of the kernel | |
| 29 | #'render_convolution_fft(dragon, kernel = 2, kernel_dim=21,kernel_extent=6, preview = TRUE) | |
| 30 | #'#Use a built-in kernel: | |
| 31 | #'render_convolution_fft(dragon, kernel = generate_2d_exponential(falloff=2, dim=31, width=21), | |
| 32 | #' preview = TRUE) | |
| 33 | #'#Perform edge detection | |
| 34 | #'edge = matrix(c(-1,-1,-1,-1,8,-1,-1,-1,-1),3,3) | |
| 35 | #'render_convolution_fft(render_bw(dragon), kernel = edge, preview = TRUE) | |
| 36 | #'#Perform edge detection with Sobel matrices | |
| 37 | #'sobel1 = matrix(c(1,2,1,0,0,0,-1,-2,-1),3,3) | |
| 38 | #'sobel2 = matrix(c(1,2,1,0,0,0,-1,-2,-1),3,3,byrow=TRUE) | |
| 39 | #'sob1 = render_convolution_fft(render_bw(dragon), kernel = sobel1) | |
| 40 | #'sob2 = render_convolution_fft(render_bw(dragon), kernel = sobel2) | |
| 41 | #'sob_all = sob1 + sob2 | |
| 42 | #'plot_image(sob1) | |
| 43 | #'plot_image(sob2) | |
| 44 | #'plot_image(sob_all) | |
| 45 | #'#We can also apply this function to matrices: | |
| 46 | #'volcano |> image() | |
| 47 | #'volcano |> | |
| 48 | #' render_convolution_fft(kernel=generate_2d_gaussian(sd=1,dim=31)) |> | |
| 49 | #' image() | |
| 50 | #'# Because this function uses the fast Fourier transform, large kernels will be much faster | |
| 51 | #'# than the same size kernels in [render_convolution()] | |
| 52 | #' render_convolution_fft(dragon, kernel_dim = c(200,200) , preview = TRUE) | |
| 53 | #'#Use a custom kernel (in this case, an X shape): | |
| 54 | #'custom = diag(10) + (diag(10)[,10:1]) | |
| 55 | #'#Normalize | |
| 56 | #'custom = custom / 20 | |
| 57 | #'plot_image(custom*20) | |
| 58 | #'render_convolution_fft(dragon, kernel = custom, preview = TRUE) | |
| 59 | render_convolution_fft = function( | |
| 60 | image, | |
| 61 | kernel = "gaussian", | |
| 62 | kernel_dim = c(11, 11), | |
| 63 | kernel_extent = 3, | |
| 64 | absolute = TRUE, | |
| 65 | pad = 50, | |
| 66 | include_alpha = FALSE, | |
| 67 | filename = NULL, | |
| 68 | preview = FALSE | |
| 69 | ) { | |
| 70 | ! | shift_fft = function(fft_mat) { |
| 71 | ! | nr = dim(fft_mat)[1] |
| 72 | ! | nc = dim(fft_mat)[2] |
| 73 | ! | if (nr %% 2 == 0) { |
| 74 | ! | nr_mid1 = nr / 2 |
| 75 | ! | nr_mid2 = nr / 2 + 1 |
| 76 | } else { | |
| 77 | ! | nr_mid1 = floor(nr / 2) |
| 78 | ! | nr_mid2 = floor(nr / 2) + 1 |
| 79 | } | |
| 80 | ! | if (nc %% 2 == 0) { |
| 81 | ! | nc_mid1 = nc / 2 |
| 82 | ! | nc_mid2 = nc / 2 + 1 |
| 83 | } else { | |
| 84 | ! | nc_mid1 = floor(nc / 2) |
| 85 | ! | nc_mid2 = floor(nc / 2) + 1 |
| 86 | } | |
| 87 | ! | fftcorn_nw = fft_mat[1:nr_mid1, 1:nc_mid1] |
| 88 | ! | fftcorn_ne = fft_mat[1:nr_mid1, nc_mid2:nc] |
| 89 | ! | fftcorn_sw = fft_mat[nr_mid2:nr, 1:nc_mid1] |
| 90 | ! | fftcorn_se = fft_mat[nr_mid2:nr, nc_mid2:nc] |
| 91 | ! | rbind(cbind(fftcorn_se, fftcorn_sw), cbind(fftcorn_ne, fftcorn_nw)) |
| 92 | } | |
| 93 | ! | temp_image = ray_read_image( |
| 94 | ! | image, |
| 95 | ! | convert_to_array = FALSE, |
| 96 | ! | reset_camera_settings = TRUE |
| 97 | ) | |
| 98 | ! | colorspace = attr(temp_image, "colorspace") |
| 99 | ! | whitepoint = attr(temp_image, "white_current") |
| 100 | ||
| 101 | #Check if file or image before below: | |
| 102 | ! | if (is.character(kernel)) { |
| 103 | ! | if (kernel == "gaussian") { |
| 104 | ! | kernel = generate_2d_gaussian(1, 1, kernel_dim, kernel_extent) |
| 105 | } | |
| 106 | } | |
| 107 | ! | if (is.numeric(kernel) && length(kernel) == 1) { |
| 108 | ! | kernel = generate_2d_gaussian(kernel, 1, kernel_dim, kernel_extent) |
| 109 | } | |
| 110 | ||
| 111 | ! | if (any(dim(kernel)[1:2] != dim(temp_image)[1:2])) { |
| 112 | ! | if (all(dim(kernel)[1:2] <= dim(temp_image)[1:2])) { |
| 113 | ! | kernel = expand_to_fit(dim(temp_image)[1:2], kernel) |
| 114 | } else { | |
| 115 | ! | stop("kernel can't have greater dimensions than image") |
| 116 | } | |
| 117 | } | |
| 118 | ! | if (pad != 0) { |
| 119 | ! | temp_image = add_multi_padding(temp_image, pad) |
| 120 | ! | kernel = add_multi_padding(kernel, pad) |
| 121 | } | |
| 122 | ||
| 123 | ! | if (any(dim(kernel) > dim(temp_image)[1:2] * 2 + 1)) { |
| 124 | ! | stop( |
| 125 | ! | "kernel dimensions: ", |
| 126 | ! | paste0(dim(kernel), collapse = "x"), |
| 127 | ! | " must not be greater than 2x image dimensions: ", |
| 128 | ! | paste0(dim(temp_image)[1:2], collapse = "x"), |
| 129 | ! | ", plus one (here, ", |
| 130 | ! | paste0(dim(temp_image)[1:2] * 2 + 1, collapse = "x"), |
| 131 | ")." | |
| 132 | ) | |
| 133 | } | |
| 134 | ||
| 135 | ! | temp_fft = temp_image |
| 136 | ! | if (length(dim(temp_image)) == 2) { |
| 137 | ! | temp_fft = stats::fft(temp_image) |
| 138 | ! | } else if (length(dim(temp_image)) == 3) { |
| 139 | ! | channels = dim(temp_image)[3] |
| 140 | ! | if (!include_alpha && (channels == 2 || channels == 4)) { |
| 141 | ! | max_channel = channels - 1 |
| 142 | } else { | |
| 143 | ! | max_channel = channels |
| 144 | } | |
| 145 | ! | for (i in seq_len(max_channel)) { |
| 146 | ! | temp_fft[,, i] = stats::fft(temp_image[,, i]) |
| 147 | } | |
| 148 | } | |
| 149 | ||
| 150 | ! | kernal_fft = stats::fft(kernel) |
| 151 | ! | vals = Re(temp_fft) |
| 152 | ! | if (length(dim(temp_fft)) == 3) { |
| 153 | ! | channels = dim(temp_image)[3] |
| 154 | ! | if (!include_alpha && (channels == 2 || channels == 4)) { |
| 155 | ! | max_channel = channels - 1 |
| 156 | } else { | |
| 157 | ! | max_channel = channels |
| 158 | } | |
| 159 | ! | for (i in seq_len(max_channel)) { |
| 160 | ! | vals[,, i] = shift_fft( |
| 161 | ! | Re(stats::fft(temp_fft[,, i] * kernal_fft, inverse = TRUE)) / |
| 162 | ! | length(vals[,, i]) |
| 163 | ) | |
| 164 | } | |
| 165 | } else { | |
| 166 | ! | vals = shift_fft( |
| 167 | ! | Re(stats::fft(temp_fft * kernal_fft, inverse = TRUE)) / length(vals) |
| 168 | ) | |
| 169 | } | |
| 170 | ! | if (absolute) { |
| 171 | ! | vals = abs(vals) |
| 172 | } | |
| 173 | ||
| 174 | ! | if (pad != 0) { |
| 175 | ! | vals = trim_padding(vals, pad) |
| 176 | } | |
| 177 | ! | final_image = ray_read_image( |
| 178 | ! | vals, |
| 179 | ! | assume_colorspace = colorspace, |
| 180 | ! | assume_white = whitepoint, |
| 181 | ! | source_linear = TRUE |
| 182 | ) | |
| 183 | ! | handle_image_output(final_image, filename = filename, preview = preview) |
| 184 | } |
| 1 | #'@title Resize Image | |
| 2 | #' | |
| 3 | #'@description Resizes an image or a matrix, using bilinear interpolation. | |
| 4 | #' | |
| 5 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 6 | #'@param mag Default `1`. Amount to magnify the image, preserving aspect ratio. Overridden if | |
| 7 | #'`dim` is not `NULL`. | |
| 8 | #'@param dims Default `NULL`. Exact resized dimensions. | |
| 9 | #'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead. | |
| 10 | #'@param preview Default `FALSE`. Whether to plot the convolved image, or just to return the values. | |
| 11 | #'@param method Default `trilinear`. Filters to up/downsample the image. Options: `bilinear`, `box`, `trilinear`, | |
| 12 | #' `catmull`, `mitchell`. | |
| 13 | #'@return A `rayimg` RGBA array. | |
| 14 | #'@export | |
| 15 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 16 | #'#Plot the image with a title | |
| 17 | #'dragon |> | |
| 18 | #' render_title("Dragon", title_offset=c(10,10), title_bar_color="black", | |
| 19 | #' title_size=20, title_color = "white") |> | |
| 20 | #' plot_image() | |
| 21 | #'#Half of the resolution | |
| 22 | #'render_resized(dragon, mag = 1/2) |> | |
| 23 | #' render_title("Dragon (half res)", title_offset=c(5,5), title_bar_color="black", | |
| 24 | #' title_size=10, title_color = "white") |> | |
| 25 | #' plot_image() | |
| 26 | #'#Double the resolution | |
| 27 | #'render_resized(dragon, mag = 2) |> | |
| 28 | #' render_title("Dragon (2x res)", title_offset=c(20,20), title_bar_color="black", | |
| 29 | #' title_size=40, title_color = "white") |> | |
| 30 | #' plot_image() | |
| 31 | #'#Specify the exact resulting dimensions | |
| 32 | #'render_resized(dragon, dim = c(160,320)) |> | |
| 33 | #' render_title("Dragon (custom size)", title_offset=c(10,10), title_bar_color="black", | |
| 34 | #' title_size=20, title_color = "white") |> | |
| 35 | #' plot_image() | |
| 36 | render_resized = function( | |
| 37 | image, | |
| 38 | mag = 1, | |
| 39 | dims = NULL, | |
| 40 | filename = NULL, | |
| 41 | preview = FALSE, | |
| 42 | method = "tri" | |
| 43 | ) { | |
| 44 | 2x | temp_image = ray_read_image(image) |
| 45 | 2x | orig_dims = dim(temp_image)[1:2] |
| 46 | 2x | downscale = if (!is.null(dims)) { |
| 47 | 2x | any(dims[1:2] < orig_dims) |
| 48 | } else { | |
| 49 | ! | isTRUE(mag < 1) |
| 50 | } | |
| 51 | 2x | use_bilinear = method %in% c("bi", "bilinear") && !downscale |
| 52 | 2x | if (!use_bilinear && method %in% c("bi", "bilinear")) { |
| 53 | ! | method = "box" |
| 54 | } | |
| 55 | #Check if file or image before below: | |
| 56 | 2x | imagetype = attr(temp_image, "filetype") |
| 57 | 2x | img_source_linear = attr(temp_image, "source_linear") |
| 58 | 2x | colorspace = attr(temp_image, "colorspace") |
| 59 | 2x | white_current = attr(temp_image, "white_current") |
| 60 | ||
| 61 | 2x | if (use_bilinear) { |
| 62 | ! | if (!is.null(dims)) { |
| 63 | ! | dims = dims[1:2] / dim(temp_image)[1:2] |
| 64 | } | |
| 65 | ! | temp_list = list() |
| 66 | ! | if (length(dim(temp_image)) == 3) { |
| 67 | ! | channels = dim(temp_image)[3] |
| 68 | ! | for (i in seq_len(channels)) { |
| 69 | ! | if (is.null(dims)) { |
| 70 | ! | temp_list[[i]] = resize_image(temp_image[,, i], mag) |
| 71 | } else { | |
| 72 | ! | x1 = seq(1, nrow(temp_image), length.out = nrow(temp_image) * dims[1]) |
| 73 | ! | y1 = seq(1, ncol(temp_image), length.out = ncol(temp_image) * dims[2]) |
| 74 | ! | temp_list[[i]] = resize_image_xy(temp_image[,, i], x1, y1) |
| 75 | } | |
| 76 | } | |
| 77 | ! | temp_image = array( |
| 78 | ! | 0, |
| 79 | ! | dim = c(nrow(temp_list[[1]]), ncol(temp_list[[1]]), channels) |
| 80 | ) | |
| 81 | ! | for (i in seq_len(channels)) { |
| 82 | ! | temp_image[,, i] = temp_list[[i]] |
| 83 | } | |
| 84 | } else { | |
| 85 | ! | if (is.null(dims)) { |
| 86 | ! | temp_image = resize_image(t(flipud(temp_image)), mag) |
| 87 | } else { | |
| 88 | ! | x1 = seq(1, nrow(temp_image), length.out = nrow(temp_image) * dims[1]) |
| 89 | ! | y1 = seq(1, ncol(temp_image), length.out = ncol(temp_image) * dims[2]) |
| 90 | ! | temp_image = resize_image_xy(t(flipud(temp_image)), x1, y1) |
| 91 | } | |
| 92 | } | |
| 93 | } else { | |
| 94 | 2x | method = tolower(method) |
| 95 | 2x | method = switch( |
| 96 | 2x | method, |
| 97 | 2x | "default" = 0, |
| 98 | 2x | "box" = 1, |
| 99 | 2x | "triangle" = 2, |
| 100 | 2x | "tri" = 3, |
| 101 | 2x | "trilinear" = 3, |
| 102 | 2x | "cubic" = 3, |
| 103 | 2x | "catmull" = 4, |
| 104 | 2x | "mitchell" = 5, |
| 105 | 2x | 3 |
| 106 | ) | |
| 107 | 2x | if (is.null(dims)) { |
| 108 | ! | dims = mag * dim(temp_image)[1:2] |
| 109 | } | |
| 110 | 2x | temp_list = list() |
| 111 | 2x | if (length(dim(temp_image)) == 3) { |
| 112 | 2x | for (i in seq_len(dim(temp_image)[3])) { |
| 113 | 8x | temp_list[[i]] = resize_matrix_stb( |
| 114 | 8x | unclass(temp_image[,, i]), |
| 115 | 8x | dims[1], |
| 116 | 8x | dims[2], |
| 117 | 8x | method |
| 118 | ) | |
| 119 | } | |
| 120 | 2x | temp_image = array(0, dim = c(dims[1], dims[2], dim(temp_image)[3])) |
| 121 | 2x | for (i in seq_len(dim(temp_image)[3])) { |
| 122 | 8x | temp_image[,, i] = temp_list[[i]] |
| 123 | } | |
| 124 | } else { | |
| 125 | ! | bare_matrix = unclass(temp_image) |
| 126 | ! | temp_image = resize_matrix_stb( |
| 127 | ! | bare_matrix, |
| 128 | ! | dims[1], |
| 129 | ! | dims[2], |
| 130 | ! | method |
| 131 | ) | |
| 132 | } | |
| 133 | } | |
| 134 | 2x | temp_image = ray_read_image( |
| 135 | 2x | temp_image, |
| 136 | 2x | filetype = imagetype, |
| 137 | 2x | source_linear = img_source_linear, |
| 138 | 2x | assume_colorspace = colorspace, |
| 139 | 2x | assume_white = white_current |
| 140 | ) | |
| 141 | 2x | handle_image_output(temp_image, filename = filename, preview = preview) |
| 142 | } |
| 1 | #'@title Render Convolution | |
| 2 | #' | |
| 3 | #'@description Takes an image and applies a convolution operation to it, using | |
| 4 | #'a user-supplied or built-in kernel. Edges are calculated by limiting the size | |
| 5 | #'of the kernel to only that overlapping the actual image (renormalizing the | |
| 6 | #'kernel for the edges). | |
| 7 | #' | |
| 8 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 9 | #'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead. | |
| 10 | #'@param kernel Default `gaussian`. By default, an 11x11 Gaussian kernel with a mean | |
| 11 | #'of `0` and a standard deviation of `1`, running from `-kernel_extent` to `kernel_extent`. | |
| 12 | #'If numeric, this will be the standard deviation of the normal distribution. If a | |
| 13 | #'matrix, it will be used directly as the convolution kernel (but resized always to be an odd number | |
| 14 | #'of columns and rows). | |
| 15 | #'@param kernel_dim Default `11`. The dimension of the `gaussian` kernel. Ignored | |
| 16 | #'if user specifies their own kernel. | |
| 17 | #'@param kernel_extent Default `3`. Extent over which to calculate the kernel. | |
| 18 | #'@param absolute Default `TRUE`. Whether to take the absolute value of the convolution. | |
| 19 | #'@param min_value Default `NULL`. If numeric, specifies the minimum value (for any color channel) | |
| 20 | #'for a pixel to have the convolution performed. | |
| 21 | #'@param include_alpha Default `FALSE`. Whether to include the alpha channel in the convolution. | |
| 22 | #'@param preview Default `TRUE`. Whether to plot the convolved image, or just to return the values. | |
| 23 | #'@param progress Default `TRUE`. Whether to display a progress bar. | |
| 24 | #'@return A `rayimg` RGBA array. | |
| 25 | #'@export | |
| 26 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 27 | #'#Perform a convolution with the default gaussian kernel | |
| 28 | #'plot_image(dragon) | |
| 29 | #'#Perform a convolution with the default gaussian kernel | |
| 30 | #'render_convolution(dragon, preview = TRUE) | |
| 31 | #'#Increase the width of the kernel | |
| 32 | #'render_convolution(dragon, kernel = 2, kernel_dim=21,kernel_extent=6, preview = TRUE) | |
| 33 | #'#Perform edge detection using an edge detection kernel | |
| 34 | #'edge = matrix(c(-1,-1,-1,-1,8,-1,-1,-1,-1),3,3) | |
| 35 | #'render_convolution(render_bw(dragon), kernel = edge, preview = TRUE, absolute=FALSE) | |
| 36 | #'#Perform edge detection with Sobel matrices | |
| 37 | #'sobel1 = matrix(c(1,2,1,0,0,0,-1,-2,-1),3,3) | |
| 38 | #'sobel2 = matrix(c(1,2,1,0,0,0,-1,-2,-1),3,3,byrow=TRUE) | |
| 39 | #'sob1 = render_convolution(render_bw(dragon), kernel = sobel1) | |
| 40 | #'sob2 = render_convolution(render_bw(dragon), kernel = sobel2) | |
| 41 | #'sob_all = sob1 + sob2 | |
| 42 | #'plot_image(sob1) | |
| 43 | #'plot_image(sob2) | |
| 44 | #'plot_image(sob_all) | |
| 45 | #' | |
| 46 | #'#Only perform the convolution on bright pixels (bloom) | |
| 47 | #'render_convolution(dragon, kernel = 5, kernel_dim=24, kernel_extent=24, | |
| 48 | #' min_value=1, preview = TRUE) | |
| 49 | #'#Use a built-in kernel: | |
| 50 | #'render_convolution(dragon, kernel = generate_2d_exponential(falloff=2, dim=31, width=21), | |
| 51 | #' preview = TRUE) | |
| 52 | #'#We can also apply this function to matrices: | |
| 53 | #'volcano |> image() | |
| 54 | #'volcano |> | |
| 55 | #' render_convolution(kernel=generate_2d_gaussian(sd=1,dim=31)) |> | |
| 56 | #' image() | |
| 57 | #'#Use a custom kernel (in this case, an X shape): | |
| 58 | #'custom = diag(10) + (diag(10)[,10:1]) | |
| 59 | #'plot_image(custom) | |
| 60 | #'render_convolution(dragon, kernel = custom, preview = TRUE) | |
| 61 | render_convolution = function( | |
| 62 | image, | |
| 63 | kernel = "gaussian", | |
| 64 | kernel_dim = 11, | |
| 65 | kernel_extent = 3, | |
| 66 | absolute = TRUE, | |
| 67 | min_value = NULL, | |
| 68 | include_alpha = FALSE, | |
| 69 | filename = NULL, | |
| 70 | preview = FALSE, | |
| 71 | progress = FALSE | |
| 72 | ) { | |
| 73 | ! | if (is.character(kernel)) { |
| 74 | ! | if (kernel == "gaussian") { |
| 75 | ! | kernel = generate_2d_gaussian(1, 1, kernel_dim, kernel_extent) |
| 76 | } | |
| 77 | } | |
| 78 | ! | if (is.numeric(kernel) && length(kernel) == 1) { |
| 79 | ! | kernel = generate_2d_gaussian(kernel, 1, kernel_dim, kernel_extent) |
| 80 | } | |
| 81 | ! | if (!is.null(dim(kernel)) && all(dim(kernel) >= 2)) { |
| 82 | ! | if (ncol(kernel) %% 2 == 0) { |
| 83 | ! | newkernel = matrix(0, ncol = ncol(kernel) + 1, nrow = nrow(kernel)) |
| 84 | ! | newkernel[, 1:ncol(kernel)] = kernel |
| 85 | ! | kernel = newkernel |
| 86 | } | |
| 87 | ! | if (nrow(kernel) %% 2 == 0) { |
| 88 | ! | newkernel = matrix(0, ncol = ncol(kernel), nrow = nrow(kernel) + 1) |
| 89 | ! | newkernel[1:nrow(kernel), ] = kernel |
| 90 | ! | kernel = newkernel |
| 91 | } | |
| 92 | } | |
| 93 | ! | temp_image = ray_read_image( |
| 94 | ! | image, |
| 95 | ! | convert_to_array = FALSE, |
| 96 | ! | reset_camera_settings = TRUE |
| 97 | ) | |
| 98 | ! | colorspace = attr(temp_image, "colorspace") |
| 99 | ! | whitepoint = attr(temp_image, "white_current") |
| 100 | ! | imagetype = attr(temp_image, "filetype") |
| 101 | ! | if (any(dim(kernel) > dim(temp_image)[1:2] * 2 + 1)) { |
| 102 | ! | stop( |
| 103 | ! | "kernel dimensions: ", |
| 104 | ! | paste0(dim(kernel), collapse = "x"), |
| 105 | ! | " must not be greater than 2x image dimensions: ", |
| 106 | ! | paste0(dim(temp_image)[1:2], collapse = "x"), |
| 107 | ! | ", plus one (here, ", |
| 108 | ! | paste0(dim(temp_image)[1:2] * 2 + 1, collapse = "x"), |
| 109 | ")." | |
| 110 | ) | |
| 111 | } | |
| 112 | ||
| 113 | ! | bloom_matrix = matrix(TRUE, nrow = nrow(temp_image), ncol = ncol(temp_image)) |
| 114 | ! | if (length(dim(temp_image)) == 3) { |
| 115 | ! | if (!is.null(min_value)) { |
| 116 | ! | bool_value = rep(TRUE, length = length(temp_image[,, 1])) |
| 117 | ! | for (i in seq_along(dim(temp_image)[3])) { |
| 118 | ! | bool_value = bool_value & temp_image[,, i] <= min_value |
| 119 | } | |
| 120 | ! | bloom_matrix[bool_value] = FALSE |
| 121 | } | |
| 122 | } else { | |
| 123 | ! | if (!is.null(min_value)) { |
| 124 | ! | bloom_matrix[temp_image <= min_value] = FALSE |
| 125 | } | |
| 126 | } | |
| 127 | ! | temp_image_final = temp_image |
| 128 | ! | if (imagetype != "matrix") { |
| 129 | ! | channels = dim(temp_image)[3] |
| 130 | ! | if (!include_alpha && (channels == 2 || channels == 4)) { |
| 131 | ! | max_channel = channels - 1 |
| 132 | } else { | |
| 133 | ! | max_channel = channels |
| 134 | } | |
| 135 | ! | for (i in seq_len(max_channel)) { |
| 136 | ! | temp_image_final[,, i] = convolution_cpp( |
| 137 | ! | temp_image[,, i], |
| 138 | ! | kernel = kernel, |
| 139 | ! | progbar = progress, |
| 140 | ! | channel = i, |
| 141 | ! | bloom_matrix = bloom_matrix |
| 142 | ) | |
| 143 | } | |
| 144 | } else { | |
| 145 | ! | temp_image_final = convolution_cpp( |
| 146 | ! | temp_image, |
| 147 | ! | kernel = kernel, |
| 148 | ! | progbar = progress, |
| 149 | ! | channel = 1, |
| 150 | ! | bloom_matrix = bloom_matrix |
| 151 | ) | |
| 152 | } | |
| 153 | ! | if (absolute) { |
| 154 | ! | temp_image_final = abs(temp_image_final) |
| 155 | } | |
| 156 | ! | final_image = ray_read_image( |
| 157 | ! | temp_image_final, |
| 158 | ! | assume_colorspace = colorspace, |
| 159 | ! | assume_white = whitepoint, |
| 160 | ! | source_linear = TRUE |
| 161 | ) | |
| 162 | ! | handle_image_output(final_image, filename = filename, preview = preview) |
| 163 | } |
| 1 | #' Create a rayimg | |
| 2 | #' | |
| 3 | #' This class will always be: | |
| 4 | #' * A matrix or a 2/3/4 layer array | |
| 5 | #' * It tracks whether the source data was linearized | |
| 6 | #' * It carries working colorspace/white | |
| 7 | #' * It carries informational exposure/ISO metadata | |
| 8 | #' | |
| 9 | #' @param x Default `NULL`. The underlying array/matrix to wrap. | |
| 10 | #' @param filetype Default `NULL`. Original source type to record (e.g., "png"). | |
| 11 | #' @param source_linear Default `FALSE`. Whether the original source was linearized. | |
| 12 | #' @param colorspace Default `CS_ACESCG`. Working space descriptor (see `make_colorspace()`). | |
| 13 | #' @param white_current Default `colorspace$white_xyz`. Current assumed scene/display white (XYZ, Y=1). | |
| 14 | #' @param exposure Default `0`. Informational exposure compensation in stops. | |
| 15 | #' @param iso Default `100`. Informational ISO value. | |
| 16 | #' | |
| 17 | #' @return An object of class `c("rayimg", <original class>)` with attributes. | |
| 18 | #' @keywords internal | |
| 19 | rayimg = function( | |
| 20 | x = NULL, | |
| 21 | filetype = NULL, | |
| 22 | source_linear = FALSE, | |
| 23 | colorspace = CS_ACESCG, | |
| 24 | white_current = colorspace$white_xyz, | |
| 25 | exposure = attr(x, "exposure", exact = TRUE), | |
| 26 | iso = attr(x, "iso", exact = TRUE) | |
| 27 | ) { | |
| 28 | 851x | if (is.null(x)) { |
| 29 | ! | stop("rayimg(): 'x' cannot be NULL.") |
| 30 | } | |
| 31 | 851x | stopifnot(is.array(x)) |
| 32 | ||
| 33 | 851x | x_new = rayimg_validate_dimensions(x) |
| 34 | ||
| 35 | # channels attribute | |
| 36 | 851x | if (is.null(attr(x, "channels"))) { |
| 37 | 353x | attr(x_new, "channels") = rayimg_detect_channels(x_new) |
| 38 | } else { | |
| 39 | 498x | attr(x_new, "channels") = attr(x, "channels") |
| 40 | } | |
| 41 | ||
| 42 | # required attrs | |
| 43 | 851x | attr(x_new, "filetype") = filetype |
| 44 | 851x | attr(x_new, "source_linear") = source_linear |
| 45 | 851x | attr(x_new, "exposure") = rayimg_exposure_value(exposure) |
| 46 | 851x | attr(x_new, "iso") = rayimg_iso_value(iso) |
| 47 | ||
| 48 | # new attrs for color mgmt | |
| 49 | 851x | stopifnot( |
| 50 | 851x | is.list(colorspace), |
| 51 | 851x | all(c("rgb_to_xyz", "xyz_to_rgb", "white_xyz") %in% names(colorspace)) |
| 52 | ) | |
| 53 | 851x | attr(x_new, "colorspace") = colorspace |
| 54 | 851x | attr(x_new, "white_current") = white_current |
| 55 | 851x | if (!is.null(attr(x, "dng", exact = TRUE))) { |
| 56 | 2x | attr(x_new, "dng") = attr(x, "dng", exact = TRUE) |
| 57 | } | |
| 58 | 851x | if (!is.null(attr(x, "exr", exact = TRUE))) { |
| 59 | 2x | attr(x_new, "exr") = attr(x, "exr", exact = TRUE) |
| 60 | } | |
| 61 | 851x | class(x_new) = c("rayimg", setdiff(class(x), "rayimg")) |
| 62 | 851x | x_new |
| 63 | } | |
| 64 | ||
| 65 | rayimg_exposure_value = function(exposure) { | |
| 66 | 949x | if (is.null(exposure) || length(exposure) == 0L) { |
| 67 | 241x | return(0) |
| 68 | } | |
| 69 | if ( | |
| 70 | 708x | !is.numeric(exposure) || |
| 71 | 708x | length(exposure) != 1L || |
| 72 | 708x | is.na(exposure) || |
| 73 | 708x | !is.finite(exposure) |
| 74 | ) { | |
| 75 | ! | stop("rayimg(): 'exposure' must be a finite numeric value.") |
| 76 | } | |
| 77 | 708x | as.numeric(exposure) |
| 78 | } | |
| 79 | ||
| 80 | rayimg_iso_value = function(iso) { | |
| 81 | 937x | if (is.null(iso) || length(iso) == 0L) { |
| 82 | 241x | return(100) |
| 83 | } | |
| 84 | if ( | |
| 85 | 696x | !is.numeric(iso) || |
| 86 | 696x | length(iso) != 1L || |
| 87 | 696x | is.na(iso) || |
| 88 | 696x | !is.finite(iso) || |
| 89 | 696x | iso <= 0 |
| 90 | ) { | |
| 91 | ! | stop("rayimg(): 'iso' must be a positive finite numeric value.") |
| 92 | } | |
| 93 | 696x | as.numeric(iso) |
| 94 | } | |
| 95 | ||
| 96 | rayimg_channels_from_count = function(n) { | |
| 97 | switch( | |
| 98 | 1736x | as.character(n), |
| 99 | ! | "1" = c("Greyscale"), |
| 100 | 20x | "2" = c("Greyscale", "Alpha"), |
| 101 | 330x | "3" = c("Red", "Green", "Blue"), |
| 102 | 1386x | "4" = c("Red", "Green", "Blue", "Alpha"), |
| 103 | ! | stop("This should never be hit.") |
| 104 | ) | |
| 105 | } | |
| 106 | ||
| 107 | rayimg_detect_channels = function(x) { | |
| 108 | 1824x | d = dim(x) |
| 109 | 1824x | if (length(d) < 3L) { |
| 110 | 88x | return("Greyscale") |
| 111 | } | |
| 112 | 1736x | rayimg_channels_from_count(d[3]) |
| 113 | } | |
| 114 | ||
| 115 | #Always return a multidimensional (d[3] = 2,3,4) array, or a matrix. | |
| 116 | rayimg_validate_dimensions = function(x) { | |
| 117 | 851x | d = dim(x) |
| 118 | 851x | stopifnot(!is.null(d), length(d) %in% c(2, 3), d[1] > 0, d[2] > 0) |
| 119 | 851x | if (length(d) == 3) { |
| 120 | 705x | if (d[3] == 1) { |
| 121 | ! | x = x[,, 1] # drop extra |
| 122 | } else { | |
| 123 | 705x | stopifnot(d[3] %in% c(2, 3, 4)) |
| 124 | } | |
| 125 | } | |
| 126 | 851x | x |
| 127 | } | |
| 128 | ||
| 129 | #' @export | |
| 130 | `[.rayimg` = function(x, ..., drop = TRUE) { | |
| 131 | 1471x | ch = rayimg_detect_channels(x) |
| 132 | 1471x | caller_env = parent.frame() |
| 133 | 1471x | mc = match.call(expand.dots = FALSE) |
| 134 | 1471x | dots_expr = as.list(mc$`...`) |
| 135 | 1471x | nd = length(dim(x)) |
| 136 | ||
| 137 | 1471x | if (length(dots_expr) < nd) { |
| 138 | 226x | dots_expr = c(dots_expr, rep(list(quote(expr = )), nd - length(dots_expr))) |
| 139 | } | |
| 140 | 1471x | idx = lapply(dots_expr, function(z) { |
| 141 | 1611x | if (identical(z, quote(expr = ))) TRUE else eval(z, envir = caller_env) |
| 142 | }) | |
| 143 | ||
| 144 | 1471x | if (nd >= 3L) { |
| 145 | 1465x | if (!isTRUE(idx[[3L]]) && length(idx[[3L]]) > 4L) { |
| 146 | 7x | stop("A rayimg can only have four or fewer channels selected at once.") |
| 147 | } | |
| 148 | 1458x | if (!isTRUE(idx[[3L]]) && any(idx[[3L]] > 4L)) { |
| 149 | ! | stop("rayimg: channel index > 4.") |
| 150 | } | |
| 151 | } | |
| 152 | ||
| 153 | 1464x | y = NextMethod("[", drop = FALSE) |
| 154 | ||
| 155 | 1464x | if (drop) { |
| 156 | 1415x | d = dim(y) |
| 157 | 1415x | dn = dimnames(y) |
| 158 | 1415x | drop_idx = which(d == 1L & seq_along(d) >= 3L) |
| 159 | 1415x | if (length(drop_idx)) { |
| 160 | 570x | keep = setdiff(seq_along(d), drop_idx) |
| 161 | 570x | y = array(y, dim = d[keep], dimnames = dn[keep]) |
| 162 | } | |
| 163 | } | |
| 164 | ||
| 165 | # carry attrs | |
| 166 | 1464x | attr(y, "filetype") = attr(x, "filetype") |
| 167 | 1464x | attr(y, "source_linear") = attr(x, "source_linear") |
| 168 | 1464x | attr(y, "exposure") = attr(x, "exposure") |
| 169 | 1464x | attr(y, "iso") = attr(x, "iso") |
| 170 | 1464x | attr(y, "colorspace") = attr(x, "colorspace") |
| 171 | 1464x | attr(y, "white_current") = attr(x, "white_current") |
| 172 | 1464x | if (!is.null(attr(x, "dng", exact = TRUE))) { |
| 173 | ! | attr(y, "dng") = attr(x, "dng", exact = TRUE) |
| 174 | } | |
| 175 | 1464x | if (!is.null(attr(x, "exr", exact = TRUE))) { |
| 176 | 6x | attr(y, "exr") = attr(x, "exr", exact = TRUE) |
| 177 | } | |
| 178 | ||
| 179 | 1464x | if (!is.null(ch)) { |
| 180 | 1464x | if (nd >= 3L) { |
| 181 | 1458x | ch_idx = idx[[3L]] |
| 182 | 1458x | if (isTRUE(ch_idx)) { |
| 183 | 265x | ch_idx = seq_along(ch) |
| 184 | } | |
| 185 | 1458x | attr(y, "channels") = ch[ch_idx] |
| 186 | } else { | |
| 187 | 6x | attr(y, "channels") = ch[seq_len(min(1L, length(ch)))] |
| 188 | } | |
| 189 | } else { | |
| 190 | ! | attr(y, "channels") = rayimg_detect_channels(y) |
| 191 | } | |
| 192 | ||
| 193 | 1464x | if (!is.null(dim(y))) { |
| 194 | 1238x | class(y) = unique(c("rayimg", setdiff(class(y), "rayimg"))) |
| 195 | } | |
| 196 | 1464x | y |
| 197 | } |
| 1 | #' @title Render White Balance (Bradford CAT) | |
| 2 | #' @description Chromatic-adapt an image from `reference_white` to `target_white` **in its working RGB space**. | |
| 3 | #' | |
| 4 | #' When `bake = FALSE` (the default), this should not result in any visible changes to the image when | |
| 5 | #' plotted in rayimage via [plot_image()], as that function then corrects the white balance for | |
| 6 | #' display. Set | |
| 7 | #' | |
| 8 | #' @param image Default `NULL`. 3-layer RGB/4-layer RGBA array, `rayimg`, or filename. | |
| 9 | #' @param reference_white Default `NA`. Source white (XYZ Y=1 or named); when `NA`, uses `attr(img, "white_current")`. | |
| 10 | #' @param target_white Default `"D60"`. Target white (XYZ Y=1 or named). | |
| 11 | #' @param bake Default `FALSE`. `FALSE` = appearance-preserving | |
| 12 | #' (update tag to the new white). When `TRUE`, apply CAT but keep the original tag, | |
| 13 | #' producing a visible warmer/cooler result on display. | |
| 14 | #' @param filename Default `NULL`. Output path. | |
| 15 | #' @param preview Default `FALSE`. If `TRUE`, display the image. | |
| 16 | #' @param bake Default `FALSE`. If `TRUE`, this will bake the color change into the image, and return the | |
| 17 | #' old tag. This can be used for stylistic adjustments. | |
| 18 | #' @export | |
| 19 | #' @examples | |
| 20 | #' # Not specifying a target white balance returns an unchanged image | |
| 21 | #' render_white_balance(dragon, preview = TRUE) | |
| 22 | #' | |
| 23 | #' # Default white "D60", converting to D50 produces a warmer image | |
| 24 | #' render_white_balance(dragon, preview = TRUE, target_white = "D50", bake = TRUE) | |
| 25 | #' | |
| 26 | #' # Default white "D60", converting to "D75" produces a cooler image | |
| 27 | #' render_white_balance(dragon, preview = TRUE, target_white = "D75", bake = TRUE) | |
| 28 | #' | |
| 29 | #' # Set reference white to colder "D75", converting to "D50" produces a very warm image | |
| 30 | #' render_white_balance(dragon, preview = TRUE, | |
| 31 | #' reference_white= "D75", target_white = "D50", bake = TRUE) | |
| 32 | #' | |
| 33 | #' # With a real, non-rendered image: | |
| 34 | #' render_white_balance(sunset_image, preview=TRUE) | |
| 35 | #' | |
| 36 | #' # Cooler | |
| 37 | #' render_white_balance(sunset_image, preview=TRUE, target_white = "D75", bake = TRUE) | |
| 38 | #' | |
| 39 | #' # Warmer | |
| 40 | #' render_white_balance(sunset_image, preview=TRUE, target_white = "D50", bake = TRUE) | |
| 41 | render_white_balance = function( | |
| 42 | image, | |
| 43 | reference_white = NA, | |
| 44 | target_white = "D60", | |
| 45 | bake = FALSE, | |
| 46 | filename = NULL, | |
| 47 | preview = FALSE | |
| 48 | ) { | |
| 49 | 2x | src = ray_read_image(image, normalize = FALSE) |
| 50 | 2x | cs = attr(src, "colorspace") |
| 51 | ||
| 52 | if ( | |
| 53 | 2x | is.atomic(reference_white) && |
| 54 | 2x | length(reference_white) == 1L && |
| 55 | 2x | is.na(reference_white) |
| 56 | ) { | |
| 57 | ! | reference_white = attr(src, "white_current") |
| 58 | } | |
| 59 | ||
| 60 | # If whites are identical, do nothing | |
| 61 | if ( | |
| 62 | 2x | isTRUE(all.equal( |
| 63 | 2x | get_whitepoint_xyz(reference_white)$value, |
| 64 | 2x | get_whitepoint_xyz(target_white)$value |
| 65 | )) | |
| 66 | ) { | |
| 67 | ! | return(handle_image_output(src, filename = filename, preview = preview)) |
| 68 | } | |
| 69 | ||
| 70 | 2x | if (!bake) { |
| 71 | # CAT + update tag (appearance-preserving) | |
| 72 | ! | return(render_convert_colorspace( |
| 73 | ! | src, |
| 74 | ! | from_mats = cs, |
| 75 | ! | to_mats = cs, |
| 76 | ! | adapt_white = TRUE, |
| 77 | ! | from_white = reference_white, |
| 78 | ! | to_white = target_white, |
| 79 | ! | filename = filename, |
| 80 | ! | preview = preview |
| 81 | )) | |
| 82 | } | |
| 83 | ||
| 84 | # bake = TRUE, CAT but keep the original tag ---- | |
| 85 | 2x | src_wp = get_whitepoint_xyz(reference_white) |
| 86 | 2x | dst_wp = get_whitepoint_xyz(target_white) |
| 87 | ||
| 88 | # Work in linear RGB | |
| 89 | 2x | if (!isTRUE(attr(src, "source_linear"))) { |
| 90 | ! | warning( |
| 91 | ! | "render_white_balance(bake = TRUE): input not linear; convert with render_gamma_linear(..., TRUE) first." |
| 92 | ) | |
| 93 | } | |
| 94 | ||
| 95 | # RGB(working) -> XYZ | |
| 96 | 2x | xyz = apply_color_matrix(src, cs$rgb_to_xyz) |
| 97 | # CAT in XYZ | |
| 98 | 2x | CAT = compute_cat_bradford(src_wp$value, dst_wp$value) |
| 99 | 2x | xyz = apply_color_matrix(xyz, CAT) |
| 100 | # XYZ -> RGB(working) | |
| 101 | 2x | out = apply_color_matrix(xyz, cs$xyz_to_rgb) |
| 102 | # preserve alpha | |
| 103 | 2x | d = dim(src) |
| 104 | 2x | if (length(d) == 3L && d[3] == 4L) { |
| 105 | 2x | out[,, 4] = src[,, 4] |
| 106 | } | |
| 107 | ||
| 108 | 2x | out = rayimg( |
| 109 | 2x | out, |
| 110 | 2x | filetype = attr(src, "filetype"), |
| 111 | 2x | source_linear = attr(src, "source_linear"), |
| 112 | 2x | colorspace = cs, # primaries unchanged |
| 113 | 2x | white_current = src_wp$value, # Keep the original tag to bake in the new color |
| 114 | 2x | exposure = attr(src, "exposure", exact = TRUE), |
| 115 | 2x | iso = attr(src, "iso", exact = TRUE) |
| 116 | ) | |
| 117 | 2x | handle_image_output(out, filename = filename, preview = preview) |
| 118 | } |
| 1 | #' Normalize/label a white point | |
| 2 | #' @param white_point Default `NULL`. Named ("D65","D60","D55","D50","D75","E") or XYZ (length 3, any Y). | |
| 3 | #' @returns list(value = XYZ with Y=1, white_name = name or "Custom") | |
| 4 | #' @keywords internal | |
| 5 | get_whitepoint_xyz = function(white_point = NULL) { | |
| 6 | 430x | std = list( |
| 7 | 430x | "D65" = c(0.95047, 1, 1.08883), |
| 8 | 430x | "D60" = c(0.95264, 1, 1.00827), |
| 9 | 430x | "D55" = c(0.95560, 1, 0.92149), |
| 10 | 430x | "D50" = c(0.96422, 1, 0.82521), |
| 11 | 430x | "D75" = c(0.94972, 1, 1.22638), |
| 12 | 430x | "E" = c(1, 1, 1) |
| 13 | ) | |
| 14 | 430x | if (is.null(white_point)) { |
| 15 | ! | return(NULL) |
| 16 | } | |
| 17 | 430x | if (is.character(white_point) && length(white_point) == 1L) { |
| 18 | 12x | wp = std[[toupper(white_point)]] |
| 19 | 12x | if (is.null(wp)) { |
| 20 | ! | stop("Unknown white: ", white_point) |
| 21 | } | |
| 22 | 12x | return(list(value = wp, white_name = white_point)) |
| 23 | } | |
| 24 | 418x | stopifnot(is.numeric(white_point), length(white_point) == 3L) |
| 25 | 418x | Y = white_point[2] |
| 26 | 418x | if (!is.finite(Y) || Y <= 0) { |
| 27 | ! | stop("White Y must be positive and finite.") |
| 28 | } | |
| 29 | 418x | list(value = white_point / Y, white_name = "Custom") |
| 30 | } | |
| 31 | ||
| 32 | #' Bradford CAT matrix from source to target white | |
| 33 | #' @param source_xyz Default `c(0.95264,1,1.00827)`. Source XYZ white, Y=1. | |
| 34 | #' @param target_xyz Default `c(0.95047,1,1.08883)`. Target XYZ white, Y=1. | |
| 35 | #' @param eps Default `1e-8`. Small epsilon. | |
| 36 | #' @return 3x3 numeric CAT matrix to apply in XYZ. | |
| 37 | #' @keywords internal | |
| 38 | compute_cat_bradford = function( | |
| 39 | source_xyz = c(0.95264, 1.0, 1.00827), | |
| 40 | target_xyz = c(0.95047, 1.0, 1.08883), | |
| 41 | eps = 1e-8 | |
| 42 | ) { | |
| 43 | 86x | B = matrix( |
| 44 | 86x | c( |
| 45 | 86x | 0.8951, |
| 46 | 86x | 0.2664, |
| 47 | 86x | -0.1614, |
| 48 | 86x | -0.7502, |
| 49 | 86x | 1.7135, |
| 50 | 86x | 0.0367, |
| 51 | 86x | 0.0389, |
| 52 | 86x | -0.0685, |
| 53 | 86x | 1.0296 |
| 54 | ), | |
| 55 | 86x | 3, |
| 56 | 86x | 3, |
| 57 | 86x | byrow = TRUE |
| 58 | ) | |
| 59 | 86x | src = B %*% source_xyz |
| 60 | 86x | dst = B %*% target_xyz |
| 61 | 86x | if (any(abs(src) < eps)) { |
| 62 | ! | stop("CAT: source LMS too close to zero") |
| 63 | } | |
| 64 | 86x | S = diag(as.numeric(dst / src)) |
| 65 | 86x | solve(B) %*% S %*% B |
| 66 | } | |
| 67 | ||
| 68 | #' Apply a 3x3 color transform to an image | |
| 69 | #' @param img 3/4-channel array (RGB/A). 2D (grey) or 2-channel (grey+alpha) pass through. | |
| 70 | #' @param M 3x3 matrix. | |
| 71 | #' @return Array with transformed RGB; alpha preserved. | |
| 72 | #' @keywords internal | |
| 73 | apply_color_matrix = function(img, M = diag(3)) { | |
| 74 | 258x | stopifnot(is.array(img), is.matrix(M), all(dim(M) == c(3, 3))) |
| 75 | 258x | d = dim(img) |
| 76 | 258x | if (length(d) == 2L) { |
| 77 | ! | return(img) |
| 78 | } | |
| 79 | 258x | ch = d[3] |
| 80 | 258x | if (ch < 3L) { |
| 81 | ! | return(img) |
| 82 | } | |
| 83 | 258x | flat = matrix(img[,, 1:3], ncol = 3) |
| 84 | 258x | flat = flat %*% t(M) |
| 85 | 258x | out = img |
| 86 | 258x | out[,, 1:3] = array(flat, dim = c(d[1], d[2], 3)) |
| 87 | 258x | out |
| 88 | } | |
| 89 | ||
| 90 | #' sRGB to Linear | |
| 91 | #' @param x Values | |
| 92 | #' @returns Transformed values | |
| 93 | #' @keywords internal | |
| 94 | to_linear = function(x) { | |
| 95 | 75x | out = x |
| 96 | 75x | low = x <= 0.04045 |
| 97 | 75x | out[low] = x[low] / 12.92 |
| 98 | 75x | out[!low] = ((x[!low] + 0.055) / 1.055)^2.4 |
| 99 | 75x | out |
| 100 | } | |
| 101 | ||
| 102 | #' Linear to sRGB | |
| 103 | #' @param x Values | |
| 104 | #' @returns Transformed values | |
| 105 | #' @keywords internal | |
| 106 | to_srgb = function(x) { | |
| 107 | 143x | x = pmin(pmax(x, 0), 1) |
| 108 | 143x | out = x |
| 109 | 143x | low = x <= 0.0031308 |
| 110 | 143x | out[low] = 12.92 * x[low] |
| 111 | 143x | out[!low] = 1.055 * x[!low]^(1 / 2.4) - 0.055 |
| 112 | 143x | out |
| 113 | } | |
| 114 | ||
| 115 | #' Encode RGB/RGBA to hex (sRGB domain) | |
| 116 | #' @param x Values. 3 or 4 columns (R,G,B,A) in 0 to 1. | |
| 117 | #' @return Hex vector (#RRGGBB or #RRGGBBAA). | |
| 118 | #' @keywords internal | |
| 119 | rgb_to_hex = function(x) { | |
| 120 | if (is.null(dim(x))) { | |
| 121 | x = matrix(x, ncol = length(x)) | |
| 122 | } | |
| 123 | if (!(ncol(x) %in% c(3L, 4L))) { | |
| 124 | stop("rgb_to_hex(): expected 3 or 4 columns (R,G,B[,A]).") | |
| 125 | } | |
| 126 | x = pmin(pmax(x, 0), 1) | |
| 127 | ints = round(x * 255) | |
| 128 | apply(ints, 1, function(row) { | |
| 129 | paste0("#", paste(sprintf("%02X", row), collapse = "")) | |
| 130 | }) | |
| 131 | } | |
| 132 | ||
| 133 | #' Array hex vector in column-major order | |
| 134 | #' @param arr Array with c>=3 | |
| 135 | #' @return Hex vector length h*w | |
| 136 | #' @keywords internal | |
| 137 | array_rgb_to_hex_colmajor = function(arr) { | |
| 138 | d = dim(arr) | |
| 139 | if (length(d) != 3L || d[3] < 3L) { | |
| 140 | stop("array_rgb_to_hex_colmajor(): need h*w*(3|4).") | |
| 141 | } | |
| 142 | R = as.vector(arr[,, 1]) | |
| 143 | G = as.vector(arr[,, 2]) | |
| 144 | B = as.vector(arr[,, 3]) | |
| 145 | if (d[3] >= 4L) { | |
| 146 | A = as.vector(arr[,, 4]) | |
| 147 | return(rgb_to_hex(cbind(R, G, B, A))) | |
| 148 | } | |
| 149 | rgb_to_hex(cbind(R, G, B)) | |
| 150 | } |
| 1 | #' @title Select PNG Device | |
| 2 | #' | |
| 3 | #' @description Internal helper to pick the best available PNG graphics | |
| 4 | #' device. Uses `ragg::agg_png()` by default, then falls back to a | |
| 5 | #' Cairo-backed `grDevices::png()` device when `use_ragg = FALSE`, and | |
| 6 | #' finally to the base PNG device. | |
| 7 | #' | |
| 8 | #' @param use_ragg Default `TRUE`. If `TRUE`, return `ragg::agg_png()`. | |
| 9 | #' Set to `FALSE` to skip `ragg`. | |
| 10 | #' | |
| 11 | #' @keywords internal | |
| 12 | #' @importFrom ragg agg_png | |
| 13 | linear_png_device = function(use_ragg = TRUE) { | |
| 14 | 68x | if (isTRUE(use_ragg)) { |
| 15 | 68x | return(function(...) { |
| 16 | 67x | args = list(...) |
| 17 | 67x | args$family = NULL |
| 18 | 67x | do.call(agg_png, args) |
| 19 | }) | |
| 20 | } | |
| 21 | ||
| 22 | ! | if (isTRUE(capabilities("cairo"))) { |
| 23 | ! | return(function(...) { |
| 24 | ! | grDevices::png(..., type = "cairo") |
| 25 | }) | |
| 26 | } | |
| 27 | ||
| 28 | ! | warning( |
| 29 | ! | "No cairo device available: install the {ragg} package to ensure correct treatment of gamma when adding text to images.", |
| 30 | ! | call. = FALSE |
| 31 | ) | |
| 32 | ||
| 33 | ! | grDevices::png |
| 34 | } |
| 1 | .libopenexr_available = function() { | |
| 2 | 3x | requireNamespace("libopenexr", quietly = TRUE) |
| 3 | } | |
| 4 | ||
| 5 | #'@title Write Image | |
| 6 | #' | |
| 7 | #'@description Takes an RGB array/filename and writes it to file. | |
| 8 | #' | |
| 9 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 10 | #'@param filename File to write to, with filetype determined by extension. Filetype can be | |
| 11 | #'`PNG`, `JPEG`, `TIFF`, `EXR`, or `DNG`. | |
| 12 | #'@param clamp Default `FALSE`, automatically determined. Whether to clamp the image to 0-1. If the file extension is `PNG` of `JPEG`, | |
| 13 | #'this is forced to `TRUE`. | |
| 14 | #'@param write_linear Default `NA`, automatically determined. By default, images will be gamma corrected (write_linear = FALSE) for | |
| 15 | #' all file types except `EXR` and `DNG` (which are linear formats), unless otherwise specified. | |
| 16 | #'@param ... Arguments to pass to either `jpeg::writeJPEG`, `png::writePNG`, `libopenexr::write_exr`, or `tiff::writeTIFF`. | |
| 17 | #'@return A `rayimg` RGBA array. | |
| 18 | #'@import grDevices | |
| 19 | #'@export | |
| 20 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 21 | #'#Write as a png | |
| 22 | #'tmparr = tempfile(fileext=".png") | |
| 23 | #'ray_read_image(dragon) |> | |
| 24 | #' ray_write_image(tmparr) | |
| 25 | #'ray_read_image(tmparr) |> | |
| 26 | #' plot_image() | |
| 27 | #'#Write as a JPEG (passing quality arguments via ...) | |
| 28 | #'tmparr = tempfile(fileext=".jpg") | |
| 29 | #'ray_read_image(dragon) |> | |
| 30 | #' ray_write_image(tmparr, quality = 0.2) | |
| 31 | #'ray_read_image(tmparr) |> | |
| 32 | #' plot_image() | |
| 33 | #'#Write as a tiff | |
| 34 | #'tmparr = tempfile(fileext=".tiff") | |
| 35 | #'ray_read_image(dragon) |> | |
| 36 | #' ray_write_image(tmparr) | |
| 37 | #'ray_read_image(tmparr) |> | |
| 38 | #' plot_image() | |
| 39 | ray_write_image = function( | |
| 40 | image, | |
| 41 | filename, | |
| 42 | clamp = FALSE, | |
| 43 | write_linear = NA, | |
| 44 | ... | |
| 45 | ) { | |
| 46 | 54x | if (missing(filename)) { |
| 47 | ! | stop("`filename` must be specified.") |
| 48 | } | |
| 49 | 54x | image = ray_read_image(image) # rayimg RGBA, linear RGB |
| 50 | 54x | fileext = tolower(tools::file_ext(filename)) |
| 51 | 54x | if (!fileext %in% c("png", "jpeg", "jpg", "tiff", "exr", "dng")) { |
| 52 | ! | stop(sprintf( |
| 53 | ! | "File extension (%s) must be one of `png`, `jpeg`, `jpg`, `exr`, `tiff`, or `dng`", |
| 54 | ! | fileext |
| 55 | )) | |
| 56 | } | |
| 57 | ||
| 58 | 54x | if (fileext == "dng") { |
| 59 | 1x | meta = attr(image, "dng") |
| 60 | 1x | if (is.null(meta)) { |
| 61 | ! | meta = list() |
| 62 | } | |
| 63 | 1x | write_dng_cpp(filename, image, meta = meta) |
| 64 | 1x | return(invisible(image)) |
| 65 | } | |
| 66 | ||
| 67 | # Auto conversion to sRGB/D65 primaries for LDR outputs | |
| 68 | 53x | is_ldr = fileext %in% c("png", "jpeg", "jpg", "tiff") |
| 69 | 53x | if (is_ldr && length(dim(image)) == 3 && dim(image)[3] >= 3) { |
| 70 | 49x | cs_from = attr(image, "colorspace") |
| 71 | 49x | white_curr = attr(image, "white_current") |
| 72 | if ( | |
| 73 | 49x | !is.null(cs_from) && |
| 74 | 49x | (!identical(cs_from$name, "sRGB") || |
| 75 | 49x | any(abs(white_curr - CS_SRGB$white_xyz) > 1e-8)) |
| 76 | ) { | |
| 77 | 48x | xyz = apply_color_matrix(image, cs_from$rgb_to_xyz) |
| 78 | 48x | if (any(abs(white_curr - CS_SRGB$white_xyz) > 1e-8)) { |
| 79 | 48x | CAT = compute_cat_bradford(white_curr, CS_SRGB$white_xyz) |
| 80 | 48x | xyz = apply_color_matrix(xyz, CAT) |
| 81 | } | |
| 82 | 48x | image = apply_color_matrix(xyz, CS_SRGB$xyz_to_rgb) |
| 83 | 48x | image[,, 1:3][image[,, 1:3] < 0] = 0 |
| 84 | # Update attributes to reflect new working space at write boundary | |
| 85 | 48x | attr(image, "colorspace") = CS_SRGB |
| 86 | 48x | attr(image, "white_current") = CS_SRGB$white_xyz |
| 87 | } | |
| 88 | } | |
| 89 | ||
| 90 | # Clamp for integer formats | |
| 91 | 53x | if (clamp || fileext %in% c("png", "jpeg", "jpg", "tiff")) { |
| 92 | 49x | image = render_clamp(image) |
| 93 | } | |
| 94 | ||
| 95 | 53x | if (is.na(write_linear)) { |
| 96 | # LDR formats default to gamma-encoded; EXR stays linear | |
| 97 | 52x | write_linear = !(fileext %in% c("png", "jpeg", "jpg", "tiff")) |
| 98 | } | |
| 99 | ||
| 100 | 53x | is_matrix = length(dim(image)) == 2 |
| 101 | 53x | if (is_matrix) { |
| 102 | ! | if (!write_linear) image = to_srgb(image) |
| 103 | } else { | |
| 104 | 53x | max_dim = dim(image)[3L] |
| 105 | 53x | has_alpha = max_dim %in% c(2L, 4L) |
| 106 | 53x | col_dims = if (has_alpha) seq_len(max_dim - 1L) else seq_len(max_dim) |
| 107 | ||
| 108 | 53x | if (has_alpha) { |
| 109 | 50x | alpha_channel = image[,, max_dim] |
| 110 | 50x | alpha_channel[alpha_channel > 1] = 1 |
| 111 | 50x | alpha_channel[alpha_channel < 0] = 0 |
| 112 | 50x | image[,, max_dim] = alpha_channel |
| 113 | } | |
| 114 | 53x | if (!write_linear) { |
| 115 | 48x | image[,, col_dims] = to_srgb(image[,, col_dims]) # OETF only on RGB |
| 116 | } | |
| 117 | } | |
| 118 | ||
| 119 | 53x | if (fileext %in% c("jpeg", "jpg")) { |
| 120 | 2x | jpeg::writeJPEG(image, target = filename, ...) |
| 121 | 51x | } else if (fileext == "png") { |
| 122 | 45x | png::writePNG(image, target = filename, ...) |
| 123 | 6x | } else if (fileext == "exr") { |
| 124 | 4x | if (!.libopenexr_available()) { |
| 125 | 1x | stop( |
| 126 | 1x | "The 'libopenexr' package is required to write EXR files.", |
| 127 | 1x | call. = FALSE |
| 128 | ) | |
| 129 | } | |
| 130 | 3x | dots = list(...) |
| 131 | 3x | user_metadata = dots$metadata |
| 132 | 3x | dots$metadata = NULL |
| 133 | 3x | rgba = array(1, dim = c(dim(image)[1:2], 4)) |
| 134 | 3x | if (is_matrix) { |
| 135 | ! | rgba[,, 1:3] = image |
| 136 | 3x | } else if (dim(image)[3] == 1) { |
| 137 | ! | rgba[,, 1:3] = image[,, 1] |
| 138 | 3x | } else if (dim(image)[3] == 2) { |
| 139 | ! | rgba[,, 1] = image[,, 1] |
| 140 | ! | rgba[,, 2] = image[,, 1] |
| 141 | ! | rgba[,, 3] = image[,, 1] |
| 142 | ! | rgba[,, 4] = image[,, 2] |
| 143 | 3x | } else if (dim(image)[3] == 3) { |
| 144 | 1x | rgba[,, 1:3] = image[,, 1:3] |
| 145 | 2x | } else if (dim(image)[3] == 4) { |
| 146 | 2x | rgba = image |
| 147 | } else { | |
| 148 | ! | stop( |
| 149 | ! | "EXR output requires a matrix or an array with 1, 2, 3, or 4 channels.", |
| 150 | ! | call. = FALSE |
| 151 | ) | |
| 152 | } | |
| 153 | 3x | write_args = list( |
| 154 | 3x | path = filename, |
| 155 | 3x | r = rgba[,, 1], |
| 156 | 3x | g = rgba[,, 2], |
| 157 | 3x | b = rgba[,, 3], |
| 158 | 3x | a = rgba[,, 4] |
| 159 | ) | |
| 160 | 3x | metadata = exr_metadata_from_rayimg(image, user_metadata) |
| 161 | 3x | if (libopenexr_supports_metadata()) { |
| 162 | 3x | write_args$metadata = metadata |
| 163 | ! | } else if (!is.null(metadata)) { |
| 164 | ! | warning( |
| 165 | ! | "Installed libopenexr does not support EXR metadata; writing pixel data only.", |
| 166 | ! | call. = FALSE |
| 167 | ) | |
| 168 | } | |
| 169 | 3x | do.call(libopenexr::write_exr, c(write_args, dots)) |
| 170 | } else { | |
| 171 | 2x | tiff::writeTIFF(image, where = filename, ...) |
| 172 | } | |
| 173 | ||
| 174 | # return the (possibly converted/encoded) rayimg invisibly | |
| 175 | 52x | invisible(image) |
| 176 | } |
| 1 | #' @title Render Vibrance | |
| 2 | #' | |
| 3 | #' @description | |
| 4 | #' Adjusts image vibrance (adaptive saturation), similar in spirit to the iPhone "Vibrance" control: | |
| 5 | #' it boosts muted colors more than already-saturated colors, and reduces saturation more strongly | |
| 6 | #' in already-saturated regions when negative. Works on HDR arrays as well (values can exceed 1). | |
| 7 | #' | |
| 8 | #' @param image Image filename, 3-layer RGB array, 4-layer RGBA array, or matrix. If a filename, | |
| 9 | #' it will be read via `ray_read_image()`. | |
| 10 | #' @param vibrance Default `0`. Numeric scalar in -1..1 (values are clamped). Positive values | |
| 11 | #' increase vibrance primarily in low-saturation regions; negative values decrease vibrance primarily | |
| 12 | #' in high-saturation regions. | |
| 13 | #' @param protect_luminance Default `0.25`. Numeric scalar in 0..1. Reduces the vibrance effect | |
| 14 | #' in deep shadows and bright highlights to avoid harsh color shifts. Set to `0` to disable. | |
| 15 | #' @param filename Default `NULL`. If not `NULL`, the processed image will be written to this file. | |
| 16 | #' @param preview Default `FALSE`. Whether to plot the processed image. | |
| 17 | #' | |
| 18 | #' @return 4-layer RGBA array (or matrix if passed a matrix and `ray_read_image()` is not used). | |
| 19 | #' @export | |
| 20 | #' | |
| 21 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 22 | #' dragon |> | |
| 23 | #' render_vibrance(vibrance = 0.4, preview = TRUE) | |
| 24 | render_vibrance = function( | |
| 25 | image, | |
| 26 | vibrance = 0, | |
| 27 | protect_luminance = 0.25, | |
| 28 | filename = NULL, | |
| 29 | preview = FALSE | |
| 30 | ) { | |
| 31 | ! | if (length(vibrance) != 1 || !is.numeric(vibrance) || !is.finite(vibrance)) { |
| 32 | ! | stop("`vibrance` must be a single finite numeric value.") |
| 33 | } | |
| 34 | if ( | |
| 35 | ! | length(protect_luminance) != 1 || |
| 36 | ! | !is.numeric(protect_luminance) || |
| 37 | ! | !is.finite(protect_luminance) |
| 38 | ) { | |
| 39 | ! | stop("`protect_luminance` must be a single finite numeric value.") |
| 40 | } | |
| 41 | ! | if (protect_luminance < 0 || protect_luminance > 1) { |
| 42 | ! | stop("`protect_luminance` must be in [0,1].") |
| 43 | } | |
| 44 | ||
| 45 | ! | vibrance = max(min(vibrance, 1), -1) |
| 46 | ||
| 47 | ! | temp_image = ray_read_image(image, reset_camera_settings = TRUE) # returns RGBA array in rayimage |
| 48 | ||
| 49 | ! | nr = dim(temp_image)[1] |
| 50 | ! | nc = dim(temp_image)[2] |
| 51 | ||
| 52 | ! | r = as.vector(temp_image[,, 1]) |
| 53 | ! | g = as.vector(temp_image[,, 2]) |
| 54 | ! | b = as.vector(temp_image[,, 3]) |
| 55 | ||
| 56 | ! | na_mask = is.na(r) | is.na(g) | is.na(b) |
| 57 | ! | if (any(na_mask)) { |
| 58 | ! | r[na_mask] = 0 |
| 59 | ! | g[na_mask] = 0 |
| 60 | ! | b[na_mask] = 0 |
| 61 | } | |
| 62 | ||
| 63 | # Avoid negative values breaking HSV math; keep HDR highs intact. | |
| 64 | ! | r = pmax(r, 0) |
| 65 | ! | g = pmax(g, 0) |
| 66 | ! | b = pmax(b, 0) |
| 67 | ||
| 68 | ! | maxc = pmax(r, pmax(g, b)) |
| 69 | ! | minc = pmin(r, pmin(g, b)) |
| 70 | ! | delta = maxc - minc |
| 71 | ||
| 72 | ! | v = maxc |
| 73 | ! | s = rep(0, length(v)) |
| 74 | ! | nz = maxc > 0 |
| 75 | ! | s[nz] = delta[nz] / maxc[nz] |
| 76 | ||
| 77 | ! | h = rep(0, length(v)) |
| 78 | ! | idx = delta > 0 |
| 79 | ||
| 80 | ! | if (any(idx)) { |
| 81 | ! | idx_r = idx & (maxc == r) |
| 82 | ! | idx_g = idx & (maxc == g) & !idx_r |
| 83 | ! | idx_b = idx & (maxc == b) & !(idx_r | idx_g) |
| 84 | ||
| 85 | ! | if (any(idx_r)) { |
| 86 | ! | h[idx_r] = (g[idx_r] - b[idx_r]) / delta[idx_r] |
| 87 | ! | h[idx_r][h[idx_r] < 0] = h[idx_r][h[idx_r] < 0] + 6 |
| 88 | } | |
| 89 | ! | if (any(idx_g)) { |
| 90 | ! | h[idx_g] = (b[idx_g] - r[idx_g]) / delta[idx_g] + 2 |
| 91 | } | |
| 92 | ! | if (any(idx_b)) { |
| 93 | ! | h[idx_b] = (r[idx_b] - g[idx_b]) / delta[idx_b] + 4 |
| 94 | } | |
| 95 | ! | h[idx] = h[idx] / 6 |
| 96 | ! | h = h - floor(h) # wrap into [0,1) |
| 97 | } | |
| 98 | ||
| 99 | ! | if (protect_luminance > 0) { |
| 100 | ! | v01 = pmin(v, 1) |
| 101 | ! | w = 1 - protect_luminance * abs(2 * v01 - 1) |
| 102 | ! | w = pmax(w, 0) |
| 103 | } else { | |
| 104 | ! | w = 1 |
| 105 | } | |
| 106 | ||
| 107 | ! | if (vibrance >= 0) { |
| 108 | ! | s2 = s + vibrance * (1 - s) * w |
| 109 | } else { | |
| 110 | ! | s2 = s + vibrance * s * w |
| 111 | } | |
| 112 | ! | s2 = pmin(pmax(s2, 0), 1) |
| 113 | ||
| 114 | # HSV -> RGB (vectorized), preserving HDR v | |
| 115 | ! | r2 = v |
| 116 | ! | g2 = v |
| 117 | ! | b2 = v |
| 118 | ||
| 119 | ! | sat = s2 |
| 120 | ! | idx_sat = sat > 0 |
| 121 | ||
| 122 | ! | if (any(idx_sat)) { |
| 123 | ! | h6 = h * 6 |
| 124 | ! | i = floor(h6) |
| 125 | ! | f = h6 - i |
| 126 | ||
| 127 | ! | p = v * (1 - sat) |
| 128 | ! | q = v * (1 - sat * f) |
| 129 | ! | t = v * (1 - sat * (1 - f)) |
| 130 | ||
| 131 | ! | im = i %% 6 |
| 132 | ||
| 133 | ! | k0 = idx_sat & (im == 0) |
| 134 | ! | k1 = idx_sat & (im == 1) |
| 135 | ! | k2 = idx_sat & (im == 2) |
| 136 | ! | k3 = idx_sat & (im == 3) |
| 137 | ! | k4 = idx_sat & (im == 4) |
| 138 | ! | k5 = idx_sat & (im == 5) |
| 139 | ||
| 140 | ! | if (any(k0)) { |
| 141 | ! | r2[k0] = v[k0] |
| 142 | ! | g2[k0] = t[k0] |
| 143 | ! | b2[k0] = p[k0] |
| 144 | } | |
| 145 | ! | if (any(k1)) { |
| 146 | ! | r2[k1] = q[k1] |
| 147 | ! | g2[k1] = v[k1] |
| 148 | ! | b2[k1] = p[k1] |
| 149 | } | |
| 150 | ! | if (any(k2)) { |
| 151 | ! | r2[k2] = p[k2] |
| 152 | ! | g2[k2] = v[k2] |
| 153 | ! | b2[k2] = t[k2] |
| 154 | } | |
| 155 | ! | if (any(k3)) { |
| 156 | ! | r2[k3] = p[k3] |
| 157 | ! | g2[k3] = q[k3] |
| 158 | ! | b2[k3] = v[k3] |
| 159 | } | |
| 160 | ! | if (any(k4)) { |
| 161 | ! | r2[k4] = t[k4] |
| 162 | ! | g2[k4] = p[k4] |
| 163 | ! | b2[k4] = v[k4] |
| 164 | } | |
| 165 | ! | if (any(k5)) { |
| 166 | ! | r2[k5] = v[k5] |
| 167 | ! | g2[k5] = p[k5] |
| 168 | ! | b2[k5] = q[k5] |
| 169 | } | |
| 170 | } | |
| 171 | ||
| 172 | ! | if (any(na_mask)) { |
| 173 | ! | r2[na_mask] = NA_real_ |
| 174 | ! | g2[na_mask] = NA_real_ |
| 175 | ! | b2[na_mask] = NA_real_ |
| 176 | } | |
| 177 | ||
| 178 | ! | temp_image[,, 1] = matrix(r2, nrow = nr, ncol = nc) |
| 179 | ! | temp_image[,, 2] = matrix(g2, nrow = nr, ncol = nc) |
| 180 | ! | temp_image[,, 3] = matrix(b2, nrow = nr, ncol = nc) |
| 181 | ||
| 182 | ! | handle_image_output(temp_image, filename = filename, preview = preview) |
| 183 | } |
| 1 | #'@title Plot Image Grid | |
| 2 | #' | |
| 3 | #'@description Displays the image in the current device. | |
| 4 | #' | |
| 5 | #'@param input_list List of 3-layer RGB/4-layer RGBA array, `rayimg` class, or image filenames. | |
| 6 | #'@param dim Default `c(1,1)`. Width by height of output grid. | |
| 7 | #'@param asp Default `1`. Aspect ratio of the pixels(s). For example, an aspect ratio of `4/3` will | |
| 8 | #'slightly widen the image. This can also be a vector the same length of | |
| 9 | #'`input_list` to specify an aspect ratio for each image in the grid. | |
| 10 | #'@param draw_grid Default `FALSE`. If `TRUE`, this will draw a grid in the background to help | |
| 11 | #'disambiguate the actual image from the device (helpful if the image background is the same as the | |
| 12 | #'device's background). | |
| 13 | #'@param gp A `grid::gpar()` object to include for the grid viewport displaying the image. | |
| 14 | #'@export | |
| 15 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 16 | #'#Plot the dragon array | |
| 17 | #'plot_image_grid(list(dragon, 1-dragon), dim = c(1,2)) | |
| 18 | #'plot_image_grid(list(dragon, 1-dragon), dim = c(2,1)) | |
| 19 | #'plot_image_grid(list(dragon, NULL, 1-dragon), dim = c(2,2), asp = c(2,1,1/2)) | |
| 20 | #'plot_image_grid(list(dragon, NULL, NULL, dragon), dim = c(2,2), asp = c(2,1,1,1/2)) | |
| 21 | #'#Plot alongside the depth matrix | |
| 22 | #'dragon_depth_reoriented = render_reorient(dragondepth, | |
| 23 | #' transpose = TRUE, | |
| 24 | #' flipx = TRUE)/2000 | |
| 25 | #'plot_image_grid(list(dragondepth/2000, dragon, dragon, dragondepth/2000), | |
| 26 | #' dim = c(2,2)) | |
| 27 | plot_image_grid = function( | |
| 28 | input_list, | |
| 29 | dim = c(1, 1), | |
| 30 | asp = 1, | |
| 31 | draw_grid = FALSE, | |
| 32 | gp = grid::gpar() | |
| 33 | ) { | |
| 34 | ! | if (length(dim) != 2) { |
| 35 | ! | stop("length of `dim` argument must equal 2") |
| 36 | } | |
| 37 | ! | if (!inherits(input_list, "list")) { |
| 38 | ! | stop("`input_list` must be a list of image arrays") |
| 39 | } | |
| 40 | ||
| 41 | ! | if (length(asp) == 1) { |
| 42 | ! | asp = rep(asp, length(input_list)) |
| 43 | ! | } else if (length(asp) != length(input_list)) { |
| 44 | ! | stop(sprintf( |
| 45 | ! | "length of `asp` (%i) not equal to length of `input_list` (%i) or length-1", |
| 46 | ! | length(asp), |
| 47 | ! | length(input_list) |
| 48 | )) | |
| 49 | } | |
| 50 | ||
| 51 | ! | if (length(input_list) > dim[1] * dim[2]) { |
| 52 | ! | warning(sprintf( |
| 53 | ! | "`input_list` of length %i, but grid only has %ix%i=%i slots: truncating list of images", |
| 54 | ! | length(input_list), |
| 55 | ! | dim[1], |
| 56 | ! | dim[2], |
| 57 | ! | dim[1] * dim[2] |
| 58 | )) | |
| 59 | ! | input_list = input_list[seq_len(dim[1] * dim[2])] |
| 60 | } | |
| 61 | ||
| 62 | ! | grid::grid.newpage() |
| 63 | ||
| 64 | # optional background grid — push, draw, then pop | |
| 65 | ! | if (draw_grid) { |
| 66 | ! | grid::pushViewport( |
| 67 | ! | grid::viewport(layout = grid::grid.layout(1, 1), name = "ray_bg_grid") |
| 68 | ) | |
| 69 | ! | grid_density = 0.01 |
| 70 | ! | for (i in seq(-2, 2, by = grid_density)) { |
| 71 | ! | grid::grid.lines( |
| 72 | ! | x = c(0, 1), |
| 73 | ! | y = c(i, i + 1), |
| 74 | ! | default.units = "npc", |
| 75 | ! | gp = grid::gpar(col = "grey") |
| 76 | ) | |
| 77 | ! | grid::grid.lines( |
| 78 | ! | x = c(0, 1), |
| 79 | ! | y = c(i, i - 1), |
| 80 | ! | default.units = "npc", |
| 81 | ! | gp = grid::gpar(col = "grey") |
| 82 | ) | |
| 83 | } | |
| 84 | ! | grid::upViewport() # pop "ray_bg_grid" |
| 85 | } | |
| 86 | ||
| 87 | # parent layout viewport | |
| 88 | ! | grid::pushViewport(grid::viewport( |
| 89 | ! | name = "ray_image_grid", |
| 90 | ! | layout = grid::grid.layout(nrow = dim[1], ncol = dim[2]), |
| 91 | ! | gp = gp |
| 92 | )) | |
| 93 | ! | on.exit( |
| 94 | { | |
| 95 | # ensure we fully unwind no matter what | |
| 96 | ! | try(grid::upViewport(0), silent = TRUE) |
| 97 | }, | |
| 98 | ! | add = TRUE |
| 99 | ) | |
| 100 | ||
| 101 | ! | layout_idx = data.frame( |
| 102 | ! | y = rep(seq_len(dim[1]), each = dim[2]), |
| 103 | ! | x = rep(seq_len(dim[2]), dim[1]) |
| 104 | ) | |
| 105 | ||
| 106 | ! | for (i in seq_len(length(input_list))) { |
| 107 | # enter the parent (in case caller changed current vp) | |
| 108 | ! | grid::seekViewport("ray_image_grid") |
| 109 | # push cell viewport, draw, then pop it | |
| 110 | ! | grid::pushViewport(grid::viewport( |
| 111 | ! | layout.pos.row = layout_idx$y[i], |
| 112 | ! | layout.pos.col = layout_idx$x[i], |
| 113 | ! | name = sprintf("ray_cell_%i_%i", layout_idx$x[i], layout_idx$y[i]), |
| 114 | ! | gp = gp |
| 115 | )) | |
| 116 | ! | if (!is.null(input_list[[i]])) { |
| 117 | ! | rayimage::plot_image(input_list[[i]], asp = asp[i], new_page = FALSE) |
| 118 | } | |
| 119 | ! | grid::upViewport() # pop cell |
| 120 | } | |
| 121 | ||
| 122 | ! | grid::upViewport() # pop "ray_image_grid" |
| 123 | ! | invisible(NULL) |
| 124 | } |
| 1 | #'@title Read Image | |
| 2 | #' | |
| 3 | #'@description Reads an image from a file/array/matrix. From files, supports | |
| 4 | #'`JPEG`, `PNG`, `TIFF`, `TGA`, `BMP`, `PSD`, `GIF`, `HDR`, `PIC`, `PNM`, `EXR`, | |
| 5 | #'and `DNG` images. | |
| 6 | #' | |
| 7 | #' @param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 8 | #' @param convert_to_array Default `FALSE`. Whether to convert 2D B&W images/matrices to RGBA arrays. | |
| 9 | #' @param preview Default `FALSE`. If `TRUE`, it will display the image in addition | |
| 10 | #'to returning it. | |
| 11 | #' @param source_linear Default `NA`, automatically determined based on the image type. | |
| 12 | #' Whether the image source is linear data or sRGB. `TRUE` for matrices, arrays, and | |
| 13 | #' floating-point HDR formats (`EXR`, `HDR`), and `DNG`; `FALSE` for all other file-based formats | |
| 14 | #' (e.g., `jpeg`, `png`, `tiff`, `tga`, `bmp`, `psd`, `gif`, `pic`, `pnm`). | |
| 15 | #' @param normalize Default `FALSE`. If `TRUE`, convert to `normalize_to` space on read. Note that | |
| 16 | #' rayimg inputs will keep their colorspace and ignore this option--use `render_convert_colorspace()` | |
| 17 | #' to change an existing rayimg to a new colorspace. | |
| 18 | #' @param dng_normalize Default `FALSE`. If `TRUE`, DNG data is normalized to 0..1, | |
| 19 | #' using black/white levels; if `FALSE`, raw values are returned. | |
| 20 | #' @param normalize_to Default `CS_ACESCG`. Target colorspace when `normalize=TRUE`. | |
| 21 | #' @param normalize_adapt_white Default `TRUE`. If `TRUE`, Bradford-adapt source white to target white. | |
| 22 | #' @param assume_colorspace Default `NULL`. A colorspace descriptor (e.g., `CS_SRGB`, | |
| 23 | #' `CS_ACESCG`). If given, the loaded image will be *tagged* with this space | |
| 24 | #' rather than the default inferred by file type. No pixel conversion is performed | |
| 25 | #' unless `normalize=TRUE`. | |
| 26 | #' @param assume_white Default `NULL`. Scene/display white for the loaded image. | |
| 27 | #' Either a named white (`"D60","D65","D50","D55","D75","E"`) or XYZ with Y=1. | |
| 28 | #' If `NULL`, uses `assume_colorspace$white_xyz`. | |
| 29 | #' @param reset_camera_settings Default `FALSE`. If `TRUE`, reset informational | |
| 30 | #' exposure/ISO metadata to neutral values (`exposure = 0`, `iso = 100`) when | |
| 31 | #' wrapping an existing `rayimg` or attributed array. | |
| 32 | #' | |
| 33 | #'@param ... Arguments to pass to `jpeg::readJPEG`, `png::readPNG`, `tiff::readTIFF`, | |
| 34 | #'or `libopenexr::read_exr()` for supported formats. | |
| 35 | #' | |
| 36 | #'@return A `rayimg` RGBA array. | |
| 37 | #'@import grDevices | |
| 38 | #'@export | |
| 39 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 40 | #'#Write as a png | |
| 41 | #'tmparr = tempfile(fileext=".png") | |
| 42 | #'ray_read_image(dragon) |> | |
| 43 | #' ray_write_image(tmparr) | |
| 44 | #'ray_read_image(tmparr) |> | |
| 45 | #' plot_image() | |
| 46 | #'#Write as a JPEG (passing quality arguments via ...) | |
| 47 | #'tmparr = tempfile(fileext=".jpg") | |
| 48 | #'ray_read_image(dragon) |> | |
| 49 | #' ray_write_image(tmparr, quality = 0.2) | |
| 50 | #'ray_read_image(tmparr) |> | |
| 51 | #' plot_image() | |
| 52 | #'#Write as a tiff | |
| 53 | #'tmparr = tempfile(fileext=".tiff") | |
| 54 | #'ray_read_image(dragon) |> | |
| 55 | #' ray_write_image(tmparr) | |
| 56 | #'ray_read_image(tmparr) |> | |
| 57 | #' plot_image() | |
| 58 | #' | |
| 59 | #'#Write as an exr | |
| 60 | #'tmparr = tempfile(fileext=".exr") | |
| 61 | #'ray_read_image(dragon) |> | |
| 62 | #' ray_write_image(tmparr) | |
| 63 | #'ray_read_image(tmparr) |> | |
| 64 | #' plot_image() | |
| 65 | ray_read_image = function( | |
| 66 | image, | |
| 67 | convert_to_array = FALSE, | |
| 68 | preview = FALSE, | |
| 69 | source_linear = NA, | |
| 70 | normalize = FALSE, | |
| 71 | dng_normalize = FALSE, | |
| 72 | normalize_to = CS_ACESCG, | |
| 73 | normalize_adapt_white = TRUE, | |
| 74 | assume_colorspace = NULL, | |
| 75 | assume_white = NULL, | |
| 76 | reset_camera_settings = FALSE, | |
| 77 | ... | |
| 78 | ) { | |
| 79 | 790x | decode_if_needed = function(img, linear_flag) { |
| 80 | 395x | if (isTRUE(linear_flag)) { |
| 81 | 339x | return(list(image = img, source_linear = TRUE)) |
| 82 | } | |
| 83 | 56x | img[is.na(img)] = 0 |
| 84 | ||
| 85 | 56x | if (length(dim(img)) == 3) { |
| 86 | 56x | if (dim(img)[3] >= 3) { |
| 87 | 56x | img[,, 1:3] = to_linear(img[,, 1:3]) |
| 88 | } else { | |
| 89 | ! | img = to_linear(img) |
| 90 | } | |
| 91 | } else { | |
| 92 | ! | img = to_linear(img) |
| 93 | } | |
| 94 | 56x | list(image = img, source_linear = TRUE) |
| 95 | } | |
| 96 | ||
| 97 | 790x | get_wp = function(white_point) { |
| 98 | 398x | wp = get_whitepoint_xyz(white_point) |
| 99 | 398x | if (is.null(wp)) { |
| 100 | ! | return(NULL) |
| 101 | } | |
| 102 | 398x | wp$value |
| 103 | } | |
| 104 | ||
| 105 | 790x | process_image_preview = function(image2) { |
| 106 | 790x | if (convert_to_array) { |
| 107 | 181x | image_val = array(1, dim = c(dim(image2)[1:2], 4)) |
| 108 | 181x | if (length(dim(image2)) == 2) { |
| 109 | ! | image_val[,, 1:3] = image2 |
| 110 | 181x | } else if (length(dim(image2)) == 3) { |
| 111 | 181x | if (dim(image2)[3] == 2) { |
| 112 | ! | image_val[,, 1:3] = image2[,, 1] |
| 113 | ! | image_val[,, 4] = image2[,, 2] |
| 114 | 181x | } else if (dim(image2)[3] == 3) { |
| 115 | 59x | image_val[,, 1:3] = image2[,, 1:3] |
| 116 | 122x | } else if (dim(image2)[3] == 4) { |
| 117 | 122x | image_val = image2 |
| 118 | } | |
| 119 | } | |
| 120 | } else { | |
| 121 | 609x | image_val = image2 |
| 122 | } | |
| 123 | 790x | if (preview) { |
| 124 | ! | plot_image(image_val) |
| 125 | } | |
| 126 | 790x | image_val |
| 127 | } | |
| 128 | ||
| 129 | 790x | imagetype = if ( |
| 130 | 790x | is.character(image) && |
| 131 | 790x | tolower(tools::file_ext(image)) == "dng" |
| 132 | ) { | |
| 133 | 1x | "dng" |
| 134 | } else { | |
| 135 | 789x | get_file_type(image) |
| 136 | } | |
| 137 | 790x | if (is.na(source_linear)) { |
| 138 | # arrays, matrices, and floating-point HDR formats are treated as linear | |
| 139 | 587x | source_linear = imagetype %in% c("array", "matrix", "exr", "hdr", "dng") |
| 140 | } | |
| 141 | ||
| 142 | 790x | finalize_image = function(img, img_type, linear_flag, default_cs) { |
| 143 | 395x | decoded = decode_if_needed(img, linear_flag) |
| 144 | 395x | cs = if (!is.null(assume_colorspace)) { |
| 145 | 204x | assume_colorspace |
| 146 | } else { | |
| 147 | 395x | switch( |
| 148 | 191x | img_type, |
| 149 | 46x | png = CS_SRGB, |
| 150 | 2x | jpg = CS_SRGB, |
| 151 | 2x | tif = CS_SRGB, |
| 152 | 1x | tga = CS_SRGB, |
| 153 | 1x | bmp = CS_SRGB, |
| 154 | 1x | psd = CS_SRGB, |
| 155 | 1x | gif = CS_SRGB, |
| 156 | 1x | pic = CS_SRGB, |
| 157 | 1x | pnm = CS_SRGB, |
| 158 | 1x | hdr = CS_ACESCG, |
| 159 | ! | exr = CS_ACESCG, |
| 160 | 121x | array = default_cs, |
| 161 | 12x | matrix = default_cs, |
| 162 | 1x | CS_ACESCG |
| 163 | ) | |
| 164 | } | |
| 165 | 395x | wc = get_wp(if (!is.null(assume_white)) assume_white else cs$white_xyz) |
| 166 | 395x | ri = rayimg( |
| 167 | 395x | process_image_preview(decoded$image), |
| 168 | 395x | filetype = img_type, |
| 169 | 395x | source_linear = decoded$source_linear, |
| 170 | 395x | colorspace = cs, |
| 171 | 395x | white_current = wc, |
| 172 | 395x | exposure = if (reset_camera_settings) { |
| 173 | 54x | 0 |
| 174 | } else { | |
| 175 | 341x | attr(img, "exposure", exact = TRUE) |
| 176 | }, | |
| 177 | 395x | iso = if (reset_camera_settings) 100 else attr(img, "iso", exact = TRUE) |
| 178 | ) | |
| 179 | 395x | if (normalize) { |
| 180 | ! | ri = render_convert_colorspace( |
| 181 | ! | ri, |
| 182 | ! | from_mats = NA, |
| 183 | ! | to_mats = normalize_to, |
| 184 | ! | adapt_white = normalize_adapt_white, |
| 185 | ! | from_white = NA, |
| 186 | ! | to_white = normalize_to$white_xyz |
| 187 | ) | |
| 188 | } | |
| 189 | 395x | ri |
| 190 | } | |
| 191 | ||
| 192 | 790x | if (inherits(image, "rayimg")) { |
| 193 | 391x | cs_assigned = if (!is.null(assume_colorspace)) { |
| 194 | 3x | assume_colorspace |
| 195 | } else { | |
| 196 | 388x | attr(image, "colorspace") |
| 197 | } | |
| 198 | 391x | wc_assigned = if (!is.null(assume_white)) { |
| 199 | 3x | get_wp(assume_white) |
| 200 | } else { | |
| 201 | 388x | attr(image, "white_current") |
| 202 | } | |
| 203 | 391x | ri = rayimg( |
| 204 | 391x | process_image_preview(image), |
| 205 | 391x | filetype = attr(image, "filetype"), |
| 206 | 391x | source_linear = attr(image, "source_linear"), |
| 207 | 391x | colorspace = cs_assigned, |
| 208 | 391x | white_current = wc_assigned, |
| 209 | 391x | exposure = if (reset_camera_settings) { |
| 210 | 211x | 0 |
| 211 | } else { | |
| 212 | 180x | attr(image, "exposure", exact = TRUE) |
| 213 | }, | |
| 214 | 391x | iso = if (reset_camera_settings) 100 else attr(image, "iso", exact = TRUE) |
| 215 | ) | |
| 216 | 391x | return(ri) # no normalization on rayimg here |
| 217 | } | |
| 218 | ||
| 219 | 399x | if (imagetype == "array") { |
| 220 | 263x | return(finalize_image(image, imagetype, source_linear, CS_ACESCG)) |
| 221 | 136x | } else if (imagetype == "matrix") { |
| 222 | 74x | if (length(dim(image)) == 3) { |
| 223 | ! | return(finalize_image( |
| 224 | ! | image[,, 1], |
| 225 | ! | imagetype, |
| 226 | ! | source_linear, |
| 227 | ! | CS_ACESCG |
| 228 | )) | |
| 229 | } | |
| 230 | 74x | return(finalize_image(image, imagetype, source_linear, CS_ACESCG)) |
| 231 | 62x | } else if (imagetype == "dng") { |
| 232 | 1x | out = read_dng_cpp(image, normalize = dng_normalize) |
| 233 | 1x | pixels = out$pixels |
| 234 | 1x | meta = out$meta |
| 235 | if ( | |
| 236 | 1x | !is.null(meta$orientation) && |
| 237 | 1x | !is.na(meta$orientation) && |
| 238 | 1x | meta$orientation != 1 |
| 239 | ) { | |
| 240 | ! | orientation = as.integer(meta$orientation) |
| 241 | ! | flipx = FALSE |
| 242 | ! | flipy = FALSE |
| 243 | ! | transpose = FALSE |
| 244 | ! | if (orientation == 2L) { |
| 245 | ! | flipx = TRUE |
| 246 | ! | } else if (orientation == 3L) { |
| 247 | ! | flipx = TRUE |
| 248 | ! | flipy = TRUE |
| 249 | ! | } else if (orientation == 4L) { |
| 250 | ! | flipy = TRUE |
| 251 | ! | } else if (orientation == 5L) { |
| 252 | ! | transpose = TRUE |
| 253 | ! | } else if (orientation == 6L) { |
| 254 | ! | flipy = TRUE |
| 255 | ! | transpose = TRUE |
| 256 | ! | } else if (orientation == 7L) { |
| 257 | ! | flipx = TRUE |
| 258 | ! | flipy = TRUE |
| 259 | ! | transpose = TRUE |
| 260 | ! | } else if (orientation == 8L) { |
| 261 | ! | flipx = TRUE |
| 262 | ! | transpose = TRUE |
| 263 | } | |
| 264 | ! | if (flipx) { |
| 265 | ! | pixels = fliplr(pixels) |
| 266 | } | |
| 267 | ! | if (flipy) { |
| 268 | ! | pixels = flipud(pixels) |
| 269 | } | |
| 270 | ! | if (transpose) { |
| 271 | ! | if (length(dim(pixels)) == 2) { |
| 272 | ! | pixels = t(pixels) |
| 273 | } else { | |
| 274 | ! | pixels = aperm(pixels, c(2, 1, 3)) |
| 275 | } | |
| 276 | ! | if (!is.null(meta$width) && !is.null(meta$height)) { |
| 277 | ! | tmp_dim = meta$width |
| 278 | ! | meta$width = meta$height |
| 279 | ! | meta$height = tmp_dim |
| 280 | } | |
| 281 | } | |
| 282 | ! | if (!is.null(meta$cfa_pattern)) { |
| 283 | ! | cfa = meta$cfa_pattern |
| 284 | ! | if (flipx) { |
| 285 | ! | cfa = cfa[, 2:1, drop = FALSE] |
| 286 | } | |
| 287 | ! | if (flipy) { |
| 288 | ! | cfa = cfa[2:1, , drop = FALSE] |
| 289 | } | |
| 290 | ! | if (transpose) { |
| 291 | ! | cfa = t(cfa) |
| 292 | } | |
| 293 | ! | meta$cfa_pattern = cfa |
| 294 | } | |
| 295 | ! | meta$orientation = 1L |
| 296 | } | |
| 297 | 1x | attr(pixels, "dng") = meta |
| 298 | 1x | if (!is.na(source_linear) && !source_linear) { |
| 299 | ! | pixels = decode_if_needed(pixels, source_linear)$image |
| 300 | } | |
| 301 | 1x | return(finalize_image(pixels, "dng", TRUE, CS_ACESCG)) |
| 302 | 61x | } else if (imagetype == "png") { |
| 303 | 46x | image = png::readPNG(image, ...) |
| 304 | 46x | return(finalize_image(image, imagetype, source_linear, CS_SRGB)) |
| 305 | 15x | } else if (imagetype == "tif") { |
| 306 | 2x | image = tiff::readTIFF(image, ...) |
| 307 | 2x | return(finalize_image(image, imagetype, source_linear, CS_SRGB)) |
| 308 | 13x | } else if (imagetype == "jpg") { |
| 309 | 2x | image = jpeg::readJPEG(image, ...) |
| 310 | 2x | return(finalize_image(image, imagetype, source_linear, CS_SRGB)) |
| 311 | 11x | } else if (imagetype == "hdr") { |
| 312 | 1x | image = read_image_stb(image, desired_channels = 4L) |
| 313 | 1x | return(finalize_image(image, imagetype, source_linear, CS_ACESCG)) |
| 314 | 10x | } else if (imagetype %in% c("tga", "bmp", "psd", "gif", "pic", "pnm")) { |
| 315 | 6x | image = read_image_stb(image, desired_channels = 4L) |
| 316 | 6x | return(finalize_image(image, imagetype, source_linear, CS_SRGB)) |
| 317 | 4x | } else if (imagetype == "exr") { |
| 318 | 4x | if (length(find.package("libopenexr", quiet = TRUE)) > 0) { |
| 319 | 4x | tmp = libopenexr::read_exr(image, ...) |
| 320 | 4x | metadata = tmp$metadata |
| 321 | 4x | exr_colorspace = colorspace_from_exr_metadata(metadata) |
| 322 | 4x | exr_white_current = white_current_from_exr_metadata(metadata) |
| 323 | 4x | colorspace = if (!is.null(assume_colorspace)) { |
| 324 | ! | assume_colorspace |
| 325 | 4x | } else if (!is.null(exr_colorspace)) { |
| 326 | 2x | exr_colorspace |
| 327 | } else { | |
| 328 | 2x | CS_ACESCG |
| 329 | } | |
| 330 | 4x | white_current = if (!is.null(assume_white)) { |
| 331 | ! | get_wp(assume_white) |
| 332 | 4x | } else if (!is.null(exr_white_current)) { |
| 333 | 2x | exr_white_current |
| 334 | } else { | |
| 335 | 2x | colorspace$white_xyz |
| 336 | } | |
| 337 | 4x | image = array(1, dim = c(tmp$height, tmp$width, 4)) |
| 338 | 4x | image[,, 1] = tmp$r |
| 339 | 4x | image[,, 2] = tmp$g |
| 340 | 4x | image[,, 3] = tmp$b |
| 341 | 4x | ri = rayimg( |
| 342 | 4x | process_image_preview(image), |
| 343 | 4x | filetype = imagetype, |
| 344 | 4x | source_linear = TRUE, |
| 345 | 4x | colorspace = colorspace, |
| 346 | 4x | white_current = white_current |
| 347 | ) | |
| 348 | 4x | if (is.list(metadata) && length(metadata) > 0L) { |
| 349 | 2x | preserved_metadata = preserved_exr_metadata(metadata) |
| 350 | 2x | if (!is.null(preserved_metadata)) { |
| 351 | 1x | attr(ri, "exr") = preserved_metadata |
| 352 | } | |
| 353 | } | |
| 354 | 4x | if (normalize) { |
| 355 | ! | ri = render_convert_colorspace( |
| 356 | ! | ri, |
| 357 | ! | from_mats = NA, |
| 358 | ! | to_mats = normalize_to, |
| 359 | ! | adapt_white = normalize_adapt_white, |
| 360 | ! | from_white = NA, |
| 361 | ! | to_white = normalize_to$white_xyz |
| 362 | ) | |
| 363 | } | |
| 364 | 4x | return(ri) |
| 365 | } else { | |
| 366 | ! | stop("The 'libopenexr' package is required for EXR support.") |
| 367 | } | |
| 368 | } else { | |
| 369 | ! | stop("Unsupported/unknown input type.") |
| 370 | } | |
| 371 | } |
| 1 | #' @title Render Tonemap | |
| 2 | #' | |
| 3 | #' @description Reinhard / Uncharted(Hable) / HBD operators in linear | |
| 4 | #' | |
| 5 | #' @param image Default `NULL`. 3/4-channel array, `rayimg`, or filename. | |
| 6 | #' @param method Default `raw`. One of `"raw"`, `"reinhard"`, `"uncharted"`, `"hbd"`. | |
| 7 | #' Chooses the global tone-mapping curve. `"raw"` leaves the image unchanged. | |
| 8 | #' `"reinhard"` applies a classic shoulder that gently compresses highlights. | |
| 9 | #' `"uncharted"` (Hable filmic) gives a film-style toe/shoulder and keeps mid-tones contrasty. | |
| 10 | #' `"hbd"` is a fast filmic-like curve with a soft toe/shoulder. | |
| 11 | #' All methods operate on **linear RGB** and return **display-referred linear** (no OETF). | |
| 12 | #' @param exposure_bias Default `2`. Only for `"uncharted"`. | |
| 13 | #' Scalar applied to the linear RGB channels **before** the Uncharted/Hable curve | |
| 14 | #' (i.e., a pre-curve exposure gain). Values >1 brighten; <1 darken. | |
| 15 | #' `exposure_bias=2` is about +1 stop; `0.5` is about -1 stop. | |
| 16 | #' @param W Default `11.2`. White (linear scene value) that maps to 1.0 **after** | |
| 17 | #' the Uncharted/Hable/Reinhard curve. Acts like a “white point” for the shoulder: larger values | |
| 18 | #' preserve more highlight detail (later roll-off), smaller values roll off earlier and harder. | |
| 19 | #' @param filename Default `NULL`. Output path. | |
| 20 | #' @param preview Default `FALSE`. Show result. | |
| 21 | #' @return A `rayimg` RGBA array. | |
| 22 | #' @export | |
| 23 | #' @examples | |
| 24 | #' # Plot unchanged image | |
| 25 | #' render_tonemap(dragon, preview = TRUE) | |
| 26 | #' # Plot Reinhard tonemapped image | |
| 27 | #' render_tonemap(dragon, method = "reinhard", preview = TRUE) | |
| 28 | #' # Plot Uncharted/Hable tonemapped image | |
| 29 | #' render_tonemap(dragon, method = "uncharted",preview = TRUE) | |
| 30 | #' # Plot Uncharted/Hable tonemapped image, white point adjusted | |
| 31 | #' render_tonemap(dragon, method = "uncharted", W=11.4, preview = TRUE) | |
| 32 | #' # Plot Uncharted/Hable tonemapped image, exposure adjusted | |
| 33 | #' render_tonemap(dragon, method = "uncharted", exposure_bias = 1,preview = TRUE) | |
| 34 | #' # Plot Hejl-Burgess-Dawson tonemapped image, exposure adjusted | |
| 35 | #' render_tonemap(dragon, method = "hbd",preview = TRUE) | |
| 36 | render_tonemap = function( | |
| 37 | image, | |
| 38 | method = c("raw", "reinhard", "uncharted", "hbd"), | |
| 39 | exposure_bias = 2.0, | |
| 40 | W = 11.2, | |
| 41 | filename = NULL, | |
| 42 | preview = FALSE | |
| 43 | ) { | |
| 44 | 2x | method = match.arg(method) |
| 45 | 2x | src = ray_read_image( |
| 46 | 2x | image, |
| 47 | 2x | convert_to_array = TRUE, |
| 48 | 2x | reset_camera_settings = TRUE |
| 49 | ) | |
| 50 | 2x | imagetype = attr(src, "filetype") |
| 51 | 2x | img_source_linear = attr(src, "source_linear") |
| 52 | 2x | colorspace = attr(src, "colorspace") |
| 53 | 2x | white_current = attr(src, "white_current") |
| 54 | ||
| 55 | 2x | colorspace_luminance_row = attr(src, "colorspace")$rgb_to_xyz[2, ] |
| 56 | 2x | d = dim(src) |
| 57 | 2x | if (length(d) != 3) { |
| 58 | ! | return(src) |
| 59 | } | |
| 60 | ||
| 61 | 2x | rgb = src[,, 1:3] |
| 62 | ||
| 63 | 2x | if (method == "reinhard") { |
| 64 | ! | eps = 1e-6 |
| 65 | ! | lw = colorspace_luminance_row |
| 66 | ||
| 67 | ! | L = lw[1] * rgb[,, 1] + lw[2] * rgb[,, 2] + lw[3] * rgb[,, 3] |
| 68 | ||
| 69 | ! | a = 0.18 |
| 70 | ! | L_log_avg = exp(mean(log(pmax(L, eps)))) |
| 71 | ||
| 72 | ! | Lm = (a / L_log_avg) * L |
| 73 | ! | Lwhite = W #White point |
| 74 | ! | Ld = (Lm * (1 + (Lm / (Lwhite * Lwhite)))) / (1 + Lm) |
| 75 | ||
| 76 | ! | scale = Ld / pmax(L, eps) |
| 77 | ||
| 78 | ! | rgb[,, 1] = rgb[,, 1] * scale |
| 79 | ! | rgb[,, 2] = rgb[,, 2] * scale |
| 80 | ! | rgb[,, 3] = rgb[,, 3] * scale |
| 81 | 2x | } else if (method == "uncharted") { |
| 82 | ! | A = 0.15 |
| 83 | ! | B = 0.50 |
| 84 | ! | C = 0.10 |
| 85 | ! | D = 0.20 |
| 86 | ! | E = 0.02 |
| 87 | ! | F = 0.30 |
| 88 | ! | eps = 1e-6 |
| 89 | ||
| 90 | ! | lw = colorspace_luminance_row |
| 91 | ! | L = lw[1] * rgb[,, 1] + lw[2] * rgb[,, 2] + lw[3] * rgb[,, 3] |
| 92 | ||
| 93 | # Key normalization | |
| 94 | ! | a = 0.18 |
| 95 | ! | L_log_avg = exp(mean(log(pmax(L, eps)))) |
| 96 | ! | pre_key = a / L_log_avg |
| 97 | ||
| 98 | ! | hable = function(x) { |
| 99 | ! | ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F) - E / F) |
| 100 | } | |
| 101 | ||
| 102 | ! | e = exposure_bias |
| 103 | ! | whiteScale = 1 / hable(e * W) |
| 104 | ||
| 105 | ! | Lm = e * pre_key * L |
| 106 | ! | Ld = hable(Lm) * whiteScale |
| 107 | ! | scale = Ld / pmax(L, eps) |
| 108 | ||
| 109 | ! | rgb[,, 1] = rgb[,, 1] * scale |
| 110 | ! | rgb[,, 2] = rgb[,, 2] * scale |
| 111 | ! | rgb[,, 3] = rgb[,, 3] * scale |
| 112 | 2x | } else if (method == "hbd") { |
| 113 | 1x | for (k in 1:3) { |
| 114 | 3x | x = pmax(rgb[,, k] - 0.004, 0) |
| 115 | 3x | encoded = (x * (6.2 * x + 0.5)) / (x * (6.2 * x + 1.7) + 0.06) |
| 116 | # HBD includes display encoding. Return linear pixels, like the other | |
| 117 | # operators, so plotting and writing apply the display transfer once. | |
| 118 | 3x | rgb[,, k] = to_linear(encoded) |
| 119 | } | |
| 120 | } else { | |
| 121 | # Nothing | |
| 122 | } | |
| 123 | ||
| 124 | 2x | out = src |
| 125 | 2x | out[,, 1:3] = rgb |
| 126 | ||
| 127 | 2x | out = ray_read_image( |
| 128 | 2x | out, |
| 129 | 2x | filetype = imagetype, |
| 130 | 2x | source_linear = img_source_linear, |
| 131 | 2x | assume_colorspace = colorspace, |
| 132 | 2x | assume_white = white_current |
| 133 | ) | |
| 134 | 2x | handle_image_output(out, filename = filename, preview = preview) |
| 135 | } |
| 1 | #' Print method for rayimg | |
| 2 | #' | |
| 3 | #' Displays the working colorspace and non-neutral camera metadata alongside a numeric preview. | |
| 4 | #' | |
| 5 | #' @param x Default `NULL`. A `rayimg` object. | |
| 6 | #' @param preview_n Default `10`. Max rows/cols to display in numeric preview. | |
| 7 | #' @param decimals Default `3`. Number of decimal places to display in numeric preview. | |
| 8 | #' @param color Default `TRUE`. Colorize headers and R/G/B/A numeric cells when supported. | |
| 9 | #' @param ... Default ``. Ignored. | |
| 10 | #' | |
| 11 | #' @return Invisibly returns `x`. | |
| 12 | #' @export | |
| 13 | print.rayimg = function( | |
| 14 | x = NULL, | |
| 15 | preview_n = 10, | |
| 16 | decimals = 3, | |
| 17 | color = TRUE, | |
| 18 | ... | |
| 19 | ) { | |
| 20 | 74x | ft = attr(x, "filetype") |
| 21 | 74x | if (is.null(ft)) { |
| 22 | ! | ft = "unknown" |
| 23 | } | |
| 24 | 74x | d = dim(x) |
| 25 | 74x | image_type = attr(x, "filetype") |
| 26 | 74x | exposure_attr = rayimg_exposure_value(attr(x, "exposure", exact = TRUE)) |
| 27 | 74x | iso_attr = rayimg_iso_value(attr(x, "iso", exact = TRUE)) |
| 28 | ||
| 29 | 74x | opt_override = getOption("rayimage.color", NA) |
| 30 | 74x | want_color = isTRUE(color) && !isFALSE(opt_override) |
| 31 | 74x | have_cli = want_color && requireNamespace("cli", quietly = TRUE) |
| 32 | 74x | can_color = have_cli && |
| 33 | 74x | isTRUE(cli::num_ansi_colors() >= 8) && |
| 34 | 74x | isTRUE(cli::is_dynamic_tty()) && |
| 35 | 74x | !isTRUE(getOption("knitr.in.progress")) && |
| 36 | 74x | !isTRUE(getOption("testthat.in_progress")) |
| 37 | 74x | truecolor_ok = rayimg_truecolor_supported() |
| 38 | ||
| 39 | 74x | style_bold = function(z) if (can_color) cli::style_bold(z) else z |
| 40 | 74x | col_magenta = function(z) if (can_color) cli::col_magenta(z) else z |
| 41 | 74x | col_yellow = function(z) if (can_color) cli::col_yellow(z) else z |
| 42 | 74x | col_cyan = function(z) if (can_color) cli::col_cyan(z) else z |
| 43 | 74x | col_silver = function(z) if (can_color) cli::col_silver(z) else z |
| 44 | 74x | col_red = function(z) if (can_color) cli::col_red(z) else z |
| 45 | 74x | col_green = function(z) if (can_color) cli::col_green(z) else z |
| 46 | 74x | col_blue = function(z) if (can_color) cli::col_blue(z) else z |
| 47 | ||
| 48 | 74x | print_camera_settings = function() { |
| 49 | 74x | if ( |
| 50 | 74x | isTRUE(all.equal(exposure_attr, 0)) && isTRUE(all.equal(iso_attr, 100)) |
| 51 | ) { | |
| 52 | 73x | return(invisible(NULL)) |
| 53 | } | |
| 54 | 1x | cat( |
| 55 | " ", | |
| 56 | 1x | col_silver("Exposure: "), |
| 57 | 1x | col_cyan(sprintf("%+.3g EV", exposure_attr)), |
| 58 | " ", | |
| 59 | 1x | col_silver("ISO: "), |
| 60 | 1x | col_cyan(format(iso_attr, trim = TRUE, scientific = FALSE)), |
| 61 | 1x | "\n", |
| 62 | 1x | sep = "" |
| 63 | ) | |
| 64 | 1x | invisible(NULL) |
| 65 | } | |
| 66 | ||
| 67 | 74x | hell = if ( |
| 68 | 74x | requireNamespace("cli", quietly = TRUE) && |
| 69 | 74x | isTRUE(cli::is_utf8_output()) |
| 70 | ) { | |
| 71 | ! | cli::symbol$ellipsis |
| 72 | } else { | |
| 73 | "..." | |
| 74 | } | |
| 75 | 74x | vell = rayimg_vertical_ellipsis(TRUE) |
| 76 | ||
| 77 | # Vector fallback | |
| 78 | 74x | if (is.null(d)) { |
| 79 | ! | cat( |
| 80 | ! | col_magenta(style_bold("<rayimg>")), |
| 81 | " ", | |
| 82 | ! | col_silver(sprintf("[length %d]", length(x))), |
| 83 | " ", | |
| 84 | ! | col_yellow("<vector>"), |
| 85 | " ", | |
| 86 | ! | "filetype: ", |
| 87 | ! | col_cyan(ft), |
| 88 | ! | "\n", |
| 89 | ! | sep = "" |
| 90 | ) | |
| 91 | ! | print_camera_settings() |
| 92 | ! | y_plain = formatC(as.numeric(x), format = "f", digits = decimals) |
| 93 | ! | print(y_plain, quote = FALSE, right = TRUE) |
| 94 | ! | return(invisible(x)) |
| 95 | } | |
| 96 | ||
| 97 | 74x | h = d[1] |
| 98 | 74x | w = d[2] |
| 99 | 74x | c = if (length(d) >= 3) d[3] else 1L |
| 100 | ||
| 101 | 74x | chan_labels = attr(x, "channels") |
| 102 | ||
| 103 | 74x | if (!length(chan_labels)) { |
| 104 | ! | chan_labels = rayimg_detect_channels(x) |
| 105 | } | |
| 106 | ||
| 107 | 74x | type_str = paste0(chan_labels, collapse = " + ") |
| 108 | ||
| 109 | 74x | cat( |
| 110 | 74x | col_magenta(style_bold("<rayimg>")), |
| 111 | " ", | |
| 112 | 74x | col_silver(sprintf( |
| 113 | 74x | "[%d x %d%s]", |
| 114 | 74x | h, |
| 115 | 74x | w, |
| 116 | 34x | if (c > 1) paste0(" x ", c) else "" |
| 117 | )), | |
| 118 | " ", | |
| 119 | 74x | col_yellow(paste0("<", type_str, ">")), |
| 120 | " ", | |
| 121 | 74x | "filetype: ", |
| 122 | 74x | col_cyan(ft), |
| 123 | 74x | " Linear Data: ", |
| 124 | 74x | col_green(as.character(attr(x, "source_linear"))), |
| 125 | 74x | "\n", |
| 126 | 74x | sep = "" |
| 127 | ) | |
| 128 | 74x | cs_attr = attr(x, "colorspace") |
| 129 | 74x | white_attr = attr(x, "white_current") |
| 130 | ||
| 131 | 74x | describe_colorspace = function(cs) { |
| 132 | 74x | if (!is.list(cs)) { |
| 133 | ! | return("unknown") |
| 134 | } | |
| 135 | 74x | nm = cs$name |
| 136 | 74x | if (is.null(nm) || length(nm) != 1L) { |
| 137 | ! | nm = "unknown" |
| 138 | } | |
| 139 | 74x | desc = as.character(nm) |
| 140 | 74x | wn = cs$white_name |
| 141 | 74x | if (!is.null(wn) && length(wn) == 1L) { |
| 142 | 74x | desc = paste0(desc, " (white ", wn, ")") |
| 143 | } | |
| 144 | 74x | desc |
| 145 | } | |
| 146 | 74x | describe_white = function(white_vec) { |
| 147 | 74x | if ( |
| 148 | 74x | is.numeric(white_vec) && |
| 149 | 74x | length(white_vec) == 3L && |
| 150 | 74x | all(is.finite(white_vec)) |
| 151 | ) { | |
| 152 | 74x | paste0( |
| 153 | "[", | |
| 154 | 74x | paste( |
| 155 | 74x | formatC(as.numeric(white_vec), format = "f", digits = 5), |
| 156 | 74x | collapse = ", " |
| 157 | ), | |
| 158 | "]" | |
| 159 | ) | |
| 160 | } else { | |
| 161 | ! | "unknown" |
| 162 | } | |
| 163 | } | |
| 164 | 74x | cs_desc = describe_colorspace(cs_attr) |
| 165 | 74x | white_desc = describe_white(white_attr) |
| 166 | 74x | white_col = if (identical(white_desc, "unknown")) col_silver else col_blue |
| 167 | ||
| 168 | 74x | cat( |
| 169 | " ", | |
| 170 | 74x | col_silver("Working colorspace: "), |
| 171 | 74x | col_blue(cs_desc), |
| 172 | " ", | |
| 173 | 74x | col_silver("White XYZ: "), |
| 174 | 74x | white_col(white_desc), |
| 175 | 74x | "\n", |
| 176 | 74x | sep = "" |
| 177 | ) | |
| 178 | 74x | print_camera_settings() |
| 179 | ||
| 180 | # Numeric preview | |
| 181 | 74x | rmax = min(h, preview_n) |
| 182 | 74x | cmax = min(w, preview_n) |
| 183 | 74x | more_rows = h > preview_n |
| 184 | 74x | more_cols = w > preview_n |
| 185 | 74x | if (more_rows || more_cols) { |
| 186 | 37x | msg = sprintf( |
| 187 | 37x | "showing [1:%d, 1:%d]%s plus last row/col", |
| 188 | 37x | rmax, |
| 189 | 37x | cmax, |
| 190 | 37x | if (c > 1) ", all channels" else "" |
| 191 | ) | |
| 192 | 37x | cat(col_silver(msg), "\n", sep = "") |
| 193 | } | |
| 194 | ||
| 195 | 74x | ux = unclass(x) |
| 196 | ||
| 197 | # Alpha analysis based on displayed labels; get physical alpha plane correctly | |
| 198 | 74x | has_alpha = "Alpha" %in% chan_labels |
| 199 | 74x | suppress_alpha = FALSE |
| 200 | 74x | alpha_idx = -1 |
| 201 | 74x | if (has_alpha && length(dim(ux)) > 2) { |
| 202 | 18x | alpha_idx = which("Alpha" == chan_labels) |
| 203 | 18x | aplane = ux[,, alpha_idx, drop = FALSE] |
| 204 | 18x | alpha_all_one = all(abs(aplane - 1) <= 1e-8, na.rm = TRUE) |
| 205 | 18x | suppress_alpha = alpha_all_one |
| 206 | } | |
| 207 | ||
| 208 | # Colorizers for numeric cells | |
| 209 | 74x | col_fun = function(lbl) { |
| 210 | 126x | if (!can_color) { |
| 211 | 126x | return(identity) |
| 212 | } | |
| 213 | 74x | switch( |
| 214 | ! | lbl, |
| 215 | ! | "Red" = col_red, |
| 216 | ! | "Green" = col_green, |
| 217 | ! | "Blue" = col_blue, |
| 218 | ! | "Alpha" = col_cyan, |
| 219 | ! | identity |
| 220 | ) | |
| 221 | } | |
| 222 | 74x | hdr_col_fun = function(lbl) { |
| 223 | 126x | if (!can_color) { |
| 224 | 126x | return(function(z) z) |
| 225 | } | |
| 226 | 74x | switch( |
| 227 | ! | lbl, |
| 228 | ! | "Red" = col_red, |
| 229 | ! | "Green" = col_green, |
| 230 | ! | "Blue" = col_blue, |
| 231 | ! | "Alpha" = col_cyan, |
| 232 | ! | function(z) z |
| 233 | ) | |
| 234 | } | |
| 235 | 74x | fmt = function(v) formatC(as.numeric(v), format = "f", digits = decimals) |
| 236 | ||
| 237 | 74x | build_preview_pair = function(mat_numeric, f_color) { |
| 238 | 126x | mat_numeric = unclass(mat_numeric) |
| 239 | 126x | if (is.null(dim(mat_numeric))) { |
| 240 | 19x | print_tl = mat_numeric |
| 241 | } else { | |
| 242 | 107x | print_tl = mat_numeric[seq_len(rmax), seq_len(cmax), drop = TRUE] |
| 243 | } | |
| 244 | 126x | tl_plain = matrix( |
| 245 | 126x | fmt(print_tl), |
| 246 | 126x | nrow = rmax, |
| 247 | 126x | ncol = cmax |
| 248 | ) | |
| 249 | 126x | tl_disp = tl_plain |
| 250 | ||
| 251 | 126x | if (more_cols) { |
| 252 | 31x | last_col_plain = fmt(mat_numeric[seq_len(rmax), w, drop = TRUE]) |
| 253 | 31x | ell_col_plain = rep(hell, rmax) |
| 254 | 31x | tl_plain = cbind(tl_plain, ell_col_plain, last_col_plain) |
| 255 | 31x | tl_disp = cbind( |
| 256 | 31x | tl_disp, |
| 257 | 31x | if (can_color) col_silver(ell_col_plain) else ell_col_plain, |
| 258 | 31x | last_col_plain |
| 259 | ) | |
| 260 | } | |
| 261 | ||
| 262 | 126x | if (more_rows) { |
| 263 | 46x | last_row_first_plain = fmt(mat_numeric[h, seq_len(cmax), drop = TRUE]) |
| 264 | 46x | if (more_cols) { |
| 265 | 16x | last_row_plain = c( |
| 266 | 16x | last_row_first_plain, |
| 267 | 16x | hell, |
| 268 | 16x | fmt(mat_numeric[h, w, drop = TRUE]) |
| 269 | ) | |
| 270 | 16x | last_row_disp = c( |
| 271 | 16x | last_row_first_plain, |
| 272 | 16x | if (can_color) col_silver(hell) else hell, |
| 273 | 16x | fmt(mat_numeric[h, w, drop = TRUE]) |
| 274 | ) | |
| 275 | } else { | |
| 276 | 30x | last_row_plain = last_row_first_plain |
| 277 | 30x | last_row_disp = last_row_first_plain |
| 278 | } | |
| 279 | 46x | ell_row_plain = rep(vell, ncol(tl_plain)) |
| 280 | 46x | ell_row_disp = if (can_color) col_silver(ell_row_plain) else ell_row_plain |
| 281 | ||
| 282 | 46x | tl_plain = rbind(tl_plain, ell_row_plain, last_row_plain) |
| 283 | 46x | tl_disp = rbind(tl_disp, ell_row_disp, last_row_disp) |
| 284 | } | |
| 285 | ||
| 286 | 126x | cn_base = if (more_cols) { |
| 287 | 31x | c( |
| 288 | 31x | paste0("[,", seq_len(cmax), "]"), |
| 289 | 31x | paste0("[,", hell, "]"), |
| 290 | 31x | paste0("[,", w, "]") |
| 291 | ) | |
| 292 | } else { | |
| 293 | 95x | paste0("[,", seq_len(cmax), "]") |
| 294 | } | |
| 295 | 126x | rn_base = if (more_rows) { |
| 296 | 46x | c( |
| 297 | 46x | paste0("[", seq_len(rmax), ",]"), |
| 298 | 46x | paste0("[", vell, ",]"), |
| 299 | 46x | paste0("[", h, ",]") |
| 300 | ) | |
| 301 | } else { | |
| 302 | 80x | paste0("[", seq_len(rmax), ",]") |
| 303 | } | |
| 304 | ||
| 305 | 126x | dimnames(tl_plain) = list(rn_base, cn_base) |
| 306 | 126x | dimnames(tl_disp) = dimnames(tl_plain) |
| 307 | ||
| 308 | 126x | if (!identical(f_color, identity)) { |
| 309 | ! | mask_num = !(tl_disp %in% c(hell, vell)) |
| 310 | ! | tl_disp[mask_num] = f_color(tl_disp[mask_num]) |
| 311 | } | |
| 312 | ||
| 313 | 126x | list(plain = tl_plain, disp = tl_disp) |
| 314 | } | |
| 315 | ||
| 316 | 74x | print_matrix_ansi = function(mat_plain, mat_disp) { |
| 317 | 126x | stopifnot(identical(dim(mat_plain), dim(mat_disp))) |
| 318 | 126x | rn = rownames(mat_plain) |
| 319 | 126x | cn = colnames(mat_plain) |
| 320 | 126x | pad = function(s, w) { |
| 321 | 12939x | vis = if (can_color) { |
| 322 | ! | cli::ansi_nchar(s, type = "width") |
| 323 | } else { | |
| 324 | 12939x | nchar(s, type = "width") |
| 325 | } | |
| 326 | 12939x | if (vis < w) { |
| 327 | 2966x | return(paste0(strrep(" ", w - vis), s)) |
| 328 | } else { | |
| 329 | 9973x | return(s) |
| 330 | } | |
| 331 | } | |
| 332 | 126x | rn_w = max(nchar(rn, type = "width")) |
| 333 | 126x | col_w = vapply( |
| 334 | 126x | seq_len(ncol(mat_plain)), |
| 335 | 126x | function(j) { |
| 336 | 1260x | max(nchar(c(cn[j], mat_plain[, j]), type = "width")) |
| 337 | }, | |
| 338 | 126x | integer(1) |
| 339 | ) | |
| 340 | ||
| 341 | 126x | cat(strrep(" ", rn_w + 1)) |
| 342 | 126x | for (j in seq_len(ncol(mat_plain))) { |
| 343 | 1260x | cat(" ", pad(cn[j], col_w[j]), sep = "") |
| 344 | } | |
| 345 | 126x | cat("\n") |
| 346 | 126x | for (i in seq_len(nrow(mat_plain))) { |
| 347 | 1034x | cat(pad(rn[i], rn_w), " ", sep = "") |
| 348 | 1034x | for (j in seq_len(ncol(mat_plain))) { |
| 349 | 10645x | cat(" ", pad(mat_disp[i, j], col_w[j]), sep = "") |
| 350 | } | |
| 351 | 1034x | cat("\n") |
| 352 | } | |
| 353 | } | |
| 354 | ||
| 355 | # ---- 2-D (single-channel) path ---- | |
| 356 | # This colors slices the appropriate color (e.g. red if it's the red slice) | |
| 357 | 74x | if (length(d) == 2L || c == 1L) { |
| 358 | 34x | chan_hint = if (length(chan_labels)) chan_labels[1] else "Grayscale" |
| 359 | 34x | cat( |
| 360 | 34x | hdr_col_fun(chan_hint)(style_bold(paste0("[", chan_hint, "]"))), |
| 361 | 34x | "\n", |
| 362 | 34x | sep = "" |
| 363 | ) | |
| 364 | 34x | pair = build_preview_pair(ux, f_color = col_fun(chan_hint)) |
| 365 | 34x | print_matrix_ansi(pair$plain, pair$disp) |
| 366 | 34x | return(invisible(x)) |
| 367 | } | |
| 368 | ||
| 369 | 40x | for (i in seq_along(chan_labels)) { |
| 370 | 108x | if (has_alpha && suppress_alpha && i == alpha_idx) { |
| 371 | 16x | next |
| 372 | } | |
| 373 | 92x | lbl = chan_labels[i] |
| 374 | 92x | cat(hdr_col_fun(lbl)(style_bold(paste0("[", lbl, "]"))), "\n", sep = "") |
| 375 | 92x | pair = build_preview_pair( |
| 376 | 92x | ux[,, i, drop = TRUE], |
| 377 | 92x | f_color = col_fun(lbl) |
| 378 | ) | |
| 379 | 92x | print_matrix_ansi(pair$plain, pair$disp) |
| 380 | ||
| 381 | if ( | |
| 382 | 92x | i < length(chan_labels) && |
| 383 | 92x | !(suppress_alpha && (i + 1L) == alpha_idx) |
| 384 | ) { | |
| 385 | 52x | cat("\n") |
| 386 | } | |
| 387 | } | |
| 388 | if ( | |
| 389 | 40x | suppress_alpha && |
| 390 | 40x | chan_labels[length(chan_labels)] == "Alpha" |
| 391 | ) { | |
| 392 | 15x | cat(col_silver(style_bold("[A] No transparency (layer all 1.0)\n"))) |
| 393 | } | |
| 394 | ||
| 395 | 40x | invisible(x) |
| 396 | } |
| 1 | #' @title Add Transparent Padding | |
| 2 | #' | |
| 3 | #' @description Expands an image or matrix canvas by adding constant-value | |
| 4 | #' padding around the original image. | |
| 5 | #' | |
| 6 | #' @param image 3-layer RGB/4-layer RGBA array, `rayimg` class, matrix, or | |
| 7 | #' filename of an image. | |
| 8 | #' @param pad Default `10`. Padding in pixels. Use a scalar for equal padding on | |
| 9 | #' all sides, or `c(top, right, bottom, left)`. | |
| 10 | #' @param color Default `"black"`. Padding color. Can be a scalar, RGB/RGBA | |
| 11 | #' numeric vector, or R color string. | |
| 12 | #' @param alpha Default `NULL`. Padding alpha for images with an alpha channel. | |
| 13 | #' If `NULL`, uses the alpha channel supplied in `color` when present, otherwise | |
| 14 | #' defaults to `0` when `color` is omitted and `1` when `color` is supplied. | |
| 15 | #' Ignored for RGB and matrix inputs. | |
| 16 | #' @param filename Default `NULL`. File to save the image to. If `NULL` and | |
| 17 | #' `preview = FALSE`, returns the padded image. | |
| 18 | #' @param preview Default `FALSE`. If `TRUE`, display the padded image. | |
| 19 | #' | |
| 20 | #' @return A padded `rayimg` image or matrix. | |
| 21 | #' @export | |
| 22 | #' @rdname render_padding | |
| 23 | #' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 24 | #'render_padding(dragon, pad = 20) |> | |
| 25 | #' plot_image() | |
| 26 | render_padding = function( | |
| 27 | image, | |
| 28 | pad = 10, | |
| 29 | color = "black", | |
| 30 | alpha = NULL, | |
| 31 | filename = NULL, | |
| 32 | preview = FALSE | |
| 33 | ) { | |
| 34 | 28x | if (is.null(image)) { |
| 35 | ! | stop("`image` must be provided.") |
| 36 | } | |
| 37 | ||
| 38 | 28x | color_missing = missing(color) |
| 39 | 28x | color = convert_color(color, single = TRUE) |
| 40 | 27x | color_alpha = if (length(color) >= 4 && !color_missing) { |
| 41 | 24x | color[4] |
| 42 | } else { | |
| 43 | 3x | NULL |
| 44 | } | |
| 45 | 27x | if (is.null(alpha)) { |
| 46 | 12x | alpha = if (!is.null(color_alpha)) { |
| 47 | 10x | color_alpha |
| 48 | 12x | } else if (color_missing) { |
| 49 | 2x | 0 |
| 50 | } else { | |
| 51 | ! | 1 |
| 52 | } | |
| 53 | } | |
| 54 | 27x | if (!is.numeric(alpha) || length(alpha) != 1 || !is.finite(alpha)) { |
| 55 | ! | stop("`alpha` must be a finite numeric scalar.") |
| 56 | } | |
| 57 | 27x | if (alpha < 0 || alpha > 1) { |
| 58 | ! | stop("`alpha` must be in [0,1].") |
| 59 | } | |
| 60 | 27x | pad = normalize_render_padding(pad) |
| 61 | 27x | pad_values = unname(pad) |
| 62 | ||
| 63 | 27x | temp_image = ray_read_image(image, convert_to_array = FALSE) |
| 64 | 27x | image_dim = dim(temp_image) |
| 65 | 27x | channels = if (length(image_dim) == 2) { |
| 66 | 7x | 1L |
| 67 | } else { | |
| 68 | 20x | image_dim[3] |
| 69 | } | |
| 70 | 27x | fill = switch( |
| 71 | 27x | as.character(channels), |
| 72 | 27x | `1` = color[1], |
| 73 | 27x | `2` = c(color[1], alpha), |
| 74 | 27x | `3` = color[1:3], |
| 75 | 27x | `4` = c(color[1:3], alpha), |
| 76 | 27x | stop("`image` must have 1, 2, 3, or 4 channels.") |
| 77 | ) | |
| 78 | ||
| 79 | 27x | if (length(image_dim) == 2) { |
| 80 | 7x | output = matrix( |
| 81 | 7x | fill[1], |
| 82 | 7x | nrow = image_dim[1] + pad_values[1] + pad_values[3], |
| 83 | 7x | ncol = image_dim[2] + pad_values[2] + pad_values[4] |
| 84 | ) | |
| 85 | 7x | output[ |
| 86 | 7x | (pad_values[1] + 1):(pad_values[1] + image_dim[1]), |
| 87 | 7x | (pad_values[4] + 1):(pad_values[4] + image_dim[2]) |
| 88 | 7x | ] = unclass(temp_image) |
| 89 | } else { | |
| 90 | 20x | output = array( |
| 91 | 20x | 0, |
| 92 | 20x | dim = c( |
| 93 | 20x | image_dim[1] + pad_values[1] + pad_values[3], |
| 94 | 20x | image_dim[2] + pad_values[2] + pad_values[4], |
| 95 | 20x | image_dim[3] |
| 96 | ) | |
| 97 | ) | |
| 98 | 20x | for (i in seq_len(image_dim[3])) { |
| 99 | 80x | output[,, i] = fill[i] |
| 100 | } | |
| 101 | 20x | output[ |
| 102 | 20x | (pad_values[1] + 1):(pad_values[1] + image_dim[1]), |
| 103 | 20x | (pad_values[4] + 1):(pad_values[4] + image_dim[2]), |
| 104 | 20x | seq_len(image_dim[3]) |
| 105 | 20x | ] = unclass(temp_image) |
| 106 | } | |
| 107 | ||
| 108 | 27x | output = rayimg( |
| 109 | 27x | output, |
| 110 | 27x | filetype = attr(temp_image, "filetype"), |
| 111 | 27x | source_linear = attr(temp_image, "source_linear"), |
| 112 | 27x | colorspace = attr(temp_image, "colorspace"), |
| 113 | 27x | white_current = attr(temp_image, "white_current"), |
| 114 | 27x | exposure = attr(temp_image, "exposure", exact = TRUE), |
| 115 | 27x | iso = attr(temp_image, "iso", exact = TRUE) |
| 116 | ) | |
| 117 | 27x | attr(output, "padding") = pad |
| 118 | 27x | handle_image_output(output, filename = filename, preview = preview) |
| 119 | } | |
| 120 | ||
| 121 | #' @keywords internal | |
| 122 | normalize_render_padding = function(pad) { | |
| 123 | 49x | if (!is.numeric(pad) || !(length(pad) %in% c(1, 4))) { |
| 124 | ! | stop("`pad` must be a numeric scalar or length-4 vector.") |
| 125 | } | |
| 126 | 49x | if (any(!is.finite(pad)) || any(pad < 0)) { |
| 127 | ! | stop("`pad` must contain non-negative finite values.") |
| 128 | } | |
| 129 | 49x | pad = as.integer(round(pad)) |
| 130 | 49x | if (length(pad) == 1) { |
| 131 | 29x | pad = rep(pad, 4) |
| 132 | } | |
| 133 | 49x | names(pad) = c("top", "right", "bottom", "left") |
| 134 | 49x | pad |
| 135 | } |
| 1 | #'@title Preview Focus | |
| 2 | #' | |
| 3 | #'@description Displays the focal point | |
| 4 | #' | |
| 5 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 6 | #'@param depthmap Depth map filename or 1d array. | |
| 7 | #'@param focus Defaults `0.5`. Depth in which to blur. Minimum 0, maximum 1. | |
| 8 | #'@keywords internal | |
| 9 | #'@examples | |
| 10 | #'#Plot the dragon | |
| 11 | preview_focus = function(image, depthmap, focus, imagetype, depthtype) { | |
| 12 | ! | image = ray_read_image(image) #Always output RGBA array |
| 13 | #Check if file or image before below: | |
| 14 | ! | depthmap = ray_read_image(depthmap, convert_to_array = FALSE) |
| 15 | ! | if (length(dim(depthmap)) == 3) { |
| 16 | ! | depthmap = depthmap[,, 1] |
| 17 | } | |
| 18 | ||
| 19 | ! | isimage = max(depthmap, na.rm = TRUE) == 1 |
| 20 | ! | if (isimage) { |
| 21 | ! | maxval = max(depthmap[depthmap != 1], na.rm = TRUE) |
| 22 | } else { | |
| 23 | ! | maxval = max(depthmap, na.rm = TRUE) |
| 24 | } | |
| 25 | ! | if (isimage) { |
| 26 | ! | depthmap[depthmap == 1] = maxval |
| 27 | } | |
| 28 | ! | depthrange = range(depthmap, na.rm = TRUE) |
| 29 | ! | range_depth_high = focus + depthrange[2] / 200 |
| 30 | ! | range_depth_low = focus - depthrange[1] / 200 |
| 31 | ! | if (range_depth_high >= maxval) { |
| 32 | ! | range_depth_high = range_depth_high - range(depthmap)[2] / 200 |
| 33 | } | |
| 34 | if ( | |
| 35 | ! | any(depthmap < range_depth_high, na.rm = TRUE) & |
| 36 | ! | any(depthmap > range_depth_low, na.rm = TRUE) |
| 37 | ) { | |
| 38 | ! | image[,, 1][depthmap < range_depth_high & depthmap > range_depth_low] = 1 |
| 39 | ! | image[,, 2][depthmap < range_depth_high & depthmap > range_depth_low] = 0 |
| 40 | ! | image[,, 3][depthmap < range_depth_high & depthmap > range_depth_low] = 0 |
| 41 | ! | message(sprintf("Focal range: %g-%g", depthrange[1], depthrange[2])) |
| 42 | ! | plot_image(image) |
| 43 | } else { | |
| 44 | ! | message(sprintf( |
| 45 | ! | "Focus point (%g) not in focal range: %g-%g", |
| 46 | ! | focus, |
| 47 | ! | depthrange[1], |
| 48 | ! | depthrange[2] |
| 49 | )) | |
| 50 | } | |
| 51 | } |
| 1 | #' Vertical ellipsis symbol | |
| 2 | #' | |
| 3 | #' @param use_cli Default `TRUE`. If `TRUE`, consult `cli::is_utf8_output()` for Unicode support. | |
| 4 | #' @return vertical ellipses if supported | |
| 5 | #' @keywords internal | |
| 6 | rayimg_vertical_ellipsis = function(use_cli = TRUE) { | |
| 7 | 74x | have_cli = use_cli && requireNamespace("cli", quietly = TRUE) |
| 8 | 74x | unicode_ok = if (have_cli) { |
| 9 | 74x | isTRUE(cli::is_utf8_output()) |
| 10 | } else { | |
| 11 | ! | isTRUE(l10n_info()[["UTF-8"]]) |
| 12 | } | |
| 13 | ! | if (unicode_ok) "\u22EE" else "..." |
| 14 | } | |
| 15 | ||
| 16 | #' @keywords internal | |
| 17 | rayimg_truecolor_supported = function() { | |
| 18 | if (!requireNamespace("cli", quietly = TRUE)) { | |
| 19 | return(FALSE) | |
| 20 | } | |
| 21 | dyn = isTRUE(cli::is_dynamic_tty()) | |
| 22 | utf8 = isTRUE(cli::is_utf8_output()) | |
| 23 | ncol = cli::num_ansi_colors() | |
| 24 | tc = grepl("truecolor|24bit", Sys.getenv("COLORTERM", ""), ignore.case = TRUE) | |
| 25 | dyn && utf8 && (tc || isTRUE(ncol >= 256)) | |
| 26 | } | |
| 27 | ||
| 28 | #' Compose RGB over checkerboard using alpha | |
| 29 | #' @keywords internal | |
| 30 | rayimg_composite_checker = function( | |
| 31 | rgb, | |
| 32 | alpha = NULL, | |
| 33 | light = 0.92, | |
| 34 | dark = 0.75 | |
| 35 | ) { | |
| 36 | ! | d = dim(rgb) |
| 37 | ! | H = d[1] |
| 38 | ! | W = d[2] |
| 39 | ! | if (is.null(alpha)) { |
| 40 | ! | return(rgb) |
| 41 | } | |
| 42 | ! | pat = outer(seq_len(H), seq_len(W), function(i, j) (i + j) %% 2L == 0L) |
| 43 | ! | bg = array(dark, dim = c(H, W, 3)) |
| 44 | ! | bg[pat] = light |
| 45 | ! | out = array(0, dim = c(H, W, 3)) |
| 46 | ! | for (k in 1:3) { |
| 47 | ! | out[,, k] = rgb[,, k] * alpha + bg[,, k] * (1 - alpha) |
| 48 | } | |
| 49 | ! | return(out) |
| 50 | } | |
| 51 | ||
| 52 | # Truecolor detection | |
| 53 | rayimg_truecolor_supported = function() { | |
| 54 | 74x | if (!requireNamespace("cli", quietly = TRUE)) { |
| 55 | ! | return(FALSE) |
| 56 | } | |
| 57 | 74x | dyn = isTRUE(cli::is_dynamic_tty()) |
| 58 | 74x | utf8 = isTRUE(cli::is_utf8_output()) |
| 59 | # Require an explicit hint for 24-bit (COLORTERM), or a TERM that advertises it (rare) | |
| 60 | 74x | tc = grepl("truecolor|24bit", Sys.getenv("COLORTERM", ""), ignore.case = TRUE) |
| 61 | 74x | term = Sys.getenv("TERM", "") |
| 62 | 74x | direct = grepl("direct", term, ignore.case = TRUE) # e.g. xterm-direct/kitty-direct |
| 63 | 74x | dyn && utf8 && (tc || direct) |
| 64 | } | |
| 65 | ||
| 66 | # Map RGB [0, 255] to nearest xterm-256 index | |
| 67 | rayimg_rgb_to_xterm256 = function(r, g, b) { | |
| 68 | # 6x6x6 color cube | |
| 69 | ! | lev = c(0, 95, 135, 175, 215, 255) |
| 70 | ! | idx = function(x) { |
| 71 | ! | which.min((lev - x)^2) - 1L |
| 72 | } | |
| 73 | ! | ri = idx(r) |
| 74 | ! | gi = idx(g) |
| 75 | ! | bi = idx(b) |
| 76 | ! | cube_idx = 16L + 36L * ri + 6L * gi + bi |
| 77 | ! | cube_rgb = c(lev[ri + 1L], lev[gi + 1L], lev[bi + 1L]) |
| 78 | ||
| 79 | # grayscale ramp [232-255] (approx [8-238] step 10) | |
| 80 | ! | gray_val = round((r + g + b) / 3) |
| 81 | ! | gray_i = as.integer(pmin(23L, pmax(0L, round((gray_val - 8) / 10)))) |
| 82 | ! | gray_idx = 232L + gray_i |
| 83 | ! | gray_rgb = rep(8L + 10L * gray_i, 3L) |
| 84 | ||
| 85 | # choose closer | |
| 86 | ! | d_cube = sum((c(r, g, b) - cube_rgb)^2) |
| 87 | ! | d_gray = sum((c(r, g, b) - gray_rgb)^2) |
| 88 | ! | if (d_gray < d_cube) { |
| 89 | ! | return(gray_idx) |
| 90 | } else { | |
| 91 | ! | return(cube_idx) |
| 92 | } | |
| 93 | } | |
| 94 | ||
| 95 | # One ANSI cell with 24-bit or 256-color fallback | |
| 96 | # style: "auto" pick bg/fg based on luminance; "block"/"bg" force mode; "bg256"/"block256" force 256-color | |
| 97 | rayimg_ansi_cell = function( | |
| 98 | r, | |
| 99 | g, | |
| 100 | b, | |
| 101 | style = c("auto", "block", "bg", "bg256", "block256") | |
| 102 | ) { | |
| 103 | ! | style = match.arg(style) |
| 104 | ! | r = as.integer(pmin(pmax(round(r), 0L), 255L)) |
| 105 | ! | g = as.integer(pmin(pmax(round(g), 0L), 255L)) |
| 106 | ! | b = as.integer(pmin(pmax(round(b), 0L), 255L)) |
| 107 | ||
| 108 | ! | tc_ok = rayimg_truecolor_supported() |
| 109 | ||
| 110 | # luminance coefs | |
| 111 | ! | Y = 0.2126 * r + 0.7152 * g + 0.0722 * b |
| 112 | ! | if (style == "auto") { |
| 113 | ! | style = if (tc_ok) { |
| 114 | ! | (if (Y < 80) "block" else "bg") |
| 115 | } else { | |
| 116 | ! | (if (Y < 80) "block256" else "bg256") |
| 117 | } | |
| 118 | } | |
| 119 | ||
| 120 | # 24-bit variants | |
| 121 | ! | if (style == "bg" && tc_ok) { |
| 122 | ! | return(paste0("\033[48;2;", r, ";", g, ";", b, "m", " ", "\033[0m")) |
| 123 | } | |
| 124 | ! | if (style == "block" && tc_ok) { |
| 125 | ! | return(paste0( |
| 126 | ! | "\033[38;2;", |
| 127 | ! | r, |
| 128 | ";", | |
| 129 | ! | g, |
| 130 | ";", | |
| 131 | ! | b, |
| 132 | ! | "m", |
| 133 | ! | "\u2588\u2588", |
| 134 | ! | "\033[0m" |
| 135 | )) | |
| 136 | } | |
| 137 | ||
| 138 | # 256-color fallback | |
| 139 | ! | idx = rayimg_rgb_to_xterm256(r, g, b) |
| 140 | ! | if (style %in% c("bg256", "bg")) { |
| 141 | ! | return(paste0("\033[48;5;", idx, "m", " ", "\033[0m")) |
| 142 | } | |
| 143 | ! | if (style %in% c("block256", "block")) { |
| 144 | ! | return(paste0("\033[38;5;", idx, "m", "\u2588\u2588", "\033[0m")) |
| 145 | } | |
| 146 | ||
| 147 | # last resort | |
| 148 | ! | "\u2588\u2588" |
| 149 | } |
| 1 | #' Estimate Lat-Long Environment White | |
| 2 | #' | |
| 3 | #' @description Estimate the scene white produced by a lat-long environment map. | |
| 4 | #' The default weighting matches the irradiance seen by an upward-facing diffuse | |
| 5 | #' surface: `cos(theta) * d_omega` over the upper hemisphere. | |
| 6 | #' | |
| 7 | #' @param environment_map Lat-long environment map image, `rayimg`, array, or filename. | |
| 8 | #' @param weighting Default `"cosine"`. Weighting method. `"cosine"` computes | |
| 9 | #' upward diffuse irradiance; `"solid_angle"` computes an unprojected spherical | |
| 10 | #' average. | |
| 11 | #' @param hemisphere Default `"upper"`. Hemisphere to use. `"upper"` uses only | |
| 12 | #' rows above the horizon; `"full"` uses the full lat-long map. | |
| 13 | #' @param environment_colorspace Default `NULL`. Optional colorspace descriptor | |
| 14 | #' used to tag `environment_map` on read. | |
| 15 | #' @param environment_white Default `NULL`. Optional white point used to tag | |
| 16 | #' `environment_map` on read. | |
| 17 | #' | |
| 18 | #' @return Length-3 XYZ white point normalized to `Y = 1`. The returned vector | |
| 19 | #' includes `rgb`, `rgb_ratio`, `xy`, approximate `cct`, `sum_weights`, | |
| 20 | #' `weighting`, and `hemisphere` attributes for diagnostics. | |
| 21 | #' @export | |
| 22 | estimate_environment_white = function( | |
| 23 | environment_map, | |
| 24 | weighting = c("cosine", "solid_angle"), | |
| 25 | hemisphere = c("upper", "full"), | |
| 26 | environment_colorspace = NULL, | |
| 27 | environment_white = NULL | |
| 28 | ) { | |
| 29 | 4x | weighting = match.arg(weighting) |
| 30 | 4x | hemisphere = match.arg(hemisphere) |
| 31 | ||
| 32 | 4x | env = ray_read_image( |
| 33 | 4x | environment_map, |
| 34 | 4x | normalize = FALSE, |
| 35 | 4x | assume_colorspace = environment_colorspace, |
| 36 | 4x | assume_white = environment_white |
| 37 | ) | |
| 38 | 4x | d = dim(env) |
| 39 | 4x | if (length(d) != 3L || d[3] < 3L) { |
| 40 | ! | stop( |
| 41 | ! | "estimate_environment_white(): environment_map must have RGB channels." |
| 42 | ) | |
| 43 | } | |
| 44 | ||
| 45 | 4x | colorspace = attr(env, "colorspace", exact = TRUE) |
| 46 | 4x | if (!is.list(colorspace) || is.null(colorspace$rgb_to_xyz)) { |
| 47 | ! | stop( |
| 48 | ! | "estimate_environment_white(): environment_map is missing colorspace metadata." |
| 49 | ) | |
| 50 | } | |
| 51 | ||
| 52 | 4x | n_theta = d[1] |
| 53 | 4x | n_phi = d[2] |
| 54 | 4x | theta = ((seq_len(n_theta) - 0.5) / n_theta) * pi |
| 55 | 4x | d_theta = pi / n_theta |
| 56 | 4x | d_phi = 2 * pi / n_phi |
| 57 | ||
| 58 | 4x | weights = sin(theta) * d_theta * d_phi |
| 59 | 4x | if (weighting == "cosine") { |
| 60 | 4x | weights = weights * pmax(cos(theta), 0) |
| 61 | } | |
| 62 | 4x | if (hemisphere == "upper") { |
| 63 | 4x | weights[theta > pi / 2] = 0 |
| 64 | } | |
| 65 | ||
| 66 | 4x | row_weight_sum = sum(weights) |
| 67 | 4x | if (!is.finite(row_weight_sum) || row_weight_sum <= 0) { |
| 68 | ! | stop("estimate_environment_white(): environment weights sum to zero.") |
| 69 | } | |
| 70 | ||
| 71 | 4x | weight_matrix = matrix(weights, nrow = n_theta, ncol = n_phi) |
| 72 | 4x | sum_weights = sum(weight_matrix) |
| 73 | 4x | rgb = vapply( |
| 74 | 4x | seq_len(3L), |
| 75 | 4x | function(channel) { |
| 76 | 12x | sum(env[,, channel] * weight_matrix, na.rm = TRUE) |
| 77 | }, | |
| 78 | 4x | numeric(1) |
| 79 | ) | |
| 80 | ||
| 81 | 4x | if (!all(is.finite(rgb)) || sum(rgb) <= 0) { |
| 82 | ! | stop( |
| 83 | ! | "estimate_environment_white(): estimated environment RGB is not positive and finite." |
| 84 | ) | |
| 85 | } | |
| 86 | ||
| 87 | 4x | xyz = as.vector(colorspace$rgb_to_xyz %*% rgb) |
| 88 | 4x | if (!all(is.finite(xyz)) || xyz[2] <= 0) { |
| 89 | ! | stop( |
| 90 | ! | "estimate_environment_white(): estimated environment XYZ is not positive and finite." |
| 91 | ) | |
| 92 | } | |
| 93 | ||
| 94 | 4x | xyz = xyz / xyz[2] |
| 95 | 4x | xy = c(xyz[1], xyz[2]) / sum(xyz) |
| 96 | 4x | names(xyz) = c("X", "Y", "Z") |
| 97 | 4x | attr(xyz, "rgb") = rgb |
| 98 | 4x | attr(xyz, "rgb_ratio") = rgb / mean(rgb) |
| 99 | 4x | attr(xyz, "xy") = xy |
| 100 | 4x | attr(xyz, "cct") = xy_to_cct_mccamy(xy) |
| 101 | 4x | attr(xyz, "sum_weights") = sum_weights |
| 102 | 4x | attr(xyz, "weighting") = weighting |
| 103 | 4x | attr(xyz, "hemisphere") = hemisphere |
| 104 | 4x | xyz |
| 105 | } | |
| 106 | ||
| 107 | #' White Balance with a Lat-Long Environment Map | |
| 108 | #' | |
| 109 | #' @description Estimate a lat-long environment map's scene white and pass it to | |
| 110 | #' [render_white_balance()] as `reference_white`. This is a camera-style white | |
| 111 | #' balance for renders lit by an environment map. | |
| 112 | #' | |
| 113 | #' @param image 3-layer RGB/4-layer RGBA array, `rayimg`, or filename. | |
| 114 | #' @param environment_map Lat-long environment map image, `rayimg`, array, or filename. | |
| 115 | #' @param target_white Default `"D65"`. Target white (XYZ Y=1 or named). | |
| 116 | #' @param bake Default `TRUE`. Passed to [render_white_balance()]. | |
| 117 | #' @param weighting Default `"cosine"`. Passed to the environment white | |
| 118 | #' estimator. | |
| 119 | #' @param hemisphere Default `"upper"`. Passed to the environment white | |
| 120 | #' estimator. | |
| 121 | #' @param environment_colorspace Default `NULL`. Optional colorspace descriptor | |
| 122 | #' used to tag `environment_map` on read. | |
| 123 | #' @param environment_white Default `NULL`. Optional white point used to tag | |
| 124 | #' `environment_map` on read. | |
| 125 | #' @param filename Default `NULL`. Output path. | |
| 126 | #' @param preview Default `FALSE`. If `TRUE`, display the image. | |
| 127 | #' | |
| 128 | #' @return A white-balanced `rayimg`. The estimated white is attached as the | |
| 129 | #' `environment_white` attribute. | |
| 130 | #' @export | |
| 131 | render_environment_white_balance = function( | |
| 132 | image, | |
| 133 | environment_map, | |
| 134 | target_white = "D65", | |
| 135 | bake = TRUE, | |
| 136 | weighting = "cosine", | |
| 137 | hemisphere = "upper", | |
| 138 | environment_colorspace = NULL, | |
| 139 | environment_white = NULL, | |
| 140 | filename = NULL, | |
| 141 | preview = FALSE | |
| 142 | ) { | |
| 143 | 1x | reference_white = estimate_environment_white( |
| 144 | 1x | environment_map, |
| 145 | 1x | weighting = weighting, |
| 146 | 1x | hemisphere = hemisphere, |
| 147 | 1x | environment_colorspace = environment_colorspace, |
| 148 | 1x | environment_white = environment_white |
| 149 | ) | |
| 150 | ||
| 151 | 1x | out = render_white_balance( |
| 152 | 1x | image, |
| 153 | 1x | reference_white = reference_white, |
| 154 | 1x | target_white = target_white, |
| 155 | 1x | bake = bake, |
| 156 | 1x | filename = filename, |
| 157 | 1x | preview = preview |
| 158 | ) | |
| 159 | 1x | attr(out, "environment_white") = reference_white |
| 160 | 1x | out |
| 161 | } | |
| 162 | ||
| 163 | #' Estimate correlated color temperature from xy chromaticity | |
| 164 | #' @param xy xy chromaticity coordinates. | |
| 165 | #' @return Approximate correlated color temperature in Kelvin. | |
| 166 | #' @keywords internal | |
| 167 | #' @noRd | |
| 168 | xy_to_cct_mccamy = function(xy) { | |
| 169 | 4x | n = (xy[1] - 0.3320) / (0.1858 - xy[2]) |
| 170 | 4x | 449 * n^3 + 3525 * n^2 + 6823.3 * n + 5520.33 |
| 171 | } |
| 1 | #' Convert XYZ to xy chromaticity coordinates | |
| 2 | #' @param xyz XYZ vector. | |
| 3 | #' @return Numeric xy vector. | |
| 4 | #' @keywords internal | |
| 5 | xyz_to_xy = function(xyz) { | |
| 6 | 12x | stopifnot(is.numeric(xyz), length(xyz) == 3L, all(is.finite(xyz))) |
| 7 | 12x | denom = sum(xyz) |
| 8 | 12x | if (!is.finite(denom) || denom <= 0) { |
| 9 | ! | stop("XYZ values must have a positive finite sum.") |
| 10 | } | |
| 11 | 12x | unname(c(xyz[1] / denom, xyz[2] / denom)) |
| 12 | } | |
| 13 | ||
| 14 | #' Convert xy chromaticity coordinates to XYZ | |
| 15 | #' @param xy xy chromaticity vector. | |
| 16 | #' @return XYZ vector normalized to Y=1. | |
| 17 | #' @keywords internal | |
| 18 | xy_to_xyz = function(xy) { | |
| 19 | 2x | stopifnot(is.numeric(xy), length(xy) == 2L, all(is.finite(xy))) |
| 20 | 2x | if (xy[2] <= 0) { |
| 21 | ! | stop("xy y-coordinate must be positive.") |
| 22 | } | |
| 23 | 2x | unname(c(xy[1] / xy[2], 1, (1 - xy[1] - xy[2]) / xy[2])) |
| 24 | } | |
| 25 | ||
| 26 | #' Check whether libopenexr supports metadata | |
| 27 | #' @return `TRUE` if `libopenexr::write_exr()` accepts metadata. | |
| 28 | #' @keywords internal | |
| 29 | libopenexr_supports_metadata = function() { | |
| 30 | 3x | "metadata" %in% names(formals(libopenexr::write_exr)) |
| 31 | } | |
| 32 | ||
| 33 | #' Normalize EXR chromaticities metadata | |
| 34 | #' @param chromaticities EXR chromaticities metadata. | |
| 35 | #' @return Named chromaticities list. | |
| 36 | #' @keywords internal | |
| 37 | normalize_exr_chromaticities = function(chromaticities) { | |
| 38 | 5x | if (is.null(chromaticities)) { |
| 39 | ! | return(NULL) |
| 40 | } | |
| 41 | ||
| 42 | 5x | if (is.list(chromaticities)) { |
| 43 | 5x | required = c("red", "green", "blue", "white") |
| 44 | 5x | if (!all(required %in% names(chromaticities))) { |
| 45 | ! | stop( |
| 46 | ! | "EXR chromaticities metadata must include red, green, blue, and white." |
| 47 | ) | |
| 48 | } | |
| 49 | 5x | out = chromaticities[required] |
| 50 | } else if ( | |
| 51 | ! | is.matrix(chromaticities) && all(dim(chromaticities) == c(4L, 2L)) |
| 52 | ) { | |
| 53 | ! | out = list( |
| 54 | ! | red = chromaticities[1L, ], |
| 55 | ! | green = chromaticities[2L, ], |
| 56 | ! | blue = chromaticities[3L, ], |
| 57 | ! | white = chromaticities[4L, ] |
| 58 | ) | |
| 59 | ! | } else if (is.numeric(chromaticities) && length(chromaticities) == 8L) { |
| 60 | ! | values = matrix(chromaticities, nrow = 4L, byrow = TRUE) |
| 61 | ! | out = list( |
| 62 | ! | red = values[1L, ], |
| 63 | ! | green = values[2L, ], |
| 64 | ! | blue = values[3L, ], |
| 65 | ! | white = values[4L, ] |
| 66 | ) | |
| 67 | } else { | |
| 68 | ! | stop("Unsupported EXR chromaticities metadata shape.") |
| 69 | } | |
| 70 | ||
| 71 | 5x | lapply(out, function(x) { |
| 72 | 20x | stopifnot(is.numeric(x), length(x) == 2L, all(is.finite(x))) |
| 73 | 20x | unname(c(as.numeric(x[1]), as.numeric(x[2]))) |
| 74 | }) | |
| 75 | } | |
| 76 | ||
| 77 | #' Convert a colorspace descriptor to EXR chromaticities metadata | |
| 78 | #' @param colorspace Colorspace descriptor. | |
| 79 | #' @return Named EXR chromaticities list. | |
| 80 | #' @keywords internal | |
| 81 | colorspace_to_exr_chromaticities = function(colorspace) { | |
| 82 | 3x | if (!is.list(colorspace) || is.null(colorspace$primaries)) { |
| 83 | ! | return(NULL) |
| 84 | } | |
| 85 | 3x | primaries = colorspace$primaries |
| 86 | 3x | if (!all(c("r", "g", "b") %in% names(primaries))) { |
| 87 | ! | return(NULL) |
| 88 | } | |
| 89 | 3x | normalize_exr_chromaticities(list( |
| 90 | 3x | red = primaries$r, |
| 91 | 3x | green = primaries$g, |
| 92 | 3x | blue = primaries$b, |
| 93 | 3x | white = xyz_to_xy(colorspace$white_xyz) |
| 94 | )) | |
| 95 | } | |
| 96 | ||
| 97 | #' Build a colorspace descriptor from EXR metadata | |
| 98 | #' @param metadata EXR metadata list. | |
| 99 | #' @return Colorspace descriptor, or `NULL` when chromaticities are absent. | |
| 100 | #' @keywords internal | |
| 101 | colorspace_from_exr_metadata = function(metadata) { | |
| 102 | 4x | if (!is.list(metadata) || is.null(metadata$chromaticities)) { |
| 103 | 2x | return(NULL) |
| 104 | } | |
| 105 | 2x | chromaticities = tryCatch( |
| 106 | 2x | normalize_exr_chromaticities(metadata$chromaticities), |
| 107 | 2x | error = function(e) { |
| 108 | ! | warning( |
| 109 | ! | "Ignoring invalid EXR chromaticities metadata: ", |
| 110 | ! | conditionMessage(e), |
| 111 | ! | call. = FALSE |
| 112 | ) | |
| 113 | ! | NULL |
| 114 | } | |
| 115 | ) | |
| 116 | 2x | if (is.null(chromaticities)) { |
| 117 | ! | return(NULL) |
| 118 | } | |
| 119 | 2x | make_colorspace( |
| 120 | 2x | name = "OpenEXR", |
| 121 | 2x | primaries = list( |
| 122 | 2x | r = chromaticities$red, |
| 123 | 2x | g = chromaticities$green, |
| 124 | 2x | b = chromaticities$blue |
| 125 | ), | |
| 126 | 2x | white_xy = chromaticities$white, |
| 127 | 2x | white_name = "EXR" |
| 128 | ) | |
| 129 | } | |
| 130 | ||
| 131 | #' Get the adopted neutral white point from EXR metadata | |
| 132 | #' @param metadata EXR metadata list. | |
| 133 | #' @return XYZ white point, or `NULL` when absent. | |
| 134 | #' @keywords internal | |
| 135 | white_current_from_exr_metadata = function(metadata) { | |
| 136 | 4x | if (!is.list(metadata) || is.null(metadata$adoptedNeutral)) { |
| 137 | 2x | return(NULL) |
| 138 | } | |
| 139 | 2x | tryCatch( |
| 140 | 2x | xy_to_xyz(metadata$adoptedNeutral), |
| 141 | 2x | error = function(e) { |
| 142 | ! | warning( |
| 143 | ! | "Ignoring invalid EXR adoptedNeutral metadata: ", |
| 144 | ! | conditionMessage(e), |
| 145 | ! | call. = FALSE |
| 146 | ) | |
| 147 | ! | NULL |
| 148 | } | |
| 149 | ) | |
| 150 | } | |
| 151 | ||
| 152 | #' Preserve EXR metadata not promoted to rayimg attributes | |
| 153 | #' @param metadata EXR metadata list. | |
| 154 | #' @return EXR metadata list, or `NULL` when no metadata remains. | |
| 155 | #' @keywords internal | |
| 156 | preserved_exr_metadata = function(metadata) { | |
| 157 | 2x | if (!is.list(metadata) || length(metadata) == 0L) { |
| 158 | ! | return(NULL) |
| 159 | } | |
| 160 | ||
| 161 | 2x | promoted = c("chromaticities", "adoptedNeutral") |
| 162 | 2x | out = metadata |
| 163 | 2x | out[promoted] = NULL |
| 164 | 2x | if (length(out) == 0L) { |
| 165 | 1x | return(NULL) |
| 166 | } | |
| 167 | 1x | out |
| 168 | } | |
| 169 | ||
| 170 | #' Build EXR metadata from a rayimg | |
| 171 | #' @param image A `rayimg`. | |
| 172 | #' @param metadata Default `NULL`. User-supplied EXR metadata. | |
| 173 | #' @return EXR metadata list. | |
| 174 | #' @keywords internal | |
| 175 | exr_metadata_from_rayimg = function(image, metadata = NULL) { | |
| 176 | 3x | out = attr(image, "exr", exact = TRUE) |
| 177 | 3x | if (!is.list(out)) { |
| 178 | 2x | out = list() |
| 179 | } | |
| 180 | 3x | if (!is.null(metadata)) { |
| 181 | 1x | if (!is.list(metadata)) { |
| 182 | ! | stop("EXR metadata must be a list.", call. = FALSE) |
| 183 | } | |
| 184 | 1x | out = utils::modifyList(out, metadata) |
| 185 | } | |
| 186 | ||
| 187 | 3x | chromaticities = colorspace_to_exr_chromaticities( |
| 188 | 3x | attr(image, "colorspace", exact = TRUE) |
| 189 | ) | |
| 190 | 3x | if (!is.null(chromaticities)) { |
| 191 | 3x | out$chromaticities = chromaticities |
| 192 | } | |
| 193 | ||
| 194 | 3x | white_current = attr(image, "white_current", exact = TRUE) |
| 195 | 3x | if (!is.null(white_current)) { |
| 196 | 3x | out$adoptedNeutral = xyz_to_xy(white_current) |
| 197 | } | |
| 198 | ||
| 199 | 3x | if (length(out) == 0L) { |
| 200 | ! | return(NULL) |
| 201 | } | |
| 202 | 3x | out |
| 203 | } |
| 1 | #' @title Handle Image Output | |
| 2 | #' | |
| 3 | #' @description Handles image output logic: returning, saving to a file, or previewing. | |
| 4 | #' | |
| 5 | #' @param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 6 | #' @param filename Default `NULL`. String specifying the file path to save the image. | |
| 7 | #' If `NULL`, the image is returned or displayed. | |
| 8 | #' @param preview Default `FALSE`. If `TRUE`, the image is displayed. | |
| 9 | #' | |
| 10 | #' @return If `filename = NULL` and `preview = FALSE`, returns the image array invisibly. | |
| 11 | #' Otherwise, saves to file or displays the image. | |
| 12 | #' | |
| 13 | #' @keywords internal | |
| 14 | handle_image_output = function(image, filename = NULL, preview = FALSE) { | |
| 15 | 301x | if (is.null(filename) || is.na(filename)) { |
| 16 | 300x | if (!preview) { |
| 17 | 300x | return(image) # Return the image data |
| 18 | } | |
| 19 | ! | plot_image(render_clamp(image)) # Display image |
| 20 | ! | return(invisible(image)) |
| 21 | } else { | |
| 22 | 1x | ray_write_image(image, filename) # Save the image to file |
| 23 | 1x | if (preview) { |
| 24 | ! | plot_image(render_clamp(image)) # Display saved image |
| 25 | } | |
| 26 | 1x | return(invisible(image)) |
| 27 | } | |
| 28 | } |
| 1 | #'@title add_padding | |
| 2 | #' | |
| 3 | #'@description Adds padding to the matrix | |
| 4 | #' | |
| 5 | #'@param input A two-dimensional matrix or a 3D array (including `rayimg`). | |
| 6 | #'@return Matrix with edges padded | |
| 7 | #'@keywords internal | |
| 8 | add_padding = function(input) { | |
| 9 | ! | is_rayimg = inherits(input, "rayimg") |
| 10 | ! | input_array = if (is_rayimg) { |
| 11 | ! | unclass(input) |
| 12 | } else { | |
| 13 | ! | input |
| 14 | } | |
| 15 | ||
| 16 | ! | if (length(dim(input_array)) == 2) { |
| 17 | ! | temp = matrix(0, nrow = nrow(input_array) + 2, ncol = ncol(input_array) + 2) |
| 18 | ! | temp[2:(nrow(temp) - 1), 2:(ncol(temp) - 1)] = input_array |
| 19 | ! | temp[2:(nrow(temp) - 1), 1] = input_array[, 1] |
| 20 | ! | temp[1, 2:(ncol(temp) - 1)] = input_array[1, ] |
| 21 | ! | temp[2:(nrow(temp) - 1), ncol(temp)] = input_array[, ncol(input_array)] |
| 22 | ! | temp[nrow(temp), 2:(ncol(temp) - 1)] = input_array[nrow(input_array), ] |
| 23 | ! | temp[1, 1] = temp[1, 2] |
| 24 | ! | temp[1, ncol(temp)] = temp[1, ncol(temp) - 1] |
| 25 | ! | temp[nrow(temp), 1] = temp[nrow(temp) - 1, 2] |
| 26 | ! | temp[nrow(temp), ncol(temp)] = temp[nrow(temp) - 1, ncol(temp)] |
| 27 | } else { | |
| 28 | ! | d = dim(input_array) |
| 29 | ! | temp = array(0, dim = c(d[1] + 2, d[2] + 2, d[3])) |
| 30 | ! | temp[2:(d[1] + 1), 2:(d[2] + 1), ] = input_array |
| 31 | ! | temp[2:(d[1] + 1), 1, ] = input_array[, 1, ] |
| 32 | ! | temp[1, 2:(d[2] + 1), ] = input_array[1, , ] |
| 33 | ! | temp[2:(d[1] + 1), d[2] + 2, ] = input_array[, d[2], ] |
| 34 | ! | temp[d[1] + 2, 2:(d[2] + 1), ] = input_array[d[1], , ] |
| 35 | ! | temp[1, 1, ] = temp[1, 2, ] |
| 36 | ! | temp[1, d[2] + 2, ] = temp[1, d[2] + 1, ] |
| 37 | ! | temp[d[1] + 2, 1, ] = temp[d[1] + 1, 2, ] |
| 38 | ! | temp[d[1] + 2, d[2] + 2, ] = temp[d[1] + 1, d[2] + 2, ] |
| 39 | } | |
| 40 | ||
| 41 | ! | if (is_rayimg) { |
| 42 | ! | temp = rayimg( |
| 43 | ! | temp, |
| 44 | ! | filetype = attr(input, "filetype"), |
| 45 | ! | source_linear = attr(input, "source_linear"), |
| 46 | ! | colorspace = attr(input, "colorspace"), |
| 47 | ! | white_current = attr(input, "white_current"), |
| 48 | ! | exposure = attr(input, "exposure", exact = TRUE), |
| 49 | ! | iso = attr(input, "iso", exact = TRUE) |
| 50 | ) | |
| 51 | } | |
| 52 | ! | temp |
| 53 | } | |
| 54 | ||
| 55 | #'@title add_multi_padding | |
| 56 | #' | |
| 57 | #'@description Adds multiple levels padding to the matrix | |
| 58 | #' | |
| 59 | #'@param input A two-dimensional matrix or a 3D array (including `rayimg`). | |
| 60 | #'@param pad Number of padding entries | |
| 61 | #'@return Matrix with edges padded | |
| 62 | #'@keywords internal | |
| 63 | add_multi_padding = function(input, pad = 1) { | |
| 64 | ! | if (length(dim(input)) == 2) { |
| 65 | ! | temp = matrix(0, nrow = nrow(input) + 2 * pad, ncol = ncol(input) + 2 * pad) |
| 66 | ! | temp[(1 + pad):(pad + nrow(input)), (1 + pad):(pad + ncol(input))] = input |
| 67 | ! | temp[(1 + pad):(pad + nrow(input)), 1:pad] = input[, 1] |
| 68 | ! | for (i in 1:pad) { |
| 69 | ! | temp[i, (1 + pad):(pad + ncol(input))] = input[1, ] |
| 70 | } | |
| 71 | ! | for (i in (pad + ncol(input) + 1):ncol(temp)) { |
| 72 | ! | temp[(1 + pad):(pad + nrow(input)), i] = input[, ncol(input)] |
| 73 | } | |
| 74 | ! | for (i in (pad + nrow(input) + 1):nrow(temp)) { |
| 75 | ! | temp[i, (1 + pad):(pad + ncol(input))] = input[nrow(input), ] |
| 76 | } | |
| 77 | ! | temp[1:pad, 1:pad] = input[1, 1] |
| 78 | ! | temp[1:pad, (pad + ncol(input) + 1):ncol(temp)] = input[1, ncol(input)] |
| 79 | ! | temp[(pad + nrow(input) + 1):nrow(temp), 1:pad] = input[nrow(input), 1] |
| 80 | ! | temp[ |
| 81 | ! | (pad + nrow(input) + 1):nrow(temp), |
| 82 | ! | (pad + ncol(input) + 1):ncol(temp) |
| 83 | ! | ] = input[nrow(input), ncol(input)] |
| 84 | ! | return(temp) |
| 85 | } else { | |
| 86 | ! | temp_height = list() |
| 87 | ! | for (i in seq_len(dim(input)[3])) { |
| 88 | ! | temp_height[[i]] = add_multi_padding(input[,, i], pad) |
| 89 | } | |
| 90 | ! | temp_array = array(0, dim = c(dim(temp_height[[i]]), dim(input)[3])) |
| 91 | ! | for (i in seq_len(dim(input)[3])) { |
| 92 | ! | temp_array[,, i] = temp_height[[i]] |
| 93 | } | |
| 94 | ! | return(temp_array) |
| 95 | } | |
| 96 | } | |
| 97 | ||
| 98 | #'@title trim_padding | |
| 99 | #' | |
| 100 | #'@description Trims padding | |
| 101 | #' | |
| 102 | #'@param input A two-dimensional matrix. | |
| 103 | #'@param pad Number of padding entries | |
| 104 | #'@return Matrix with edges trimmed | |
| 105 | #'@keywords internal | |
| 106 | trim_padding = function(input, pad = 1) { | |
| 107 | ! | if (length(dim(input)) == 2) { |
| 108 | ! | return(input[(1 + pad):(nrow(input) - pad), (1 + pad):(ncol(input) - pad)]) |
| 109 | } else { | |
| 110 | ! | return(input[ |
| 111 | ! | (1 + pad):(nrow(input) - pad), |
| 112 | ! | (1 + pad):(ncol(input) - pad), |
| 113 | , | |
| 114 | ! | drop = FALSE |
| 115 | ]) | |
| 116 | } | |
| 117 | } | |
| 118 | ||
| 119 | #'@title pad to fit | |
| 120 | #' | |
| 121 | #'@description Pads to a rect | |
| 122 | #' | |
| 123 | #'@return Hillshade with edges trimmed | |
| 124 | #'@keywords internal | |
| 125 | pad_to_fit = function(dim, kernel) { | |
| 126 | ! | whichdim = which.min(dim) |
| 127 | ! | if (dim[1] != dim[2]) { |
| 128 | ! | if (whichdim == 1) { |
| 129 | ! | extra_rows = dim[2] - dim[1] |
| 130 | ! | if (extra_rows %% 2 == 0) { |
| 131 | ! | pad = matrix(0, nrow = extra_rows / 2, ncol = ncol(kernel)) |
| 132 | ! | kernel = rbind(pad, kernel, pad) |
| 133 | } else { | |
| 134 | ! | pad1 = matrix(0, nrow = floor(extra_rows / 2) + 1, ncol = ncol(kernel)) |
| 135 | ! | pad2 = matrix(0, nrow = floor(extra_rows / 2), ncol = ncol(kernel)) |
| 136 | ! | kernel = rbind(pad1, kernel, pad2) |
| 137 | } | |
| 138 | } else { | |
| 139 | ! | extra_cols = dim[1] - dim[2] |
| 140 | ! | if (extra_cols %% 2 == 0) { |
| 141 | ! | pad = matrix(0, nrow = nrow(kernel), ncol = extra_cols / 2) |
| 142 | ! | kernel = cbind(pad, kernel, pad) |
| 143 | } else { | |
| 144 | ! | pad1 = matrix(0, nrow = nrow(kernel), ncol = floor(extra_cols / 2) + 1) |
| 145 | ! | pad2 = matrix(0, nrow = nrow(kernel), ncol = floor(extra_cols / 2)) |
| 146 | ! | kernel = cbind(pad1, kernel, pad2) |
| 147 | } | |
| 148 | } | |
| 149 | } | |
| 150 | ! | return(kernel) |
| 151 | } | |
| 152 | ||
| 153 | #'@title expand to fit | |
| 154 | #' | |
| 155 | #'@description Pads to a rect | |
| 156 | #' | |
| 157 | #'@return Hillshade with edges trimmed | |
| 158 | #'@keywords internal | |
| 159 | expand_to_fit = function(dim, kernel) { | |
| 160 | ! | kdim = dim(kernel) |
| 161 | ! | if (!all(kdim <= dim)) { |
| 162 | ! | stop("kernel dimensions must be less than or equal to image") |
| 163 | } | |
| 164 | ! | if (kdim[1] != dim[1]) { |
| 165 | ! | extra_rows = dim[1] - kdim[1] |
| 166 | ! | if (extra_rows %% 2 == 0) { |
| 167 | ! | pad = matrix(0, nrow = extra_rows / 2, ncol = ncol(kernel)) |
| 168 | ! | kernel = rbind(pad, kernel, pad) |
| 169 | } else { | |
| 170 | ! | pad1 = matrix(0, nrow = floor(extra_rows / 2) + 1, ncol = ncol(kernel)) |
| 171 | ! | pad2 = matrix(0, nrow = floor(extra_rows / 2), ncol = ncol(kernel)) |
| 172 | ! | kernel = rbind(pad1, kernel, pad2) |
| 173 | } | |
| 174 | } | |
| 175 | ! | if (kdim[2] != dim[2]) { |
| 176 | ! | extra_cols = dim[2] - kdim[2] |
| 177 | ! | if (extra_cols %% 2 == 0) { |
| 178 | ! | pad = matrix(0, nrow = nrow(kernel), ncol = extra_cols / 2) |
| 179 | ! | kernel = cbind(pad, kernel, pad) |
| 180 | } else { | |
| 181 | ! | pad1 = matrix(0, nrow = nrow(kernel), ncol = floor(extra_cols / 2) + 1) |
| 182 | ! | pad2 = matrix(0, nrow = nrow(kernel), ncol = floor(extra_cols / 2)) |
| 183 | ! | kernel = cbind(pad1, kernel, pad2) |
| 184 | } | |
| 185 | } | |
| 186 | ! | return(kernel) |
| 187 | } |
| 1 | #'@title Reorient Image | |
| 2 | #' | |
| 3 | #'@description Reorients an image or matrix. Transformations are applied in this order: x, y, and transpose. | |
| 4 | #' | |
| 5 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 6 | #'@param flipx Default `FALSE`. Flip horizontally | |
| 7 | #'@param flipy Default `FALSE`. Flip vertically. | |
| 8 | #'@param transpose Default `FALSE`. Transpose image. | |
| 9 | #'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead. | |
| 10 | #'@param preview Default `FALSE`. Whether to plot the convolved image, or just to return the values. | |
| 11 | #'@return 3-layer RGB reoriented array or matrix. | |
| 12 | #'@export | |
| 13 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 14 | #'#Original orientation | |
| 15 | #'plot_image(dragon) | |
| 16 | #'#Flip the dragon image horizontally | |
| 17 | #'dragon |> | |
| 18 | #' render_reorient(flipx = TRUE) |> | |
| 19 | #' plot_image() | |
| 20 | #'#Flip the dragon image vertically | |
| 21 | #'dragon |> | |
| 22 | #' render_reorient(flipy = TRUE) |> | |
| 23 | #' plot_image() | |
| 24 | #'#Transpose the dragon image | |
| 25 | #'dragon |> | |
| 26 | #' render_reorient(transpose = TRUE) |> | |
| 27 | #' plot_image() | |
| 28 | render_reorient = function( | |
| 29 | image, | |
| 30 | flipx = FALSE, | |
| 31 | flipy = FALSE, | |
| 32 | transpose = FALSE, | |
| 33 | filename = NULL, | |
| 34 | preview = FALSE | |
| 35 | ) { | |
| 36 | #Check if file or image before below: | |
| 37 | ! | temp_image = ray_read_image(image, convert_to_array = FALSE) |
| 38 | ! | imagetype = attr(temp_image, "filetype") |
| 39 | ! | img_source_linear = attr(temp_image, "source_linear") |
| 40 | ! | colorspace = attr(temp_image, "colorspace") |
| 41 | ! | white_current = attr(temp_image, "white_current") |
| 42 | ||
| 43 | ! | if (flipx) { |
| 44 | ! | temp_image = fliplr(temp_image) |
| 45 | } | |
| 46 | ! | if (flipy) { |
| 47 | ! | temp_image = flipud(temp_image) |
| 48 | } | |
| 49 | ! | if (transpose) { |
| 50 | ! | if (imagetype == "matrix") { |
| 51 | ! | temp_image = t(temp_image) |
| 52 | } else { | |
| 53 | ! | temp_image = aperm(temp_image, c(2, 1, 3)) |
| 54 | } | |
| 55 | } | |
| 56 | ! | temp_image = ray_read_image( |
| 57 | ! | temp_image, |
| 58 | ! | filetype = imagetype, |
| 59 | ! | source_linear = img_source_linear, |
| 60 | ! | assume_colorspace = colorspace, |
| 61 | ! | assume_white = white_current |
| 62 | ) | |
| 63 | ||
| 64 | ! | handle_image_output(temp_image, filename = filename, preview = preview) |
| 65 | } |
| 1 | #' @title Render a Title on an Image | |
| 2 | #' | |
| 3 | #' @description Adds a title with optional styling and a title bar to an image. | |
| 4 | #' The image can be previewed or saved to a file. Supports both the `grid`-based | |
| 5 | #' method and (deprecated) `magick` package for rendering the title. | |
| 6 | #' | |
| 7 | #' @param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 8 | #' @param title_text Default `""`. Text string to be added as the title to the image. | |
| 9 | #' @param title_offset Default `c(15,15)`. Numeric vector specifying the horizontal | |
| 10 | #' and vertical offset of the title text, relative to its anchor position. | |
| 11 | #' @param title_lineheight Default `1`. Multiplier for the lineheight. | |
| 12 | #' @param title_color Default `"black"`. String specifying the color of the title text. | |
| 13 | #' @param title_size Default `30`. Numeric value specifying the font size of the title text. | |
| 14 | #' @param title_font Default `"Arial"`. String specifying the font family for the title text. | |
| 15 | #' Common options include `"sans"`, `"mono"`, `"serif"`, `"Times"`, `"Helvetica"`, etc. | |
| 16 | #' @param title_style Default `"plain"`. String specifying the font style, such as | |
| 17 | #' `"plain"`, `"italic"`, or `"bold"`. | |
| 18 | #' @param title_bar_color Default `NULL`. Color of the optional title bar. If `NULL`, no bar is added. | |
| 19 | #' @param title_bar_alpha Default `0.5`. Transparency level of the title bar. A value | |
| 20 | #' between `0` (fully transparent) and `1` (fully opaque). | |
| 21 | #' @param title_bar_width Default `NULL`. Numeric value for the height of the title bar in pixels. | |
| 22 | #' If `NULL`, it is automatically calculated based on the text size and line breaks. | |
| 23 | #' @param title_position Default `"northwest"`. String specifying the position of the title text. | |
| 24 | #' Only used when `use_magick = TRUE`. Common options include `"northwest"`, `"center"`, `"south"`, etc. | |
| 25 | #' @param title_just Default `"left"`. Horizontal alignment of the title text: `"left"`, | |
| 26 | #' `"center"`, or `"right"`. | |
| 27 | #' @param use_magick Default `FALSE`. Boolean indicating whether to use the `magick` package for | |
| 28 | #' rendering titles. This option will be deprecated in future versions. | |
| 29 | #' @param filename Default `NULL`. String specifying the file path to save the resulting image. | |
| 30 | #' If `NULL` and `preview = FALSE`, the function returns the processed RGB array. | |
| 31 | #' @param preview Default `FALSE`. Boolean indicating whether to display the image after processing. | |
| 32 | #' If `TRUE`, the image is displayed but not saved or returned. | |
| 33 | #' | |
| 34 | #' @return A 3-layer RGB array of the processed image if `filename = NULL` and `preview = FALSE`. | |
| 35 | #' Otherwise, writes the image to the specified file or displays it if `preview = TRUE`. | |
| 36 | #' | |
| 37 | #' @note The `use_magick` parameter and all functionality tied to the `magick` package are | |
| 38 | #' planned for deprecation. It is recommended to use the `grid`-based method for | |
| 39 | #' future compatibility. | |
| 40 | #' | |
| 41 | #' @import grDevices grid | |
| 42 | #' @export | |
| 43 | #' | |
| 44 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 45 | #'#Plot the dragon | |
| 46 | #'render_title(dragon, preview = TRUE, title_text = "Dragon", title_size=20) | |
| 47 | #'#That's hard to see--let's add a title bar: | |
| 48 | #'render_title(dragon, preview = TRUE, title_text = "Dragon", title_size=20, | |
| 49 | #' title_bar_color="white") | |
| 50 | #'#Change the width of the bar: | |
| 51 | #'render_title(dragon, preview = TRUE, title_text = "Dragon", title_size=20, | |
| 52 | #' title_bar_color="white", title_offset = c(8,8)) | |
| 53 | #'#The width of the bar will also automatically adjust for newlines: | |
| 54 | #'render_title(dragon, preview = TRUE, title_text = "Dragon\n(Blue)", title_size=20, | |
| 55 | #' title_bar_color="white") | |
| 56 | #'#Change the color and title color: | |
| 57 | #'render_title(dragon, preview = TRUE, title_text = "Dragon", title_size=20, | |
| 58 | #' title_bar_color="red", title_color = "white") | |
| 59 | #'#Change the transparency: | |
| 60 | #'render_title(dragon, preview = TRUE, title_text = "Dragon", | |
| 61 | #' title_size=20, title_bar_alpha = 0.8, | |
| 62 | #' title_bar_color="red", title_color = "white") | |
| 63 | #' #Read directly from a file | |
| 64 | #' temp_image = tempfile(fileext = ".png") | |
| 65 | #' ray_write_image(dragon, temp_image) | |
| 66 | #' render_title(temp_image, preview = TRUE, title_text = "Dragon", | |
| 67 | #' title_size=20, title_bar_alpha = 0.8, | |
| 68 | #' title_bar_color="red", title_color = "white") | |
| 69 | render_title = function( | |
| 70 | image, | |
| 71 | title_text = "", | |
| 72 | title_size = 30, | |
| 73 | title_offset = rep(title_size / 2, 2), | |
| 74 | title_lineheight = 1, | |
| 75 | title_color = "black", | |
| 76 | title_font = "Arial", | |
| 77 | title_style = "plain", | |
| 78 | title_bar_color = NA, | |
| 79 | title_bar_alpha = 0.5, | |
| 80 | title_bar_width = NULL, | |
| 81 | title_position = NA, | |
| 82 | title_just = "left", | |
| 83 | use_magick = FALSE, | |
| 84 | filename = NULL, | |
| 85 | preview = FALSE | |
| 86 | ) { | |
| 87 | #Always output RGBA array, need to ensure alpha is preserved | |
| 88 | 25x | image = ray_read_image( |
| 89 | 25x | image, |
| 90 | 25x | convert_to_array = TRUE, |
| 91 | 25x | reset_camera_settings = TRUE |
| 92 | ) | |
| 93 | ||
| 94 | 25x | temp = tempfile(fileext = ".png") |
| 95 | 25x | ray_write_image( |
| 96 | 25x | image = ray_read_image(array(0, dim = dim(image))), |
| 97 | 25x | filename = temp |
| 98 | ) | |
| 99 | ||
| 100 | 25x | if (use_magick) { |
| 101 | ! | if (title_style == "plain") { |
| 102 | ! | title_style = "normal" |
| 103 | } | |
| 104 | ! | if (is.na(title_bar_color)) { |
| 105 | ! | title_bar_color = NULL |
| 106 | } | |
| 107 | ! | if (is.na(title_position)) { |
| 108 | ! | title_position = "northwest" |
| 109 | } | |
| 110 | ! | dimensions = dim(image) |
| 111 | ! | if (!("magick" %in% rownames(utils::installed.packages()))) { |
| 112 | ! | stop("`magick` package required for adding title") |
| 113 | } | |
| 114 | ||
| 115 | ! | if (!is.null(title_bar_color)) { |
| 116 | ! | title_bar_color = col2rgb(title_bar_color) / 255 |
| 117 | ! | title_bar = array(0, c(dimensions[1], dimensions[2], 4)) |
| 118 | ! | if (is.null(title_bar_width)) { |
| 119 | #Detect newlines and adjust title bar width | |
| 120 | ! | char_vector = unlist(strsplit(title_text, "")) |
| 121 | ! | newline_indices = which(char_vector == "\n") |
| 122 | ! | newline_indices = newline_indices[ |
| 123 | ! | newline_indices != length(char_vector) |
| 124 | ] | |
| 125 | ! | newlines = length(newline_indices) |
| 126 | ! | title_bar_width = 2 * title_offset[2] + title_size * (1 + newlines) |
| 127 | } | |
| 128 | ! | if (title_bar_width > dimensions[1]) { |
| 129 | ! | message(paste0( |
| 130 | ! | c( |
| 131 | ! | "Input title_bar_width (", |
| 132 | ! | title_bar_width, |
| 133 | ! | ") greater than image height (", |
| 134 | ! | dimensions[1], |
| 135 | ! | "), reducing size." |
| 136 | ), | |
| 137 | ! | collapse = "" |
| 138 | )) | |
| 139 | ! | title_bar_width = dimensions[1] |
| 140 | } | |
| 141 | ! | if (title_position %in% c("northwest", "north", "northeast")) { |
| 142 | ! | title_bar[1:title_bar_width, , 1] = title_bar_color[1] |
| 143 | ! | title_bar[1:title_bar_width, , 2] = title_bar_color[2] |
| 144 | ! | title_bar[1:title_bar_width, , 3] = title_bar_color[3] |
| 145 | ! | title_bar[1:title_bar_width, , 4] = title_bar_alpha |
| 146 | ! | } else if (title_position %in% c("southwest", "south", "southeast")) { |
| 147 | ! | title_bar[ |
| 148 | ! | (nrow(title_bar) - title_bar_width):nrow(title_bar), |
| 149 | , | |
| 150 | ! | 1 |
| 151 | ! | ] = title_bar_color[1] |
| 152 | ! | title_bar[ |
| 153 | ! | (nrow(title_bar) - title_bar_width):nrow(title_bar), |
| 154 | , | |
| 155 | ! | 2 |
| 156 | ! | ] = title_bar_color[2] |
| 157 | ! | title_bar[ |
| 158 | ! | (nrow(title_bar) - title_bar_width):nrow(title_bar), |
| 159 | , | |
| 160 | ! | 3 |
| 161 | ! | ] = title_bar_color[3] |
| 162 | ! | title_bar[ |
| 163 | ! | (nrow(title_bar) - title_bar_width):nrow(title_bar), |
| 164 | , | |
| 165 | ! | 4 |
| 166 | ! | ] = title_bar_alpha |
| 167 | } else { | |
| 168 | ! | title_bar[ |
| 169 | ! | (nrow(title_bar) / 2 - title_bar_width / 2):(nrow(title_bar) / |
| 170 | ! | 2 + |
| 171 | ! | title_bar_width / 2), |
| 172 | , | |
| 173 | ! | 1 |
| 174 | ! | ] = title_bar_color[1] |
| 175 | ! | title_bar[ |
| 176 | ! | (nrow(title_bar) / 2 - title_bar_width / 2):(nrow(title_bar) / |
| 177 | ! | 2 + |
| 178 | ! | title_bar_width / 2), |
| 179 | , | |
| 180 | ! | 2 |
| 181 | ! | ] = title_bar_color[2] |
| 182 | ! | title_bar[ |
| 183 | ! | (nrow(title_bar) / 2 - title_bar_width / 2):(nrow(title_bar) / |
| 184 | ! | 2 + |
| 185 | ! | title_bar_width / 2), |
| 186 | , | |
| 187 | ! | 3 |
| 188 | ! | ] = title_bar_color[3] |
| 189 | ! | title_bar[ |
| 190 | ! | (nrow(title_bar) / 2 - title_bar_width / 2):(nrow(title_bar) / |
| 191 | ! | 2 + |
| 192 | ! | title_bar_width / 2), |
| 193 | , | |
| 194 | ! | 4 |
| 195 | ! | ] = title_bar_alpha |
| 196 | } | |
| 197 | ! | title_bar_temp = paste0(tempfile(), ".png") |
| 198 | ! | png::writePNG(title_bar, title_bar_temp) |
| 199 | ! | magick::image_read(temp) |> |
| 200 | ! | magick::image_composite(magick::image_read(title_bar_temp), ) |> |
| 201 | ! | magick::image_write(path = temp, format = "png") |
| 202 | } | |
| 203 | ! | magick::image_read(temp) |> |
| 204 | ! | magick::image_annotate( |
| 205 | ! | title_text, |
| 206 | ! | location = paste0("+", title_offset[1], "+", title_offset[2]), |
| 207 | ! | size = title_size, |
| 208 | ! | color = title_color, |
| 209 | ! | style = title_style, |
| 210 | ! | font = title_font, |
| 211 | ! | gravity = title_position |
| 212 | ) |> | |
| 213 | ! | magick::image_write(path = temp, format = "png") |
| 214 | ! | new_image = render_image_overlay(image, temp) |
| 215 | } else { | |
| 216 | 25x | draw_title_card = function( |
| 217 | 25x | image, |
| 218 | 25x | title, |
| 219 | 25x | padding_x = 10, |
| 220 | 25x | padding_y = 10, |
| 221 | 25x | gp_text = grid::gpar(col = "white", fontsize = title_size), |
| 222 | 25x | bg_color = "black", |
| 223 | 25x | bg_alpha = 0.65, |
| 224 | 25x | title_just = c("left", "top") |
| 225 | ) { | |
| 226 | 25x | close_device_safely = function(dev_id) { |
| 227 | 25x | try(grid::upViewport(0), silent = TRUE) |
| 228 | 25x | devs = grDevices::dev.list() |
| 229 | 25x | if (!is.null(devs) && dev_id %in% devs) { |
| 230 | 25x | grDevices::dev.off(dev_id) |
| 231 | } | |
| 232 | } | |
| 233 | ||
| 234 | 25x | png_device = linear_png_device() |
| 235 | 25x | png_device( |
| 236 | 25x | temp, |
| 237 | 25x | width = ncol(image), |
| 238 | 25x | height = nrow(image), |
| 239 | 25x | pointsize = 12, |
| 240 | 25x | family = title_font, |
| 241 | 25x | units = "px", |
| 242 | 25x | res = 72 |
| 243 | ) | |
| 244 | 25x | dev_id = grDevices::dev.cur() |
| 245 | 25x | pushed = 0L |
| 246 | 25x | on.exit( |
| 247 | { | |
| 248 | 25x | if (pushed > 0L) { |
| 249 | ! | try(grid::popViewport(pushed), silent = TRUE) |
| 250 | } | |
| 251 | 25x | close_device_safely(dev_id) |
| 252 | }, | |
| 253 | 25x | add = TRUE |
| 254 | ) | |
| 255 | ||
| 256 | 25x | grid::grid.newpage() |
| 257 | ||
| 258 | 25x | prepared = prepare_native_raster(image) |
| 259 | 25x | nr = prepared$native_raster |
| 260 | 25x | image_dim = prepared$display_dim |
| 261 | ||
| 262 | 25x | image_width = image_dim[2] |
| 263 | 25x | image_height = image_dim[1] |
| 264 | ||
| 265 | 25x | image_vp = grid::viewport( |
| 266 | 25x | name = "image", |
| 267 | 25x | xscale = c(0, image_width), |
| 268 | 25x | yscale = c(image_height, 0), |
| 269 | 25x | gp = gp_text |
| 270 | ) | |
| 271 | 25x | grid::pushViewport(image_vp) |
| 272 | 25x | pushed = pushed + 1L |
| 273 | ||
| 274 | 25x | image_grob = grid::rasterGrob( |
| 275 | 25x | nr, |
| 276 | 25x | interpolate = FALSE, |
| 277 | 25x | width = grid::unit(1, "npc"), |
| 278 | 25x | height = grid::unit(1, "npc") |
| 279 | ) | |
| 280 | 25x | grid::grid.draw(image_grob) |
| 281 | ||
| 282 | 25x | title_hjust = title_just[1] |
| 283 | 25x | if (!title_hjust %in% c("left", "center", "right")) { |
| 284 | ! | stop( |
| 285 | ! | 'Invalid title_just value for horizontal alignment. Must be "left", "center", or "right".' |
| 286 | ) | |
| 287 | } | |
| 288 | ||
| 289 | # Available width for text depends on horizontal justification. | |
| 290 | # For left/right aligned text, `padding_x` is only applied on one side. | |
| 291 | 25x | available_width = if (identical(title_hjust, "center")) { |
| 292 | ! | image_width - padding_x * 2 |
| 293 | } else { | |
| 294 | 25x | image_width - padding_x |
| 295 | } | |
| 296 | 25x | available_width = max(0, available_width) |
| 297 | ||
| 298 | # Wrap text into lines based on available width | |
| 299 | 25x | wrap_text = function(text, available_width) { |
| 300 | # Split text into segments by newline characters | |
| 301 | 25x | segments = unlist(strsplit(text, "\n")) |
| 302 | 25x | all_lines = character(0) |
| 303 | ||
| 304 | 25x | for (segment in segments) { |
| 305 | 25x | words = strsplit(segment, "\\s+")[[1]] |
| 306 | 25x | if (length(words) == 0) { |
| 307 | ! | all_lines = c(all_lines, "") # Add an empty line for consecutive newlines |
| 308 | ! | next |
| 309 | } | |
| 310 | ||
| 311 | 25x | lines = character(0) |
| 312 | 25x | current_line = words[1] |
| 313 | ||
| 314 | 25x | for (word in words[-1]) { |
| 315 | ! | test_line = paste(current_line, word) |
| 316 | ! | test_width = grid::convertWidth( |
| 317 | ! | grid::stringWidth(test_line), |
| 318 | ! | "native", |
| 319 | ! | valueOnly = TRUE |
| 320 | ) | |
| 321 | ! | if (test_width > available_width) { |
| 322 | ! | lines = c(lines, current_line) |
| 323 | ! | current_line = word |
| 324 | } else { | |
| 325 | ! | current_line = test_line |
| 326 | } | |
| 327 | } | |
| 328 | ||
| 329 | 25x | lines = c(lines, current_line) |
| 330 | 25x | all_lines = c(all_lines, lines) |
| 331 | } | |
| 332 | ||
| 333 | 25x | return(all_lines) |
| 334 | } | |
| 335 | ||
| 336 | # Wrap the title text | |
| 337 | 25x | lines = wrap_text(title, available_width) |
| 338 | 25x | lines_with_newlines = paste0(lines, collapse = "\n") |
| 339 | ||
| 340 | 25x | text_size = systemfonts::shape_string( |
| 341 | 25x | lines_with_newlines, |
| 342 | 25x | size = title_size, |
| 343 | 25x | vjust = 0, |
| 344 | 25x | res = 72, |
| 345 | 25x | lineheight = title_lineheight, |
| 346 | 25x | family = title_font |
| 347 | 25x | )[["metrics"]] |
| 348 | # Position adjustments | |
| 349 | 25x | if (title_hjust == "left") { |
| 350 | 25x | x = padding_x |
| 351 | 25x | just = c("left", "top") |
| 352 | ! | } else if (title_hjust == "center") { |
| 353 | ! | x = image_width / 2 |
| 354 | ! | just = c("center", "top") |
| 355 | ! | } else if (title_hjust == "right") { |
| 356 | ! | x = image_width - padding_x |
| 357 | ! | just = c("right", "top") |
| 358 | } | |
| 359 | 25x | height_with_padding = text_size$height - |
| 360 | 25x | text_size$top_bearing - |
| 361 | 25x | text_size$bottom_bearing - |
| 362 | 25x | text_size$top_border + |
| 363 | 25x | padding_y * 2 |
| 364 | # Draw background rectangle | |
| 365 | 25x | grid::grid.rect( |
| 366 | 25x | x = 0, |
| 367 | 25x | y = 0, |
| 368 | 25x | width = image_width, |
| 369 | 25x | height = height_with_padding, |
| 370 | 25x | just = c("left", "bottom"), |
| 371 | 25x | default.units = "native", |
| 372 | 25x | gp = grid::gpar( |
| 373 | 25x | fill = grDevices::adjustcolor(bg_color, alpha.f = bg_alpha), |
| 374 | 25x | col = NA |
| 375 | ) | |
| 376 | ) | |
| 377 | 25x | grid::grid.text( |
| 378 | 25x | label = lines_with_newlines, |
| 379 | 25x | x = x, |
| 380 | 25x | y = padding_y, |
| 381 | 25x | default.units = "native", |
| 382 | 25x | just = just, |
| 383 | 25x | gp = grid::gpar( |
| 384 | 25x | col = title_color, |
| 385 | 25x | fontsize = title_size, |
| 386 | 25x | lineheight = title_lineheight, |
| 387 | 25x | cex = 1, |
| 388 | 25x | fontfamily = title_font |
| 389 | ) | |
| 390 | ) | |
| 391 | 25x | grid::popViewport(pushed) |
| 392 | 25x | pushed = 0L |
| 393 | } | |
| 394 | 25x | if (!is.na(title_position)) { |
| 395 | ! | warning("Title position is ignored when not using {magick}") |
| 396 | } | |
| 397 | 25x | if (is.null(title_bar_color)) { |
| 398 | ! | title_bar_color = NA |
| 399 | } | |
| 400 | 25x | if (is.null(title_bar_alpha)) { |
| 401 | ! | title_bar_alpha = NA |
| 402 | } | |
| 403 | 25x | draw_title_card( |
| 404 | 25x | image, |
| 405 | 25x | title = title_text, |
| 406 | 25x | padding_x = title_offset[1], |
| 407 | 25x | padding_y = title_offset[2], |
| 408 | 25x | gp_text = grid::gpar( |
| 409 | 25x | col = title_color, |
| 410 | 25x | fontsize = title_size, |
| 411 | 25x | fontfamily = title_font, |
| 412 | 25x | lineheight = title_lineheight, |
| 413 | 25x | fontface = title_style, |
| 414 | 25x | fill = NA |
| 415 | ), | |
| 416 | 25x | bg_color = title_bar_color, |
| 417 | 25x | bg_alpha = title_bar_alpha, |
| 418 | 25x | title_just = title_just |
| 419 | ) | |
| 420 | 25x | new_image = ray_read_image(temp) |
| 421 | } | |
| 422 | 25x | handle_image_output(new_image, filename = filename, preview = preview) |
| 423 | } |
| 1 | #'@title Add Vignette Effect | |
| 2 | #' | |
| 3 | #'@description Takes an RGB array/filename and adds a camera vignette effect. | |
| 4 | #' | |
| 5 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 6 | #'@param filename Default `NULL`. Filename which to save the image. If `NULL` and `preview = FALSE`, | |
| 7 | #'returns an RGB array. | |
| 8 | #'@param vignette Default `1`. A camera vignetting effect will be added to the image. | |
| 9 | #'`1` is the darkest vignetting, while `0` is no vignetting. If vignette is a length-2 vector, the second entry will | |
| 10 | #'control the blurriness of the vignette effect (`1` is the default, e.g. `2` would double the blurriness but would take | |
| 11 | #'much longer to compute). | |
| 12 | #'@param radius Default `1.1`. Multiplier for the size of the vignette. If `1`, the vignette touches | |
| 13 | #'the edge of the image. | |
| 14 | #'@param color Default `"#000000"` (black). Color of the vignette. | |
| 15 | #'@param preview Default `FALSE`. If `TRUE`, it will display the image in addition | |
| 16 | #'to returning it. | |
| 17 | #' | |
| 18 | #'@return A `rayimg` RGBA array. | |
| 19 | #'@import grDevices | |
| 20 | #'@export | |
| 21 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 22 | #'#Plot the dragon | |
| 23 | #'plot_image(dragon) | |
| 24 | #'#Add a vignette effect: | |
| 25 | #'render_vignette(dragon, preview = TRUE, vignette = 1, radius=1.1) | |
| 26 | #'#Lighten the vignette effect: | |
| 27 | #'render_vignette(dragon, preview = TRUE, vignette = 0.5) | |
| 28 | #'#Change the radius: | |
| 29 | #'render_vignette(dragon, preview = TRUE, vignette = 1, radius=1.5) | |
| 30 | #'render_vignette(dragon, preview = TRUE, vignette = 0.1, radius=0.8) | |
| 31 | #'#Change the color: | |
| 32 | #'render_vignette(dragon, preview = TRUE, vignette = 1, color="white") | |
| 33 | #'#Increase the width of the blur by 50%: | |
| 34 | #'render_vignette(dragon, preview = TRUE, vignette = c(1,1.5)) | |
| 35 | render_vignette = function( | |
| 36 | image, | |
| 37 | vignette = 0.5, | |
| 38 | color = "#000000", | |
| 39 | radius = 1.1, | |
| 40 | filename = NULL, | |
| 41 | preview = FALSE | |
| 42 | ) { | |
| 43 | ! | image = ray_read_image(image, reset_camera_settings = TRUE) |
| 44 | ! | dimensions = dim(image) |
| 45 | ||
| 46 | ! | if (!("magick" %in% rownames(utils::installed.packages()))) { |
| 47 | ! | stop("`magick` package required for adding overlay") |
| 48 | } | |
| 49 | ! | if (length(vignette) > 1) { |
| 50 | ! | if (vignette[2] < 0) { |
| 51 | ! | stop("vignette[2] must be greater than 0") |
| 52 | } | |
| 53 | ! | radiusval = min(c(dimensions[1], dimensions[2])) / 2 * vignette[2] |
| 54 | ! | vignette = vignette[1] |
| 55 | } else { | |
| 56 | ! | radiusval = min(c(dimensions[1], dimensions[2])) / 2 |
| 57 | } | |
| 58 | ! | if (is.numeric(vignette)) { |
| 59 | ! | if (vignette[1] > 1 || vignette[1] < 0) { |
| 60 | ! | stop("vignette value (", vignette[1], ") must be between 0 and 1.") |
| 61 | } | |
| 62 | } else { | |
| 63 | ! | vignette = 0.4 |
| 64 | } | |
| 65 | ! | image_vignette = make_vignette_overlay( |
| 66 | ! | width = dimensions[1], |
| 67 | ! | height = dimensions[2], |
| 68 | ! | intensity = vignette, |
| 69 | ! | radius = radiusval, |
| 70 | ! | radius_multiplier = radius, |
| 71 | ! | color = color |
| 72 | ) | |
| 73 | ! | temp = render_image_overlay(image, image_vignette) |
| 74 | ! | handle_image_output(temp, filename = filename, preview = preview) |
| 75 | } |
| 1 | rgb_to_hex = function(x) { | |
| 2 | 44x | if (is.null(dim(x))) { |
| 3 | 4x | x = matrix(x, ncol = length(x)) |
| 4 | } | |
| 5 | 44x | if (!(ncol(x) %in% c(3L, 4L))) { |
| 6 | ! | stop("rgb_to_hex(): expected 3 or 4 columns (R,G,B[,A]).") |
| 7 | } | |
| 8 | 44x | x = pmin(pmax(x, 0), 1) |
| 9 | 44x | ints = round(x * 255) |
| 10 | 44x | apply(ints, 1, function(row) { |
| 11 | 76x | paste0("#", paste(sprintf("%02X", row), collapse = "")) |
| 12 | }) | |
| 13 | } | |
| 14 | ||
| 15 | ||
| 16 | array_rgb_to_hex_colmajor = function(arr) { | |
| 17 | 3x | d = dim(arr) |
| 18 | 3x | R = as.vector(arr[,, 1]) |
| 19 | 3x | G = as.vector(arr[,, 2]) |
| 20 | 3x | B = as.vector(arr[,, 3]) |
| 21 | 3x | if (d[3] >= 4L) { |
| 22 | 2x | A = as.vector(arr[,, 4]) |
| 23 | 2x | return(rgb_to_hex(cbind(R, G, B, A))) |
| 24 | } | |
| 25 | 1x | rgb_to_hex(cbind(R, G, B)) |
| 26 | } | |
| 27 | ||
| 28 | #' Render Gamma/Linear | |
| 29 | #' | |
| 30 | #' Convert sRGB-encoded color data to linear light (and vice versa). | |
| 31 | #' | |
| 32 | #' @param color A `rayimg`, hex color string (or vector), length-3 numeric RGB vector, | |
| 33 | #' or RGB/RGBA matrix. | |
| 34 | #' @param srgb_to_linear Default `TRUE`. If `TRUE`, converts sRGB-encoded data to linear light. | |
| 35 | #' If `FALSE`, converts linear-light data to sRGB. | |
| 36 | #' @param as_hex Default `FALSE`. When `srgb_to_linear = FALSE` and input is an RGB/RGBA | |
| 37 | #' matrix or array, returns hex: for matrices a length-`n` vector; for arrays a | |
| 38 | #' length-`prod(dim(x)[1:2])` vector in column-major order. Alpha (if present) is passed through. | |
| 39 | #' | |
| 40 | #' @return Same shape/type as input unless `as_hex = TRUE` on matrix/array with `srgb_to_linear = FALSE`, | |
| 41 | #' in which case a character vector of hex codes is returned. | |
| 42 | #' @export | |
| 43 | #' @examples | |
| 44 | #' # Numeric RGB vector (sRGB -> linear -> back to sRGB) | |
| 45 | #' srgb_vec = c(0.2, 0.4, 0.6) | |
| 46 | #' linear_vec = render_gamma_linear(srgb_vec) | |
| 47 | #' render_gamma_linear(linear_vec, srgb_to_linear = FALSE) | |
| 48 | #' | |
| 49 | #' # Hex input (single color) | |
| 50 | #' linear_from_hex = render_gamma_linear("#336699") | |
| 51 | #' render_gamma_linear(linear_from_hex, srgb_to_linear = FALSE, as_hex = TRUE) | |
| 52 | #' | |
| 53 | #' # Greyscale matrix (treated as image plane) | |
| 54 | #' grey_image = matrix(c(0.1, 0.5, 0.9, 0.3), nrow = 2) | |
| 55 | #' linear_grey = render_gamma_linear(grey_image) | |
| 56 | #' render_gamma_linear(linear_grey, srgb_to_linear = FALSE, as_hex = TRUE) | |
| 57 | #' | |
| 58 | #' # Array with a single greyscale channel | |
| 59 | #' grey_pixels = array(c(0.2, 0.7), dim = c(1, 2, 1)) | |
| 60 | #' linear_grey_arr = render_gamma_linear(grey_pixels) | |
| 61 | #' render_gamma_linear(linear_grey_arr, srgb_to_linear = FALSE, as_hex = TRUE) | |
| 62 | #' | |
| 63 | #' # Array with greyscale + alpha | |
| 64 | #' grey_alpha = array(c(0.3, 0.9, 0.6, 0.4), dim = c(1, 2, 2)) | |
| 65 | #' linear_grey_alpha = render_gamma_linear(grey_alpha) | |
| 66 | #' render_gamma_linear(linear_grey_alpha, srgb_to_linear = FALSE, as_hex = TRUE) | |
| 67 | #' | |
| 68 | #' # RGB array (3 channels) | |
| 69 | #' rgb_pixels = array( | |
| 70 | #' c( | |
| 71 | #' 0.2, 0.4, 0.6, | |
| 72 | #' 0.7, 0.1, 0.3 | |
| 73 | #' ), | |
| 74 | #' dim = c(1, 2, 3) | |
| 75 | #' ) | |
| 76 | #' linear_rgb = render_gamma_linear(rgb_pixels) | |
| 77 | #' render_gamma_linear(linear_rgb, srgb_to_linear = FALSE, as_hex = TRUE) | |
| 78 | #' | |
| 79 | #' # RGBA array (alpha channel preserved) | |
| 80 | #' rgba_pixels = array( | |
| 81 | #' c( | |
| 82 | #' 0.2, 0.4, 0.6, 0.5, | |
| 83 | #' 0.7, 0.1, 0.3, 0.8 | |
| 84 | #' ), | |
| 85 | #' dim = c(1, 2, 4) | |
| 86 | #' ) | |
| 87 | #' linear_rgba = render_gamma_linear(rgba_pixels) | |
| 88 | #' render_gamma_linear(linear_rgba, srgb_to_linear = FALSE, as_hex = TRUE) | |
| 89 | #' | |
| 90 | #' # rayimg input retains metadata and supports hex conversion | |
| 91 | #' linear_img = render_gamma_linear(ray_read_image(rgba_pixels)) | |
| 92 | #' render_gamma_linear(linear_img, srgb_to_linear = FALSE, as_hex = TRUE) | |
| 93 | render_gamma_linear = function(color, srgb_to_linear = TRUE, as_hex = FALSE) { | |
| 94 | 28x | fxn = if (srgb_to_linear) to_linear else to_srgb |
| 95 | ||
| 96 | 28x | if (inherits(color, "rayimg")) { |
| 97 | 4x | out = color |
| 98 | 4x | d = dim(out) |
| 99 | 4x | if (is.null(d)) { |
| 100 | ! | out[] = fxn(out[]) |
| 101 | } else { | |
| 102 | 4x | arr = unclass(out) |
| 103 | 4x | c = d[3] |
| 104 | 4x | if (length(d) == 2L) { |
| 105 | ! | arr = fxn(arr) # greyscale matrix |
| 106 | 4x | } else if (length(d) == 3L) { |
| 107 | 4x | if (c >= 1L) { |
| 108 | 4x | arr[,, 1] = fxn(arr[,, 1]) |
| 109 | } # grey or R | |
| 110 | 4x | if (c >= 3L) { |
| 111 | # RGB | |
| 112 | 4x | arr[,, 2] = fxn(arr[,, 2]) |
| 113 | 4x | arr[,, 3] = fxn(arr[,, 3]) |
| 114 | } | |
| 115 | # alpha (2nd when c==2, 4th when c==4) untouched | |
| 116 | } else { | |
| 117 | ! | stop("render_gamma_linear(): expected 2D matrix or 3D array in rayimg.") |
| 118 | } | |
| 119 | 4x | out[] = arr |
| 120 | } | |
| 121 | 4x | if (!srgb_to_linear && isTRUE(as_hex)) { |
| 122 | 1x | d = dim(out) |
| 123 | 1x | if (length(d) == 2L) { |
| 124 | ! | g = as.vector(unclass(out)) |
| 125 | ! | return(rgb_to_hex(cbind(g, g, g))) |
| 126 | } | |
| 127 | 1x | if (length(d) == 3L && d[3] >= 1L && d[3] <= 4L) { |
| 128 | 1x | arr = unclass(out) |
| 129 | 1x | if (d[3] == 1L) { |
| 130 | ! | g = as.vector(arr[,, 1]) |
| 131 | ! | return(rgb_to_hex(cbind(g, g, g))) |
| 132 | 1x | } else if (d[3] == 2L) { |
| 133 | ! | g = as.vector(arr[,, 1]) |
| 134 | ! | a = as.vector(arr[,, 2]) |
| 135 | ! | return(rgb_to_hex(cbind(g, g, g, a))) |
| 136 | } else { | |
| 137 | 1x | return(array_rgb_to_hex_colmajor(arr)) |
| 138 | } | |
| 139 | } | |
| 140 | ! | stop("render_gamma_linear(): unsupported rayimg shape for hex.") |
| 141 | } | |
| 142 | 3x | attr(out, "source_linear") = srgb_to_linear |
| 143 | 3x | attr(out, "exposure") = 0 |
| 144 | 3x | attr(out, "iso") = 100 |
| 145 | 3x | return(out) |
| 146 | } | |
| 147 | ||
| 148 | 24x | if (is.character(color)) { |
| 149 | 2x | if (!length(color)) { |
| 150 | ! | stop("render_gamma_linear(): character input cannot be empty.") |
| 151 | } | |
| 152 | 2x | if (!srgb_to_linear) { |
| 153 | ! | stop( |
| 154 | ! | "render_gamma_linear(): for hex input, only sRGB -> linear is supported." |
| 155 | ) | |
| 156 | } | |
| 157 | 2x | rgb = t(grDevices::col2rgb(color)) / 255 |
| 158 | 2x | lin = to_linear(rgb) |
| 159 | 1x | return(if (nrow(lin) == 1L) as.numeric(lin[1, ]) else lin) |
| 160 | } | |
| 161 | ||
| 162 | 22x | if (is.matrix(color)) { |
| 163 | 4x | if (srgb_to_linear) { |
| 164 | 1x | return(fxn(color)) # greyscale plane |
| 165 | } else { | |
| 166 | 3x | srgb_grey = fxn(color) |
| 167 | 3x | if (as_hex) { |
| 168 | 1x | g = as.vector(srgb_grey) |
| 169 | 1x | return(rgb_to_hex(cbind(g, g, g))) |
| 170 | } | |
| 171 | 2x | return(srgb_grey) |
| 172 | } | |
| 173 | } | |
| 174 | ||
| 175 | 18x | if (is.array(color)) { |
| 176 | 12x | if (length(dim(color)) != 3L) { |
| 177 | ! | stop("render_gamma_linear(): array must be h*w*c.") |
| 178 | } | |
| 179 | 12x | d = dim(color) |
| 180 | 12x | c = d[3] |
| 181 | 12x | out = color |
| 182 | 12x | if (c >= 1L) { |
| 183 | 12x | out[,, 1] = fxn(out[,, 1]) |
| 184 | } | |
| 185 | 12x | if (c >= 3L) { |
| 186 | 6x | out[,, 2] = fxn(out[,, 2]) |
| 187 | 6x | out[,, 3] = fxn(out[,, 3]) |
| 188 | } | |
| 189 | 12x | if (!srgb_to_linear && as_hex) { |
| 190 | 4x | if (c == 1L) { |
| 191 | 1x | g = as.vector(out[,, 1]) |
| 192 | 1x | return(rgb_to_hex(cbind(g, g, g))) |
| 193 | } | |
| 194 | 3x | if (c == 2L) { |
| 195 | 1x | g = as.vector(out[,, 1]) |
| 196 | 1x | a = as.vector(out[,, 2]) |
| 197 | 1x | return(rgb_to_hex(cbind(g, g, g, a))) |
| 198 | } | |
| 199 | 2x | return(array_rgb_to_hex_colmajor(out)) |
| 200 | } | |
| 201 | 8x | return(out) |
| 202 | } | |
| 203 | ||
| 204 | 6x | if (is.numeric(color)) { |
| 205 | 6x | if (length(color) != 3L) { |
| 206 | ! | stop("render_gamma_linear(): numeric input must be length-3 RGB.") |
| 207 | } | |
| 208 | 6x | if (any(!is.finite(color)) || any(color < 0 | color > 1)) { |
| 209 | ! | stop("render_gamma_linear(): numeric RGB values must be between 0 and 1.") |
| 210 | } | |
| 211 | 6x | out = fxn(color) |
| 212 | 6x | if (!srgb_to_linear && as_hex) { |
| 213 | 4x | return(rgb_to_hex(out)) |
| 214 | } | |
| 215 | 2x | return(out) |
| 216 | } | |
| 217 | ||
| 218 | ! | stop("render_gamma_linear(): unsupported input type.") |
| 219 | } |
| 1 | #'@title Crop Image | |
| 2 | #' | |
| 3 | #'@description Crops an image (or matrix) either by specifying axis-aligned limits | |
| 4 | #'(`width_limits`/`height_limits`) or by specifying a centered box size via `center`. | |
| 5 | #' | |
| 6 | #'@param image Default `NULL`. 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 7 | #'@param width_limits Default `NULL`. Length-2 numeric `(xmin, xmax)` along the width (x/columns). | |
| 8 | #' Values in 0..1 are treated as fractions of image width; otherwise they are pixel indices. | |
| 9 | #' Mutually exclusive with `center`. If provided alone, `height_limits` defaults to full height. | |
| 10 | #'@param height_limits Default `NULL`. Length-2 numeric `(ymin, ymax)` along the height (y/rows). | |
| 11 | #' Values in 0..1 are treated as fractions of image height; otherwise they are pixel indices. | |
| 12 | #' Mutually exclusive with `center`. If provided alone, `width_limits` defaults to full width. | |
| 13 | #'@param center Default `NULL`. Length-2 numeric `(height, width)` for a center-crop. | |
| 14 | #' Values in (0,1] are treated as fractions of `(image height, image width)`; otherwise pixels. | |
| 15 | #' Mutually exclusive with `width_limits`/`height_limits`. | |
| 16 | #'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead. | |
| 17 | #'@param preview Default `FALSE`. Whether to plot the cropped image, or just to return the values. | |
| 18 | #'@return A `rayimg` array with the cropped region. | |
| 19 | #'@export | |
| 20 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 21 | #'# Left half of the image | |
| 22 | #'render_crop(dragon, | |
| 23 | #' width_limits = c(0, 0.50), | |
| 24 | #' height_limits = c(0, 1)) |> | |
| 25 | #' plot_image() | |
| 26 | #'# Right half of the image | |
| 27 | #'render_crop(dragon, | |
| 28 | #' width_limits = c(0.50, 1), | |
| 29 | #' height_limits = c(0, 1)) |> | |
| 30 | #' plot_image() | |
| 31 | #'# Top middle of the image (25%–50% height, 25%–75% width) | |
| 32 | #'render_crop(dragon, | |
| 33 | #' height_limits = c(0.25, 0.50), | |
| 34 | #' width_limits = c(0.25, 0.75)) |> | |
| 35 | #' plot_image() | |
| 36 | #'# Top middle, explicit pixel coords (for a 200x200 image) | |
| 37 | #'render_crop(dragon, | |
| 38 | #' height_limits = c(50, 100), | |
| 39 | #' width_limits = c(50, 150)) |> | |
| 40 | #' plot_image() | |
| 41 | #'# Center-crop: 50% height and width of the image | |
| 42 | #'render_crop(dragon, center = c(0.5, 0.5)) |> | |
| 43 | #' plot_image() | |
| 44 | #'# Center-crop: fixed 50x100 pixels | |
| 45 | #'render_crop(dragon, center = c(50, 100)) |> | |
| 46 | #' plot_image() | |
| 47 | render_crop = function( | |
| 48 | image = NULL, | |
| 49 | width_limits = NULL, | |
| 50 | height_limits = NULL, | |
| 51 | center = NULL, | |
| 52 | filename = NULL, | |
| 53 | preview = FALSE | |
| 54 | ) { | |
| 55 | 1x | if (is.null(image)) { |
| 56 | ! | stop("`image` must be provided.", call. = FALSE) |
| 57 | } | |
| 58 | ||
| 59 | 1x | use_limits = !is.null(width_limits) || !is.null(height_limits) |
| 60 | 1x | use_center = !is.null(center) |
| 61 | ||
| 62 | 1x | if (use_limits && use_center) { |
| 63 | ! | stop( |
| 64 | ! | "Provide either `width_limits`/`height_limits` OR `center`, not both.", |
| 65 | ! | call. = FALSE |
| 66 | ) | |
| 67 | } | |
| 68 | 1x | if (!use_limits && !use_center) { |
| 69 | ! | stop( |
| 70 | ! | "You must provide `width_limits`/`height_limits`, or `center`.", |
| 71 | ! | call. = FALSE |
| 72 | ) | |
| 73 | } | |
| 74 | ||
| 75 | 1x | if (!is.null(filename)) { |
| 76 | ! | if (tools::file_ext(filename) != "png") { |
| 77 | ! | filename = paste0(filename, ".png") |
| 78 | } | |
| 79 | } | |
| 80 | ||
| 81 | # Normalize input and preserve metadata | |
| 82 | 1x | temp_image = ray_read_image(image) |
| 83 | 1x | imagetype = attr(temp_image, "filetype") |
| 84 | 1x | img_source_linear = attr(temp_image, "source_linear") |
| 85 | 1x | colorspace = attr(temp_image, "colorspace") |
| 86 | 1x | white_current = attr(temp_image, "white_current") |
| 87 | ||
| 88 | 1x | h = nrow(temp_image) |
| 89 | 1x | w = ncol(temp_image) |
| 90 | ||
| 91 | 1x | to_px_range = function(lims, len) { |
| 92 | 2x | if (length(lims) != 2 || !is.numeric(lims)) { |
| 93 | ! | stop("Limits must be length-2 numeric.", call. = FALSE) |
| 94 | } | |
| 95 | 2x | a = lims[1] |
| 96 | 2x | b = lims[2] |
| 97 | 2x | if (all(a >= 0, a <= 1, b >= 0, b <= 1)) { |
| 98 | 2x | start = floor(min(a, b) * len) + 1L |
| 99 | 2x | end = ceiling(max(a, b) * len) |
| 100 | } else { | |
| 101 | ! | start = floor(min(a, b)) |
| 102 | ! | end = ceiling(max(a, b)) |
| 103 | } | |
| 104 | 2x | start = max(1L, start) |
| 105 | 2x | end = min(len, end) |
| 106 | 2x | if (end < start) { |
| 107 | ! | stop( |
| 108 | ! | "Computed limits are empty after clamping; check your inputs.", |
| 109 | ! | call. = FALSE |
| 110 | ) | |
| 111 | } | |
| 112 | 2x | c(start, end) |
| 113 | } | |
| 114 | ||
| 115 | 1x | if (use_limits) { |
| 116 | 1x | if (is.null(width_limits)) { |
| 117 | ! | width_limits = c(0, 1) |
| 118 | } | |
| 119 | 1x | if (is.null(height_limits)) { |
| 120 | ! | height_limits = c(0, 1) |
| 121 | } | |
| 122 | ||
| 123 | 1x | x_rng = to_px_range(width_limits, w) |
| 124 | 1x | y_rng = to_px_range(height_limits, h) |
| 125 | ||
| 126 | 1x | x_start = x_rng[1] |
| 127 | 1x | x_end = x_rng[2] |
| 128 | 1x | y_start = y_rng[1] |
| 129 | 1x | y_end = y_rng[2] |
| 130 | } else { | |
| 131 | ! | if (length(center) != 2 || !is.numeric(center)) { |
| 132 | ! | stop( |
| 133 | ! | "`center` must be a length-2 numeric vector (height, width).", |
| 134 | ! | call. = FALSE |
| 135 | ) | |
| 136 | } | |
| 137 | ! | box_h = center[1] |
| 138 | ! | box_w = center[2] |
| 139 | ! | box_h = if (box_h > 0 && box_h <= 1) { |
| 140 | ! | round(max(1, box_h * h)) |
| 141 | } else { | |
| 142 | ! | round(box_h) |
| 143 | } | |
| 144 | ! | box_w = if (box_w > 0 && box_w <= 1) { |
| 145 | ! | round(max(1, box_w * w)) |
| 146 | } else { | |
| 147 | ! | round(box_w) |
| 148 | } | |
| 149 | ! | box_h = min(max(1L, box_h), h) |
| 150 | ! | box_w = min(max(1L, box_w), w) |
| 151 | ||
| 152 | ! | y_start = floor((h - box_h) / 2) + 1L |
| 153 | ! | y_end = y_start + box_h - 1L |
| 154 | ! | x_start = floor((w - box_w) / 2) + 1L |
| 155 | ! | x_end = x_start + box_w - 1L |
| 156 | } | |
| 157 | ||
| 158 | 1x | if (imagetype != "matrix") { |
| 159 | 1x | temp_image = temp_image[y_start:y_end, x_start:x_end, , drop = FALSE] |
| 160 | } else { | |
| 161 | ! | temp_image = temp_image[y_start:y_end, x_start:x_end, drop = FALSE] |
| 162 | } | |
| 163 | ||
| 164 | 1x | temp_image = ray_read_image( |
| 165 | 1x | temp_image, |
| 166 | 1x | filetype = imagetype, |
| 167 | 1x | source_linear = img_source_linear, |
| 168 | 1x | assume_colorspace = colorspace, |
| 169 | 1x | assume_white = white_current |
| 170 | ) | |
| 171 | 1x | handle_image_output(temp_image, filename = filename, preview = preview) |
| 172 | } |
| 1 | #' Render To Display | |
| 2 | #' @description Convert an image from its working space to a display space, and optionally apply sRGB OETF for viewing. | |
| 3 | #' @param image A `rayimg`, array, or filename. | |
| 4 | #' @param display Default `CS_SRGB`. Target display RGB space. | |
| 5 | #' @param encode Default `TRUE`. If `TRUE`, apply sRGB OETF (only valid when `display` is sRGB-like). | |
| 6 | #' @param adapt_white Default `TRUE`. Whether to perform CAT from working white to display white. | |
| 7 | #' @return A `rayimg` when `encode=FALSE`, or a `rayimg` with sRGB-encoded RGB when `encode=TRUE`. | |
| 8 | #' @export | |
| 9 | render_to_display = function( | |
| 10 | image, | |
| 11 | display = CS_SRGB, | |
| 12 | encode = TRUE, | |
| 13 | adapt_white = TRUE | |
| 14 | ) { | |
| 15 | ! | img = ray_read_image( |
| 16 | ! | image, |
| 17 | ! | normalize = FALSE, |
| 18 | ! | reset_camera_settings = TRUE |
| 19 | ) | |
| 20 | # Ensure linear before color conversion | |
| 21 | ! | if (!isTRUE(attr(img, "source_linear"))) { |
| 22 | ! | img = render_gamma_linear(img, srgb_to_linear = TRUE) |
| 23 | } | |
| 24 | # Move primaries (and optionally white) to display | |
| 25 | ! | moved = render_convert_colorspace( |
| 26 | ! | img, |
| 27 | ! | from_mats = NA, |
| 28 | ! | to_mats = display, |
| 29 | ! | adapt_white = adapt_white, |
| 30 | ! | from_white = NA, |
| 31 | ! | to_white = display$white_xyz |
| 32 | ) | |
| 33 | ! | if (!encode) { |
| 34 | ! | return(moved) |
| 35 | } | |
| 36 | # Only sRGB OETF is implemented here | |
| 37 | ! | if (!identical(display$name, CS_SRGB$name)) { |
| 38 | ! | warning( |
| 39 | ! | "render_to_display(): encode=TRUE uses sRGB OETF; non-sRGB displays may require a different OETF/transfer." |
| 40 | ) | |
| 41 | } | |
| 42 | ! | render_gamma_linear(moved, srgb_to_linear = FALSE) |
| 43 | } |
| 1 | prepare_native_raster = function(image, angle = 0, show_linear = FALSE) { | |
| 2 | 62x | img = ray_read_image(image, convert_to_array = TRUE) |
| 3 | ||
| 4 | 62x | display = img |
| 5 | 62x | cs_from = attr(display, "colorspace") |
| 6 | 62x | white_curr = attr(display, "white_current") |
| 7 | ||
| 8 | 62x | display = render_clamp(display) |
| 9 | 62x | display[is.na(display)] = 0 |
| 10 | ||
| 11 | 62x | alpha_channel = unclass(render_clamp( |
| 12 | 62x | display[,, 4], |
| 13 | 62x | min_value = 0, |
| 14 | 62x | max_value = 1 |
| 15 | )) | |
| 16 | 62x | display[,, 4] = alpha_channel |
| 17 | ||
| 18 | 62x | if (!show_linear) { |
| 19 | if ( | |
| 20 | 62x | !is.null(cs_from) && |
| 21 | 62x | (!identical(cs_from$name, "sRGB") || |
| 22 | 62x | any(abs(white_curr - CS_SRGB$white_xyz) > 1e-8)) |
| 23 | ) { | |
| 24 | 28x | xyz = apply_color_matrix(display, cs_from$rgb_to_xyz) |
| 25 | 28x | if (any(abs(white_curr - CS_SRGB$white_xyz) > 1e-8)) { |
| 26 | 28x | CAT = compute_cat_bradford(white_curr, CS_SRGB$white_xyz) |
| 27 | 28x | xyz = apply_color_matrix(xyz, CAT) |
| 28 | } | |
| 29 | 28x | display = apply_color_matrix(xyz, CS_SRGB$xyz_to_rgb) |
| 30 | 28x | display[,, 1:3][display[,, 1:3] < 0] = 0 |
| 31 | } | |
| 32 | 62x | display[,, 1:3] = to_srgb(display[,, 1:3]) |
| 33 | } | |
| 34 | ||
| 35 | 62x | if (!isTRUE(all.equal(angle %% 360, 0))) { |
| 36 | ! | display = rotate_image_array(display, angle) |
| 37 | } | |
| 38 | ||
| 39 | 62x | list( |
| 40 | 62x | native_raster = convert_to_native_raster(display), |
| 41 | 62x | display_dim = dim(display) |
| 42 | ) | |
| 43 | } |
| 1 | #' Rotate an image array around its center | |
| 2 | #' | |
| 3 | #' @keywords internal | |
| 4 | rotate_image_array = function(img, angle) { | |
| 5 | ! | if (length(dim(img)) < 2) { |
| 6 | ! | stop("rotate_image_array() expects a matrix or array input") |
| 7 | } | |
| 8 | ! | if (is.null(angle) || is.na(angle) || !is.finite(angle)) { |
| 9 | ! | return(img) |
| 10 | } | |
| 11 | ! | angle = angle %% 360 |
| 12 | ! | if (isTRUE(all.equal(angle, 0))) { |
| 13 | ! | return(img) |
| 14 | } | |
| 15 | ! | theta = angle * pi / 180 |
| 16 | ! | cos_t = cos(theta) |
| 17 | ! | sin_t = sin(theta) |
| 18 | ||
| 19 | ! | dims = dim(img) |
| 20 | ! | if (length(dims) == 2) { |
| 21 | ! | img = array(img, dim = c(dims, 1)) |
| 22 | ! | dims = dim(img) |
| 23 | } | |
| 24 | ! | height = dims[1] |
| 25 | ! | width = dims[2] |
| 26 | ! | channels = dims[3] |
| 27 | ||
| 28 | ! | width_rot = abs(width * cos_t) + abs(height * sin_t) |
| 29 | ! | height_rot = abs(width * sin_t) + abs(height * cos_t) |
| 30 | ! | new_width = max(1L, as.integer(ceiling(width_rot))) |
| 31 | ! | new_height = max(1L, as.integer(ceiling(height_rot))) |
| 32 | ||
| 33 | ! | cx_old = (width + 1) / 2 |
| 34 | ! | cy_old = (height + 1) / 2 |
| 35 | ! | cx_new = (new_width + 1) / 2 |
| 36 | ! | cy_new = (new_height + 1) / 2 |
| 37 | ||
| 38 | ! | x_indices = matrix( |
| 39 | ! | rep(seq_len(new_width), each = new_height), |
| 40 | ! | nrow = new_height |
| 41 | ) | |
| 42 | ! | y_indices = matrix( |
| 43 | ! | rep(seq_len(new_height), times = new_width), |
| 44 | ! | nrow = new_height |
| 45 | ) | |
| 46 | ||
| 47 | ! | x_rel = x_indices - cx_new |
| 48 | ! | y_rel = cy_new - y_indices |
| 49 | ||
| 50 | ! | x_src = x_rel * cos_t + y_rel * sin_t + cx_old |
| 51 | ! | y_src_rel = -x_rel * sin_t + y_rel * cos_t |
| 52 | ! | y_src = cy_old - y_src_rel |
| 53 | ||
| 54 | ! | x_vec = as.vector(x_src) |
| 55 | ! | y_vec = as.vector(y_src) |
| 56 | ||
| 57 | ! | rotated = array(0, dim = c(new_height, new_width, channels)) |
| 58 | ! | for (ch in seq_len(channels)) { |
| 59 | ! | channel = img[,, ch, drop = TRUE] |
| 60 | ! | rotated_channel = bilinear_sample_matrix(channel, x_vec, y_vec) |
| 61 | ! | rotated[,, ch] = matrix( |
| 62 | ! | rotated_channel, |
| 63 | ! | nrow = new_height, |
| 64 | ! | ncol = new_width |
| 65 | ) | |
| 66 | } | |
| 67 | ! | return(rotated) |
| 68 | } | |
| 69 | ||
| 70 | bilinear_sample_matrix = function(mat, x, y, fill = 0) { | |
| 71 | ! | height = nrow(mat) |
| 72 | ! | width = ncol(mat) |
| 73 | ! | result = rep(fill, length(x)) |
| 74 | ! | valid = !is.na(x) & !is.na(y) & x >= 1 & x <= width & y >= 1 & y <= height |
| 75 | ! | if (!any(valid)) { |
| 76 | ! | return(result) |
| 77 | } | |
| 78 | ! | xv = x[valid] |
| 79 | ! | yv = y[valid] |
| 80 | ! | x0 = floor(xv) |
| 81 | ! | y0 = floor(yv) |
| 82 | ! | x1 = pmin(x0 + 1, width) |
| 83 | ! | y1 = pmin(y0 + 1, height) |
| 84 | ! | dx = xv - x0 |
| 85 | ! | dy = yv - y0 |
| 86 | ||
| 87 | ! | idx00 = cbind(as.integer(y0), as.integer(x0)) |
| 88 | ! | idx10 = cbind(as.integer(y0), as.integer(x1)) |
| 89 | ! | idx01 = cbind(as.integer(y1), as.integer(x0)) |
| 90 | ! | idx11 = cbind(as.integer(y1), as.integer(x1)) |
| 91 | ||
| 92 | ! | v00 = mat[idx00] |
| 93 | ! | v10 = mat[idx10] |
| 94 | ! | v01 = mat[idx01] |
| 95 | ! | v11 = mat[idx11] |
| 96 | ||
| 97 | ! | interp = v00 * |
| 98 | ! | (1 - dx) * |
| 99 | ! | (1 - dy) + |
| 100 | ! | v10 * dx * (1 - dy) + |
| 101 | ! | v01 * (1 - dx) * dy + |
| 102 | ! | v11 * dx * dy |
| 103 | ! | result[valid] = interp |
| 104 | ! | return(result) |
| 105 | } |
| 1 | #'@title Stack Images | |
| 2 | #' | |
| 3 | #'@description Stacks a list of images vertically or horizontally into a single image. | |
| 4 | #' | |
| 5 | #'@param input_list List of 3-layer RGB/4-layer RGBA array, `rayimg` class, or image filenames. | |
| 6 | #'@param stack Default `"v"`. Stack direction: `"v"`/`"vertical"` or `"h"`/`"horizontal"`. | |
| 7 | #'@param align Default `"center"`. Alignment on the non-stacking axis. Options: | |
| 8 | #'`"start"`/`"left"`/`"top"`, `"center"`, `"end"`/`"right"`/`"bottom"`. | |
| 9 | #'@param background Default `c(0,0,0,0)`. Background color for padding, as numeric | |
| 10 | #'`c(r,g,b[,a])` in 0..1 or a color string. | |
| 11 | #'@param convert_colorspace Default `TRUE`. Whether to convert all images to match | |
| 12 | #'the colorspace of the first image in the list. | |
| 13 | #'@param filename Default `NULL`. File to save the image to. If `NULL` and `preview = FALSE`, | |
| 14 | #'returns an RGB array. | |
| 15 | #'@param preview Default `FALSE`. If `TRUE`, it will display the image in addition | |
| 16 | #'to returning it. | |
| 17 | #' | |
| 18 | #'@return A `rayimg` RGBA array. | |
| 19 | #'@export | |
| 20 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 21 | #'render_stack(list(dragon, 1 - dragon), stack = "h") |> | |
| 22 | #' plot_image() | |
| 23 | #'render_stack(list(dragon, render_bw(dragon)), stack = "v") |> | |
| 24 | #' plot_image() | |
| 25 | render_stack = function( | |
| 26 | input_list, | |
| 27 | stack = c("v", "h", "vertical", "horizontal"), | |
| 28 | align = c("center", "start", "end", "left", "right", "top", "bottom"), | |
| 29 | background = c(0, 0, 0, 0), | |
| 30 | convert_colorspace = TRUE, | |
| 31 | filename = NULL, | |
| 32 | preview = FALSE | |
| 33 | ) { | |
| 34 | 3x | if (!inherits(input_list, "list") || length(input_list) == 0) { |
| 35 | ! | stop("`input_list` must be a non-empty list of images.") |
| 36 | } | |
| 37 | 3x | if (any(vapply(input_list, is.null, logical(1)))) { |
| 38 | ! | stop("`input_list` cannot contain NULL entries.") |
| 39 | } | |
| 40 | ||
| 41 | 3x | if (missing(stack)) { |
| 42 | ! | stack = "v" |
| 43 | } else { | |
| 44 | 3x | stack = tolower(stack) |
| 45 | } | |
| 46 | 3x | stack = match.arg(stack, c("v", "h", "vertical", "horizontal")) |
| 47 | 3x | is_vertical = stack %in% c("v", "vertical") |
| 48 | 3x | if (missing(align)) { |
| 49 | 1x | align = "center" |
| 50 | } else { | |
| 51 | 2x | align = tolower(align) |
| 52 | } | |
| 53 | 3x | align = match.arg( |
| 54 | 3x | align, |
| 55 | 3x | c("center", "start", "end", "left", "right", "top", "bottom") |
| 56 | ) | |
| 57 | 3x | align = switch( |
| 58 | 3x | align, |
| 59 | 3x | left = "start", |
| 60 | 3x | top = "start", |
| 61 | 3x | right = "end", |
| 62 | 3x | bottom = "end", |
| 63 | 3x | align |
| 64 | ) | |
| 65 | ||
| 66 | 3x | images = lapply(input_list, function(img) { |
| 67 | 6x | ray_read_image( |
| 68 | 6x | img, |
| 69 | 6x | convert_to_array = TRUE, |
| 70 | 6x | reset_camera_settings = TRUE |
| 71 | ) | |
| 72 | }) | |
| 73 | ||
| 74 | 3x | base_image = images[[1]] |
| 75 | 3x | base_colorspace = attr(base_image, "colorspace") |
| 76 | 3x | base_white = attr(base_image, "white_current") |
| 77 | ||
| 78 | 3x | if (convert_colorspace) { |
| 79 | ! | for (i in seq_along(images)) { |
| 80 | ! | images[[i]] = render_convert_colorspace( |
| 81 | ! | images[[i]], |
| 82 | ! | to_mats = base_colorspace, |
| 83 | ! | to_white = base_white |
| 84 | ) | |
| 85 | } | |
| 86 | ! | base_white = attr(images[[1]], "white_current") |
| 87 | } | |
| 88 | ||
| 89 | 3x | heights = vapply(images, function(img) dim(img)[1], numeric(1)) |
| 90 | 3x | widths = vapply(images, function(img) dim(img)[2], numeric(1)) |
| 91 | 3x | max_height = max(heights) |
| 92 | 3x | max_width = max(widths) |
| 93 | ||
| 94 | 3x | if (is_vertical) { |
| 95 | 3x | out_height = sum(heights) |
| 96 | 3x | out_width = max_width |
| 97 | } else { | |
| 98 | ! | out_height = max_height |
| 99 | ! | out_width = sum(widths) |
| 100 | } | |
| 101 | ||
| 102 | 3x | bg = convert_color(background, single = TRUE) |
| 103 | 2x | if (length(bg) == 3) { |
| 104 | ! | bg = c(bg, 1) |
| 105 | } | |
| 106 | 2x | stacked = array(0, dim = c(out_height, out_width, 4)) |
| 107 | 2x | stacked[,, 1] = bg[1] |
| 108 | 2x | stacked[,, 2] = bg[2] |
| 109 | 2x | stacked[,, 3] = bg[3] |
| 110 | 2x | stacked[,, 4] = bg[4] |
| 111 | ||
| 112 | 2x | align_offset = function(total, size) { |
| 113 | 4x | extra = total - size |
| 114 | 4x | if (extra < 0) { |
| 115 | ! | stop("stacked size cannot be smaller than component size.") |
| 116 | } | |
| 117 | 2x | switch( |
| 118 | 4x | align, |
| 119 | 4x | start = 1L, |
| 120 | ! | center = floor(extra / 2) + 1L, |
| 121 | ! | end = extra + 1L |
| 122 | ) | |
| 123 | } | |
| 124 | ||
| 125 | 2x | if (is_vertical) { |
| 126 | 2x | row_start = 1L |
| 127 | 2x | for (i in seq_along(images)) { |
| 128 | 4x | img = unclass(images[[i]]) |
| 129 | 4x | h = dim(img)[1] |
| 130 | 4x | w = dim(img)[2] |
| 131 | 4x | col_start = align_offset(max_width, w) |
| 132 | 4x | rows = row_start:(row_start + h - 1L) |
| 133 | 4x | cols = col_start:(col_start + w - 1L) |
| 134 | 4x | stacked[rows, cols, ] = img |
| 135 | 4x | row_start = row_start + h |
| 136 | } | |
| 137 | } else { | |
| 138 | ! | col_start = 1L |
| 139 | ! | for (i in seq_along(images)) { |
| 140 | ! | img = unclass(images[[i]]) |
| 141 | ! | h = dim(img)[1] |
| 142 | ! | w = dim(img)[2] |
| 143 | ! | row_start = align_offset(max_height, h) |
| 144 | ! | rows = row_start:(row_start + h - 1L) |
| 145 | ! | cols = col_start:(col_start + w - 1L) |
| 146 | ! | stacked[rows, cols, ] = img |
| 147 | ! | col_start = col_start + w |
| 148 | } | |
| 149 | } | |
| 150 | ||
| 151 | 2x | stacked = ray_read_image( |
| 152 | 2x | stacked, |
| 153 | 2x | assume_colorspace = base_colorspace, |
| 154 | 2x | assume_white = base_white, |
| 155 | 2x | source_linear = TRUE |
| 156 | ) | |
| 157 | 2x | handle_image_output(stacked, filename = filename, preview = preview) |
| 158 | } |
| 1 | #' Check Filename | |
| 2 | #' | |
| 3 | #' @param file Filename to be checked | |
| 4 | #' @return Filename | |
| 5 | #' @keywords internal | |
| 6 | #' | |
| 7 | #' @examples | |
| 8 | #' #Fake example | |
| 9 | get_file_type = function(file) { | |
| 10 | 789x | if (is.character(file)) { |
| 11 | 61x | ext = tolower(tools::file_ext(file)) |
| 12 | 61x | if (ext == "png") { |
| 13 | 46x | imagetype = "png" |
| 14 | 15x | } else if (ext %in% c("tif", "tiff")) { |
| 15 | 2x | imagetype = "tif" |
| 16 | 13x | } else if (ext %in% c("jpeg", "jpg")) { |
| 17 | 2x | imagetype = "jpg" |
| 18 | 11x | } else if (ext == "exr") { |
| 19 | 4x | imagetype = "exr" |
| 20 | 7x | } else if (ext == "hdr") { |
| 21 | 1x | imagetype = "hdr" |
| 22 | 6x | } else if (ext == "dng") { |
| 23 | ! | imagetype = "dng" |
| 24 | 6x | } else if (ext == "tga") { |
| 25 | 1x | imagetype = "tga" |
| 26 | 5x | } else if (ext == "bmp") { |
| 27 | 1x | imagetype = "bmp" |
| 28 | 4x | } else if (ext == "psd") { |
| 29 | 1x | imagetype = "psd" |
| 30 | 3x | } else if (ext == "gif") { |
| 31 | 1x | imagetype = "gif" |
| 32 | 2x | } else if (ext == "pic") { |
| 33 | 1x | imagetype = "pic" |
| 34 | 1x | } else if (ext %in% c("pnm", "ppm", "pgm")) { |
| 35 | 1x | imagetype = "pnm" |
| 36 | } else { | |
| 37 | ! | stop( |
| 38 | "`", | |
| 39 | ! | file, |
| 40 | ! | "` not recognized class (png, tiff, jpeg, exr, hdr, dng, tga, bmp, psd, gif, pic, pnm, array, matrix)." |
| 41 | ) | |
| 42 | } | |
| 43 | 728x | } else if (length(dim(file)) == 3 && dim(file)[3] == 1) { |
| 44 | ! | imagetype = "matrix" |
| 45 | 728x | } else if (length(dim(file)) == 3) { |
| 46 | 591x | imagetype = "array" |
| 47 | 137x | } else if (length(dim(file)) == 2) { |
| 48 | 137x | imagetype = "matrix" |
| 49 | ! | } else if (length(dim(file)) > 3) { |
| 50 | ! | stop( |
| 51 | ! | "Images can only be paths to image files, matrices, ", |
| 52 | ! | "and arrays with fewer than 3 dimensions" |
| 53 | ) | |
| 54 | } else { | |
| 55 | ! | if (is.character(file)) { |
| 56 | ! | stop( |
| 57 | "`", | |
| 58 | ! | file, |
| 59 | ! | "` not recognized class (png, tiff, jpeg, exr, hdr, dng, tga, bmp, psd, gif, pic, pnm, array, matrix)." |
| 60 | ) | |
| 61 | } else { | |
| 62 | ! | stop( |
| 63 | ! | "input not recognized class (png, tiff, jpeg, exr, hdr, dng, tga, bmp, psd, gif, pic, pnm, array, matrix)." |
| 64 | ) | |
| 65 | } | |
| 66 | } | |
| 67 | 789x | imagetype |
| 68 | } |
| 1 | #' Add a Small Corner Tagline | |
| 2 | #' | |
| 3 | #' Render a single line of text in a corner without resizing the image. The | |
| 4 | #' default monospace font and size keep the tagline small across resolutions. | |
| 5 | #' Text is alpha-composited using the image's colorspace. | |
| 6 | #' | |
| 7 | #' @param image RGB/RGBA array, `rayimg`, or image filename. | |
| 8 | #' @param text Single-line tagline to add. | |
| 9 | #' @param corner Default `"bottomright"`. One of `"bottomright"`, | |
| 10 | #' `"bottomleft"`, `"topright"`, or `"topleft"`. | |
| 11 | #' @param size Default `NULL`. Font size in pixels at 72 dpi. `NULL` uses | |
| 12 | #' the image width divided by 64, rounded, with a minimum of 6. | |
| 13 | #' @param padding Default `NULL`. Inset from both corner edges in pixels. | |
| 14 | #' `NULL` uses the image width divided by 64, rounded, with a minimum of 4. | |
| 15 | #' @param font Default `"mono"`. Font family; the default is fixed-width. | |
| 16 | #' @param color Default `"white"`. Text color. | |
| 17 | #' @param alpha Default `0.7`. Text opacity, between zero and one. | |
| 18 | #' @param filename Default `NULL`. Optional output image filename. | |
| 19 | #' @param preview Default `FALSE`. Display the result as well as returning it. | |
| 20 | #' @return A `rayimg` array, invisibly when saved or previewed. RGB/RGBA array | |
| 21 | #' inputs retain their channel count. Text that does not fit raises an error; | |
| 22 | #' reduce `size` or `padding`, or shorten `text`. | |
| 23 | #' @export | |
| 24 | #' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 25 | #' render_tagline(dragon, "Created with rayrender", preview = TRUE) | |
| 26 | render_tagline = function( | |
| 27 | image, | |
| 28 | text, | |
| 29 | corner = "bottomright", | |
| 30 | size = NULL, | |
| 31 | padding = NULL, | |
| 32 | font = "mono", | |
| 33 | color = "white", | |
| 34 | alpha = .7, | |
| 35 | filename = NULL, | |
| 36 | preview = FALSE | |
| 37 | ) { | |
| 38 | 15x | corner = match.arg( |
| 39 | 15x | corner, |
| 40 | 15x | c("bottomright", "bottomleft", "topright", "topleft") |
| 41 | ) | |
| 42 | if ( | |
| 43 | 14x | !is.character(text) || |
| 44 | 14x | length(text) != 1L || |
| 45 | 14x | is.na(text) || |
| 46 | 14x | !nzchar(trimws(text)) || |
| 47 | 14x | grepl("[\r\n]", text) |
| 48 | ) { | |
| 49 | 2x | stop("`text` must be one nonempty line.") |
| 50 | } | |
| 51 | if ( | |
| 52 | 12x | !is.character(font) || length(font) != 1L || is.na(font) || !nzchar(font) |
| 53 | ) { | |
| 54 | ! | stop("`font` must be one nonempty font family.") |
| 55 | } | |
| 56 | if ( | |
| 57 | 12x | !is.numeric(alpha) || |
| 58 | 12x | length(alpha) != 1L || |
| 59 | 12x | !is.finite(alpha) || |
| 60 | 12x | alpha < 0 || |
| 61 | 12x | alpha > 1 |
| 62 | ) { | |
| 63 | 1x | stop("`alpha` must be a number between zero and one.") |
| 64 | } | |
| 65 | 11x | source = ray_read_image(image, convert_to_array = TRUE) |
| 66 | 11x | height = dim(source)[1] |
| 67 | 11x | width = dim(source)[2] |
| 68 | 11x | if (is.null(size)) { |
| 69 | 4x | size = max(6, round(width / 64)) |
| 70 | } | |
| 71 | 11x | if (is.null(padding)) { |
| 72 | 6x | padding = max(4, round(width / 64)) |
| 73 | } | |
| 74 | if ( | |
| 75 | 11x | !is.numeric(size) || length(size) != 1L || !is.finite(size) || size <= 0 |
| 76 | ) { | |
| 77 | 1x | stop("`size` must be a positive number.") |
| 78 | } | |
| 79 | if ( | |
| 80 | 10x | !is.numeric(padding) || |
| 81 | 10x | length(padding) != 1L || |
| 82 | 10x | !is.finite(padding) || |
| 83 | 10x | padding < 0 || |
| 84 | 10x | padding != round(padding) |
| 85 | ) { | |
| 86 | 1x | stop("`padding` must be a nonnegative integer.") |
| 87 | } | |
| 88 | 9x | label = render_text_image( |
| 89 | 9x | text, |
| 90 | 9x | size = size, |
| 91 | 9x | font = font, |
| 92 | 9x | color = color, |
| 93 | 9x | background_alpha = 0, |
| 94 | 9x | trim = TRUE |
| 95 | ) | |
| 96 | 9x | if (ncol(label) + 2 * padding > width || nrow(label) + 2 * padding > height) { |
| 97 | 1x | stop("Tagline does not fit. Reduce `size` or `padding`, or shorten `text`.") |
| 98 | } | |
| 99 | 8x | right = corner %in% c("bottomright", "topright") |
| 100 | 8x | bottom = corner %in% c("bottomright", "bottomleft") |
| 101 | # Sprite anchors use inclusive, one-based pixel coordinates. This leaves | |
| 102 | # exactly `padding` untouched rows/columns outside the glyph bounding box. | |
| 103 | 8x | coords = c( |
| 104 | 8x | if (right) width - padding else padding + 1, |
| 105 | 8x | if (bottom) height - padding else padding + 1 |
| 106 | ) | |
| 107 | 8x | anchor = switch( |
| 108 | 8x | corner, |
| 109 | 8x | bottomright = "se", |
| 110 | 8x | bottomleft = "sw", |
| 111 | 8x | topright = "ne", |
| 112 | 8x | topleft = "nw" |
| 113 | ) | |
| 114 | 8x | render_sprite_overlay( |
| 115 | 8x | image, |
| 116 | 8x | label, |
| 117 | 8x | overlay_coords = coords, |
| 118 | 8x | overlay_anchor = anchor, |
| 119 | 8x | alpha = alpha, |
| 120 | 8x | filename = filename, |
| 121 | 8x | preview = preview |
| 122 | ) | |
| 123 | } |
| 1 | #' @title Render Convert Colorspace | |
| 2 | #' @description Convert between two RGB spaces via XYZ, with optional white adaptation. Operates on **linear** RGB. | |
| 3 | #' | |
| 4 | #' @param image 3-layer RGB/4-layer RGBA array, `rayimg`, or filename. | |
| 5 | #' @param from_mats Default `NA`. Source space object; when `NA`, pulled from `attr(src,"colorspace")`. | |
| 6 | #' @param to_mats Default `CS_ACESCG`. Target space object. | |
| 7 | #' @param adapt_white Default `TRUE`. Apply Bradford CAT from `from_white` to `to_white`. | |
| 8 | #' @param from_white Default `NA`. Source white (name or XYZ, Y=1). When `NA`, uses `attr(src,"white_current")`. | |
| 9 | #' @param to_white Default `NA`. Target white (name or XYZ, Y=1). When `NA`, uses `to_mats$white_xyz`. | |
| 10 | #' @param filename Default `NULL`. Output path. | |
| 11 | #' @param preview Default `FALSE`. If `TRUE`, display the image. | |
| 12 | #' @return A `rayimg` RGBA array tagged with the **target** space. | |
| 13 | #' @export | |
| 14 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 15 | #' # Read photo, convert to ACEScg with CAT (scene) | |
| 16 | #' photo = ray_read_image(sunset_image, normalize = FALSE) | |
| 17 | #' photo_aces = render_convert_colorspace( | |
| 18 | #' photo, | |
| 19 | #' to_mats = CS_ACESCG, | |
| 20 | #' adapt_white = TRUE | |
| 21 | #' ) | |
| 22 | #' tmp_txt = tempfile(fileext = ".png") | |
| 23 | #' render_text_image( | |
| 24 | #' "Sunset", | |
| 25 | #' size = 60, | |
| 26 | #' filename = tmp_txt, | |
| 27 | #' color = "#c300ffff", | |
| 28 | #' background_alpha = 0 | |
| 29 | #' ) | |
| 30 | #' # Read logo (display-referred), convert primaries only (no CAT) | |
| 31 | #' logo = ray_read_image(tmp_txt, normalize = FALSE) # sRGB/D65 | |
| 32 | #' logo_aces = render_convert_colorspace( | |
| 33 | #' logo, | |
| 34 | #' to_mats = CS_ACESCG, | |
| 35 | #' adapt_white = FALSE | |
| 36 | #' ) | |
| 37 | #' | |
| 38 | #' # Composite in ACEScg, then display (plot_image converts to sRGB/D65 + OETF) | |
| 39 | #' # Here, we also turn overlay conversion in [render_image_overlay()] off, | |
| 40 | #' # to show what happens when you don't account for the colorspace difference. | |
| 41 | #' # By default [render_image_overlay()] will do this for you. | |
| 42 | #' comp1 = render_image_overlay( | |
| 43 | #' photo_aces, | |
| 44 | #' logo_aces, | |
| 45 | #' convert_overlay_colorspace = FALSE | |
| 46 | #' ) | |
| 47 | #' comp2 = render_image_overlay( | |
| 48 | #' photo_aces, | |
| 49 | #' logo, | |
| 50 | #' convert_overlay_colorspace = FALSE | |
| 51 | #' ) | |
| 52 | #' #Note the color differences, which arise from the mismatched colorspace on the right. | |
| 53 | #' plot_image_grid(list(comp1, comp2), dim = c(1, 2)) | |
| 54 | render_convert_colorspace = function( | |
| 55 | image, | |
| 56 | from_mats = NA, | |
| 57 | to_mats = CS_ACESCG, | |
| 58 | adapt_white = TRUE, | |
| 59 | from_white = NA, | |
| 60 | to_white = NA, | |
| 61 | filename = NULL, | |
| 62 | preview = FALSE | |
| 63 | ) { | |
| 64 | 10x | og_src = ray_read_image(image, normalize = FALSE) |
| 65 | 10x | d = dim(og_src) |
| 66 | 10x | if (length(d) != 3L || d[3] < 3L) { |
| 67 | ! | return(handle_image_output(og_src, filename = filename, preview = preview)) |
| 68 | } | |
| 69 | 10x | src = ray_read_image(image, normalize = FALSE) |
| 70 | ||
| 71 | 10x | if (is.atomic(from_mats) && length(from_mats) == 1L && is.na(from_mats)) { |
| 72 | 10x | from_mats = attr(src, "colorspace") |
| 73 | } | |
| 74 | 10x | stopifnot(is.list(from_mats), is.list(to_mats)) |
| 75 | ||
| 76 | 10x | if (is.atomic(from_white) && length(from_white) == 1L && is.na(from_white)) { |
| 77 | 10x | from_white = attr(src, "white_current") |
| 78 | } | |
| 79 | 10x | if (is.atomic(to_white) && length(to_white) == 1L && is.na(to_white)) { |
| 80 | 10x | to_white = to_mats$white_xyz |
| 81 | } | |
| 82 | ||
| 83 | 10x | src_wp = get_whitepoint_xyz(from_white) |
| 84 | 10x | dst_wp = get_whitepoint_xyz(to_white) |
| 85 | ||
| 86 | # Idempotence: same primaries, no CAT, and equal whites | |
| 87 | 10x | same_mats = isTRUE(all.equal(from_mats$rgb_to_xyz, to_mats$rgb_to_xyz)) && |
| 88 | 10x | isTRUE(all.equal(from_mats$xyz_to_rgb, to_mats$xyz_to_rgb)) |
| 89 | 10x | same_white = isTRUE(all.equal(src_wp$value, dst_wp$value)) |
| 90 | 10x | if (same_mats && (!adapt_white || same_white)) { |
| 91 | 2x | return(handle_image_output(src, filename = filename, preview = preview)) |
| 92 | } | |
| 93 | ||
| 94 | # Assert linear data | |
| 95 | 8x | if (!isTRUE(attr(src, "source_linear"))) { |
| 96 | ! | warning( |
| 97 | ! | "render_convert_colorspace(): input is not linear; convert with render_gamma_linear(..., TRUE) first." |
| 98 | ) | |
| 99 | } | |
| 100 | ||
| 101 | # RGB(from) -> XYZ | |
| 102 | 8x | xyz = apply_color_matrix(src, from_mats$rgb_to_xyz) |
| 103 | ||
| 104 | # Optional CAT in XYZ | |
| 105 | 8x | if (adapt_white && !isTRUE(all.equal(src_wp$value, dst_wp$value))) { |
| 106 | 8x | CAT = compute_cat_bradford(src_wp$value, dst_wp$value) |
| 107 | 8x | xyz = apply_color_matrix(xyz, CAT) |
| 108 | } | |
| 109 | ||
| 110 | # XYZ -> RGB(to) | |
| 111 | 8x | out = apply_color_matrix(xyz, to_mats$xyz_to_rgb) |
| 112 | 8x | if (d[3] == 4L) { |
| 113 | 7x | out[,, 4] = src[,, 4] |
| 114 | } # preserve alpha | |
| 115 | ||
| 116 | # Tag with the target space | |
| 117 | 8x | white_tag = if (adapt_white) dst_wp else src_wp |
| 118 | 8x | to_mats$white_name = white_tag$white_name |
| 119 | ||
| 120 | 8x | out = rayimg( |
| 121 | 8x | out, |
| 122 | 8x | filetype = attr(src, "filetype"), |
| 123 | 8x | source_linear = TRUE, |
| 124 | 8x | colorspace = to_mats, |
| 125 | 8x | white_current = white_tag$value, |
| 126 | 8x | exposure = attr(src, "exposure", exact = TRUE), |
| 127 | 8x | iso = attr(src, "iso", exact = TRUE) |
| 128 | ) | |
| 129 | ||
| 130 | 8x | handle_image_output(out, filename = filename, preview = preview) |
| 131 | } |
| 1 | #' @title Render Color Correction Matrix (3x3, linear RGB) | |
| 2 | #' | |
| 3 | #' @description Apply a technical/look 3x3 matrix to an image | |
| 4 | #' | |
| 5 | #' @param image Default `NULL`. 3-layer RGB/4-layer RGBA array, `rayimg`, or filename. | |
| 6 | #' @param matrix Default `diag(3)`. 3x3 numeric matrix. | |
| 7 | #' @param filename Default `NULL`. Output path. | |
| 8 | #' @param preview Default `FALSE`. If `TRUE`, display the image. | |
| 9 | #' @return A `rayimg` RGBA array. | |
| 10 | #' @export | |
| 11 | #' @examples | |
| 12 | #' # We will start with an image that's too warm--we want to correct it to | |
| 13 | #' # match the color of the second as closely as possible. | |
| 14 | #' dragon_D50 = render_white_balance(dragon, target_white = "D50", bake = TRUE) | |
| 15 | #' dragon_D75 = render_white_balance(dragon, target_white = "D75", bake = TRUE) | |
| 16 | #' plot_image(dragon_D50) | |
| 17 | #' plot_image(dragon_D75) | |
| 18 | #' | |
| 19 | #' # Fucntion to fit a color correction matrix | |
| 20 | #' fit_cc_matrix = function(src, tgt) { | |
| 21 | #' stopifnot(ncol(src) == 3, ncol(tgt) == 3, nrow(src) == nrow(tgt)) | |
| 22 | #' M_t = apply(tgt, 2, function(y) qr.solve(src, y)) | |
| 23 | #' t(M_t) | |
| 24 | #' } | |
| 25 | #' | |
| 26 | #' # Sample N RGBs from an image for fit | |
| 27 | #' rand_samples = function(img, n = 5000, seed=1) { | |
| 28 | #' set.seed(seed) | |
| 29 | #' d = dim(img) | |
| 30 | #' ys = sample.int(d[1], n, TRUE); xs = sample.int(d[2], n, TRUE) | |
| 31 | #' cbind(img[cbind(ys,xs,1)], img[cbind(ys,xs,2)], img[cbind(ys,xs,3)]) | |
| 32 | #' } | |
| 33 | #' | |
| 34 | #' S = rand_samples(dragon_D50) | |
| 35 | #' T = rand_samples(dragon_D75) | |
| 36 | #' | |
| 37 | #' M = fit_cc_matrix(S, T) | |
| 38 | #' # Optionally, regularize toward identity to avoid overfitting | |
| 39 | #' # M = 0.8 * M + 0.2 * diag(3) | |
| 40 | #' | |
| 41 | #' updated_source = render_color_correction(dragon_D50, matrix = M) | |
| 42 | #' | |
| 43 | #' # Matching the old image (grey) to the target image (orange), | |
| 44 | #' # giving a new image (black). | |
| 45 | #' plot(S,pch=16,cex=0.5,col="grey") | |
| 46 | #' points(T,pch=16,cex=0.5,col="orange") | |
| 47 | #' points(rand_samples(updated_source,seed=2),pch=16,cex=0.5,col="black") | |
| 48 | #' | |
| 49 | #' # Plot the images | |
| 50 | #' plot_image(render_title(dragon_D50, "OG Image", | |
| 51 | #' title_color = "white", title_size = 12)) | |
| 52 | #' plot_image(render_title(dragon_D75, "Target Image", | |
| 53 | #' title_color = "white", title_size = 12)) | |
| 54 | #' plot_image(render_title(updated_source, "Corrected OG Image", | |
| 55 | #' title_color = "white", title_size = 12)) | |
| 56 | render_color_correction = function( | |
| 57 | image, | |
| 58 | matrix = diag(3), | |
| 59 | filename = NULL, | |
| 60 | preview = FALSE | |
| 61 | ) { | |
| 62 | ! | stopifnot(is.matrix(matrix), all(dim(matrix) == c(3, 3)), is.numeric(matrix)) |
| 63 | ! | src = ray_read_image( |
| 64 | ! | image, |
| 65 | ! | convert_to_array = TRUE, |
| 66 | ! | normalize = FALSE, |
| 67 | ! | reset_camera_settings = TRUE |
| 68 | ) | |
| 69 | ! | imagetype = attr(src, "filetype") |
| 70 | ! | img_source_linear = attr(src, "source_linear") |
| 71 | ! | colorspace = attr(src, "colorspace") |
| 72 | ! | white_current = attr(src, "white_current") |
| 73 | ||
| 74 | ! | if (!isTRUE(attr(src, "source_linear"))) { |
| 75 | ! | warning( |
| 76 | ! | "render_color_correction(): input is not linear; convert with render_gamma_linear(..., TRUE) first." |
| 77 | ) | |
| 78 | } | |
| 79 | ! | d = dim(src) |
| 80 | ! | if (length(d) != 3L) { |
| 81 | ! | return(src) |
| 82 | } | |
| 83 | ! | out = apply_color_matrix(src, matrix) |
| 84 | ! | out[,, 1:3][out[,, 1:3] < 0] = 0 |
| 85 | ! | out = ray_read_image( |
| 86 | ! | out, |
| 87 | ! | filetype = imagetype, |
| 88 | ! | source_linear = img_source_linear, |
| 89 | ! | assume_colorspace = colorspace, |
| 90 | ! | assume_white = white_current |
| 91 | ) | |
| 92 | ! | handle_image_output(out, filename = filename, preview = preview) |
| 93 | } |
| 1 | #' @title Generate Text Image | |
| 2 | #' | |
| 3 | #' @description Generates an image which tightly fits text. | |
| 4 | #' | |
| 5 | #' @param text Text to turn into an image. | |
| 6 | #' @param color Default `"black"`. String specifying the color of the text. | |
| 7 | #' @param size Default `12`. Numeric value specifying the font size of the text. | |
| 8 | #' @param font Default `"sans"`. String specifying the font family for the text. | |
| 9 | #' Common options include `"sans"`, `"mono"`, `"serif"`, `"Times"`, `"Helvetica"`, etc. | |
| 10 | #' @param just Default `"left"`. Horizontal alignment of the text: `"left"`, | |
| 11 | #' `"center"`, or `"right"`. | |
| 12 | #' @param lineheight Default `1`. Multiplier for the lineheight. | |
| 13 | #' @param background_color Default `"white"`. Color of the background. | |
| 14 | #' @param background_alpha Default `1`. Transparency of the background. A value | |
| 15 | #' between `0` (fully transparent) and `1` (fully opaque). | |
| 16 | #' @param use_ragg Default `TRUE`. Whether to use the `ragg` package as the graphics device. Required for emojis. | |
| 17 | #' @param width Default `NA`. User-defined textbox width. | |
| 18 | #' @param height Default `NA`. User-defined textbox height. | |
| 19 | #' @param check_text_width Default `TRUE`. Whether to manually adjust the bounding | |
| 20 | #' box of the resulting image to ensure the string bbox is wide enough for the text. | |
| 21 | #' Not all systems provide accurate font sizes: this ensures the string is not cut off | |
| 22 | #' at the edges, at the cost of needing to repeatedly render the image internally until | |
| 23 | #' a suitable image is found. | |
| 24 | #' @param check_text_height Default `FALSE`. Whether to manually adjust the bounding | |
| 25 | #' box of the resulting image to ensure the string bbox is tall enough for the text. | |
| 26 | #' This will ensure a tight vertical bounding box on the text. | |
| 27 | #' @param trim Default `FALSE`. If `TRUE`, post-process the rendered image by | |
| 28 | #' cropping it to the tight bounding box of the text or emoji pixels. The | |
| 29 | #' bounding box is measured from a transparent text mask, so this can also trim | |
| 30 | #' images with opaque backgrounds. | |
| 31 | #' @param trim_padding Default `0`. Padding in pixels to add after trimming. Use | |
| 32 | #' a scalar for equal padding on all sides, or `c(top, right, bottom, left)`. | |
| 33 | #' Nonzero padding implies `trim = TRUE`. | |
| 34 | #' @param filename Default `NULL`. String specifying the file path to save the resulting image. | |
| 35 | #' If `NULL` and `preview = FALSE`, the function returns the processed RGB array. | |
| 36 | #' @param preview Default `FALSE`. Boolean indicating whether to display the image after processing. | |
| 37 | #' If `TRUE`, the image is displayed but not saved or returned. | |
| 38 | #' | |
| 39 | #' @return A 3-layer RGB array of the processed image if `filename = NULL` and `preview = FALSE`. | |
| 40 | #' Otherwise, writes the image to the specified file or displays it if `preview = TRUE`. | |
| 41 | #' | |
| 42 | #' | |
| 43 | #' @import grDevices grid | |
| 44 | #' @export | |
| 45 | #' | |
| 46 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 47 | #' #Generate an image of some text | |
| 48 | #' render_text_image("Some text", preview = TRUE) | |
| 49 | #' #Change the font size | |
| 50 | #' render_text_image("Some text", size = 100, preview = TRUE) | |
| 51 | #' #Change the font color | |
| 52 | #' render_text_image("Some text", size = 100, color="red",preview = TRUE) | |
| 53 | #' #Change the background color and transparency | |
| 54 | #' render_text_image("Some text", size = 50, color="purple", | |
| 55 | #' background_color="purple", background_alpha = 0.5, | |
| 56 | #' preview = TRUE) | |
| 57 | #' # Plot an emoji with the agg device. | |
| 58 | #' render_text_image("\U0001F600\U0001F680", size = 50, color = "purple", use_ragg = TRUE, | |
| 59 | #' background_alpha = 0, | |
| 60 | #' preview = TRUE) | |
| 61 | #' | |
| 62 | #' # Plot an emoji with the agg device and adjust the height and width (which | |
| 63 | #' # is on by default) to be a tight fit. | |
| 64 | #' render_text_image("\U0001F600\U0001F680", size = 50, color = "purple", use_ragg = TRUE, | |
| 65 | #' background_alpha = 0, check_text_width = TRUE, | |
| 66 | #' check_text_height = TRUE, | |
| 67 | #' preview = TRUE) | |
| 68 | #' | |
| 69 | #' # Trim the image to the rendered glyphs and then add transparent padding. | |
| 70 | #' render_text_image("\U0001F409", size = 80, use_ragg = TRUE, | |
| 71 | #' background_alpha = 0, trim = TRUE, trim_padding = 8, | |
| 72 | #' preview = TRUE) | |
| 73 | render_text_image = function( | |
| 74 | text, | |
| 75 | lineheight = 1, | |
| 76 | color = "black", | |
| 77 | size = 12, | |
| 78 | font = "sans", | |
| 79 | just = "left", | |
| 80 | background_color = "white", | |
| 81 | background_alpha = 1, | |
| 82 | use_ragg = TRUE, | |
| 83 | width = NA, | |
| 84 | height = NA, | |
| 85 | filename = NULL, | |
| 86 | check_text_width = TRUE, | |
| 87 | check_text_height = TRUE, | |
| 88 | trim = FALSE, | |
| 89 | trim_padding = 0, | |
| 90 | preview = FALSE | |
| 91 | ) { | |
| 92 | 13x | if (!is.logical(trim) || length(trim) != 1 || is.na(trim)) { |
| 93 | ! | stop("`trim` must be `TRUE` or `FALSE`.") |
| 94 | } | |
| 95 | 13x | trim_padding = normalize_render_padding(trim_padding) |
| 96 | 13x | trim_padding_values = unname(trim_padding) |
| 97 | 13x | if (any(trim_padding_values > 0)) { |
| 98 | 2x | trim = TRUE |
| 99 | } | |
| 100 | 13x | text_metrics = systemfonts::shape_string( |
| 101 | 13x | text, |
| 102 | 13x | size = size, |
| 103 | 13x | vjust = 0.5, |
| 104 | 13x | res = 72, |
| 105 | 13x | lineheight = lineheight, |
| 106 | 13x | family = font |
| 107 | 13x | )[["metrics"]] |
| 108 | 13x | bg_col = convert_color(background_color, as_hex = TRUE) |
| 109 | 13x | metrics_string = systemfonts::string_metrics_dev( |
| 110 | 13x | text, |
| 111 | 13x | unit = "inches", |
| 112 | 13x | size = size |
| 113 | ) * | |
| 114 | 13x | 72 |
| 115 | 13x | max_total_width = ceiling(metrics_string$width) + 2 |
| 116 | 13x | max_total_height = ceiling(text_metrics$height) |
| 117 | 13x | n_newlines = sum(strsplit(text, "") == "\n") |
| 118 | 13x | if (!is.na(width)) { |
| 119 | 4x | max_total_width = width |
| 120 | } | |
| 121 | 13x | if (!is.na(height)) { |
| 122 | 4x | max_total_height = height |
| 123 | } | |
| 124 | 13x | final_array = array( |
| 125 | 13x | 1, |
| 126 | 13x | dim = c( |
| 127 | 13x | max_total_height, |
| 128 | 13x | max_total_width, |
| 129 | 13x | 4 |
| 130 | ) | |
| 131 | ) | |
| 132 | 13x | temp_filename = tempfile(fileext = ".png") |
| 133 | 13x | ray_write_image(final_array, temp_filename) |
| 134 | ||
| 135 | 13x | temp_image = png::readPNG(temp_filename) |
| 136 | 13x | image_width = ncol(temp_image) |
| 137 | 13x | image_height = nrow(temp_image) |
| 138 | ||
| 139 | 13x | render_text_alpha_mask = function(image_width, image_height) { |
| 140 | 29x | png_device = linear_png_device(use_ragg = use_ragg) |
| 141 | 29x | png_device( |
| 142 | 29x | temp_filename, |
| 143 | 29x | width = image_width, |
| 144 | 29x | height = image_height, |
| 145 | 29x | units = "px", |
| 146 | 29x | pointsize = size, |
| 147 | 29x | family = font, |
| 148 | 29x | res = 72, |
| 149 | 29x | bg = NA |
| 150 | ) | |
| 151 | 29x | dev_id = grDevices::dev.cur() |
| 152 | 29x | close_device = function() { |
| 153 | 58x | devs = grDevices::dev.list() |
| 154 | 58x | if (!is.null(devs) && dev_id %in% devs) { |
| 155 | 29x | grDevices::dev.off(which = dev_id) |
| 156 | } | |
| 157 | } | |
| 158 | 29x | on.exit(close_device(), add = TRUE) |
| 159 | ||
| 160 | #First write with no background | |
| 161 | 29x | grid::grid.newpage() |
| 162 | 29x | grid::grid.rect( |
| 163 | 29x | x = 0.5, |
| 164 | 29x | y = 0.5, |
| 165 | 29x | width = 1, |
| 166 | 29x | height = 1, |
| 167 | 29x | just = c("center"), |
| 168 | 29x | default.units = "npc", |
| 169 | 29x | gp = grid::gpar( |
| 170 | 29x | fill = grDevices::adjustcolor("black", alpha.f = 0), |
| 171 | 29x | col = NA |
| 172 | ) | |
| 173 | ) | |
| 174 | 29x | grid::grid.text( |
| 175 | 29x | label = text, |
| 176 | 29x | x = 0.5, |
| 177 | 29x | y = 0.5, |
| 178 | 29x | default.units = "npc", |
| 179 | 29x | just = c("center", "center"), |
| 180 | 29x | gp = grid::gpar( |
| 181 | 29x | fontsize = size, |
| 182 | 29x | lineheight = lineheight, |
| 183 | 29x | cex = 1, |
| 184 | 29x | col = "black", |
| 185 | 29x | fontfamily = font |
| 186 | ) | |
| 187 | ) | |
| 188 | 29x | close_device() |
| 189 | 29x | temp = png::readPNG(temp_filename) |
| 190 | 29x | temp[,, 4] |
| 191 | } | |
| 192 | ||
| 193 | 13x | test_edges = function(image_width, image_height) { |
| 194 | 17x | text_alpha = render_text_alpha_mask(image_width, image_height) |
| 195 | 17x | side_edges = text_alpha[c(1, nrow(text_alpha)), ] |
| 196 | 17x | vert_edges = text_alpha[, c(1, ncol(text_alpha))] |
| 197 | 17x | return(c(any(vert_edges > 0), any(side_edges > 0))) |
| 198 | } | |
| 199 | ||
| 200 | #First write with no background | |
| 201 | 13x | if (check_text_width || check_text_height) { |
| 202 | 9x | test_edge_vec = test_edges(image_width, image_height) |
| 203 | 9x | if (!check_text_height) { |
| 204 | ! | test_edge_vec[2] = FALSE |
| 205 | } | |
| 206 | 9x | if (!check_text_width) { |
| 207 | ! | test_edge_vec[1] = FALSE |
| 208 | } | |
| 209 | 17x | while (any(test_edge_vec)) { |
| 210 | 8x | if (test_edge_vec[1]) { |
| 211 | 8x | image_width = image_width * 2 |
| 212 | } | |
| 213 | 8x | if (check_text_height) { |
| 214 | 8x | if (test_edge_vec[2]) { |
| 215 | ! | image_height = image_height * 2 |
| 216 | } | |
| 217 | } | |
| 218 | 8x | test_edge_vec = test_edges(image_width, image_height) |
| 219 | } | |
| 220 | ||
| 221 | 9x | temp = png::readPNG(temp_filename) |
| 222 | 9x | stopifnot(any(temp[,, 4] != 0)) |
| 223 | ||
| 224 | 9x | vert_bbox = range(which(apply(temp[,, 4], 1, sum) != 0)) |
| 225 | 9x | hori_bbox = range(which(apply(temp[,, 4], 2, sum) != 0)) |
| 226 | ||
| 227 | 9x | vert_blank = (vert_bbox[1] - 1) + (image_height - vert_bbox[2]) |
| 228 | 9x | hori_blank = (hori_bbox[1] - 1) + (image_width - hori_bbox[2]) |
| 229 | 9x | if (check_text_height) { |
| 230 | 9x | image_height = image_height - vert_blank + size |
| 231 | } | |
| 232 | 9x | image_width = image_width - hori_blank + size |
| 233 | } | |
| 234 | ||
| 235 | #If no edges, proceed with normal render | |
| 236 | 13x | png_device = linear_png_device(use_ragg = use_ragg) |
| 237 | 13x | png_device( |
| 238 | 13x | temp_filename, |
| 239 | 13x | width = image_width, |
| 240 | 13x | height = image_height, |
| 241 | 13x | units = "px", |
| 242 | 13x | pointsize = size, |
| 243 | 13x | family = font, |
| 244 | 13x | res = 72, |
| 245 | 13x | bg = NA |
| 246 | ) | |
| 247 | ||
| 248 | 13x | dev_id = grDevices::dev.cur() |
| 249 | 13x | grid::grid.newpage() |
| 250 | 13x | grid::grid.rect( |
| 251 | 13x | x = 0.5, |
| 252 | 13x | y = 0.5, |
| 253 | 13x | width = 1, |
| 254 | 13x | height = 1, |
| 255 | 13x | just = c("center"), |
| 256 | 13x | default.units = "npc", |
| 257 | 13x | gp = grid::gpar( |
| 258 | 13x | fill = grDevices::adjustcolor(bg_col, alpha.f = background_alpha), |
| 259 | 13x | col = NA |
| 260 | ) | |
| 261 | ) | |
| 262 | ||
| 263 | 13x | grid::grid.text( |
| 264 | 13x | label = text, |
| 265 | 13x | x = 0.5, |
| 266 | 13x | y = 0.5, |
| 267 | 13x | default.units = "npc", |
| 268 | 13x | just = c("center", "center"), |
| 269 | 13x | gp = grid::gpar( |
| 270 | 13x | fontsize = size, |
| 271 | 13x | lineheight = lineheight, |
| 272 | 13x | cex = 1, |
| 273 | 13x | col = convert_color(color, as_hex = TRUE), |
| 274 | 13x | fontfamily = font |
| 275 | ) | |
| 276 | ) | |
| 277 | 13x | grDevices::dev.off(which = dev_id) |
| 278 | ||
| 279 | 13x | temp = ray_read_image(temp_filename, reset_camera_settings = TRUE) |
| 280 | 13x | if (trim) { |
| 281 | 12x | text_alpha = render_text_alpha_mask(image_width, image_height) |
| 282 | 12x | text_rows = which(rowSums(text_alpha > 0) > 0) |
| 283 | 12x | text_cols = which(colSums(text_alpha > 0) > 0) |
| 284 | 12x | if (length(text_rows) > 0 && length(text_cols) > 0) { |
| 285 | 12x | temp = temp[ |
| 286 | 12x | min(text_rows):max(text_rows), |
| 287 | 12x | min(text_cols):max(text_cols), |
| 288 | , | |
| 289 | 12x | drop = FALSE |
| 290 | ] | |
| 291 | } | |
| 292 | } | |
| 293 | 13x | if (any(trim_padding_values > 0)) { |
| 294 | 2x | temp = render_padding( |
| 295 | 2x | temp, |
| 296 | 2x | pad = trim_padding, |
| 297 | 2x | color = background_color, |
| 298 | 2x | alpha = background_alpha, |
| 299 | 2x | preview = FALSE |
| 300 | ) | |
| 301 | } | |
| 302 | ||
| 303 | 13x | handle_image_output(temp, filename = filename, preview = preview) |
| 304 | } |
| 1 | #'@title Render Boolean Distance | |
| 2 | #' | |
| 3 | #'@description Takes a logical matrix and returns the nearest distance to each TRUE value. | |
| 4 | #' | |
| 5 | #'@param boolean Logical matrix (or matrix of 1s and 0s), where distance will be measured to the `TRUE` values. | |
| 6 | #'@param rescale Default `FALSE`. Rescales the calculated distance to a range of 0-1. | |
| 7 | #'Useful for visualizing the distance matrix. | |
| 8 | #'@return Matrix of distance values. | |
| 9 | #'@export | |
| 10 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 11 | #'#Measure distance to | |
| 12 | #'plot_image(render_boolean_distance(t(volcano) > 150)) | |
| 13 | #'plot_image(render_boolean_distance(t(volcano) < 150)) | |
| 14 | #'#If we want to rescale this to zero to one (to visualize like an image), set rescale=TRUE | |
| 15 | #'plot_image(render_boolean_distance(t(volcano) > 150,rescale=TRUE)) | |
| 16 | render_boolean_distance = function(boolean, rescale = FALSE) { | |
| 17 | 7x | if (any(is.na(boolean))) { |
| 18 | ! | stop("`boolean` must not have any NA values") |
| 19 | } | |
| 20 | 7x | distval = get_boolean_distance(boolean) |
| 21 | 7x | if (rescale) { |
| 22 | ! | if (min(distval) != max(distval)) { |
| 23 | ! | distval = (distval - min(distval)) / (max(distval) - min(distval)) |
| 24 | } | |
| 25 | ! | return(distval) |
| 26 | } else { | |
| 27 | 7x | return(distval) |
| 28 | } | |
| 29 | } |
| 1 | #'@title Render Bokeh | |
| 2 | #' | |
| 3 | #'@description Takes an image and a depth map to render the image with depth of field | |
| 4 | #'(i.e. similar to "Portrait Mode" in an iPhone). User can specify a custom bokeh shape, | |
| 5 | #'or use one of the built-in bokeh types. | |
| 6 | #' | |
| 7 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 8 | #'@param depthmap Depth map filename or 1d array. | |
| 9 | #'@param focus Defaults `0.5`. Depth in which to blur. | |
| 10 | #'@param focallength Default `100`. Focal length of the virtual camera. | |
| 11 | #'@param fstop Default `4`. F-stop of the virtual camera. | |
| 12 | #'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead. | |
| 13 | #'@param preview Default `TRUE`. If `FALSE`, it will not display the image and just return the RGB array. | |
| 14 | #'@param preview_focus Default `FALSE`. If `TRUE`, a red line will be drawn across the image | |
| 15 | #'showing where the camera will be focused. | |
| 16 | #'@param bokehshape Default `circle`. Also built-in: `hex`. The shape of the bokeh. If the user | |
| 17 | #'passes in a 2D matrix, that matrix will control the shape of the bokeh. | |
| 18 | #'@param bokehintensity Default `1`. Intensity of the bokeh when the pixel intensity is greater than `bokehlimit`. | |
| 19 | #'@param bokehlimit Default `0.8`. Limit after which the bokeh intensity is increased by `bokehintensity`. | |
| 20 | #'@param rotation Default `0`. Number of degrees to rotate the hexagonal bokeh shape. | |
| 21 | #'@param aberration Default `0`. Adds chromatic aberration to the image. Maximum of `1`. | |
| 22 | #'@param progress Default `TRUE`. Whether to display a progress bar. | |
| 23 | #'@param ... Additional arguments to pass to [plot_image()] if `preview = TRUE`. | |
| 24 | #'@return A `rayimg` RGBA array. | |
| 25 | #'@export | |
| 26 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 27 | #'#Plot the dragon | |
| 28 | #'plot_image(dragon) | |
| 29 | #'#Plot the depth map | |
| 30 | #' plot_image(dragondepth/1500) | |
| 31 | #'#Preview the focal plane: | |
| 32 | #'render_bokeh(dragon, dragondepth, focus=950, preview_focus = TRUE) | |
| 33 | #'#Change the focal length: | |
| 34 | #'render_bokeh(dragon, dragondepth, focus=950, focallength=300) | |
| 35 | #'#Add chromatic aberration: | |
| 36 | #'render_bokeh(dragon, dragondepth, focus=950, focallength=300, aberration = 0.5) | |
| 37 | #'#Change the focal distance: | |
| 38 | #'render_bokeh(dragon, dragondepth, focus=600, focallength=300) | |
| 39 | #'render_bokeh(dragon, dragondepth, focus=1300, focallength=300) | |
| 40 | #'#Change the bokeh shape to a hexagon: | |
| 41 | #'render_bokeh(dragon, dragondepth, bokehshape = "hex", | |
| 42 | #' focallength=300, focus=600) | |
| 43 | #'#Change the bokeh intensity: | |
| 44 | #'render_bokeh(dragon, dragondepth, | |
| 45 | #' focallength=400, focus=900, bokehintensity = 1) | |
| 46 | #'render_bokeh(dragon, dragondepth, | |
| 47 | #' focallength=400, focus=900, bokehintensity = 3) | |
| 48 | #'#Rotate the hexagonal shape: | |
| 49 | #'render_bokeh(dragon, dragondepth, bokehshape = "hex", rotation=15, bokehintensity=3, | |
| 50 | #' focallength=400, focus=800) | |
| 51 | render_bokeh = function( | |
| 52 | image, | |
| 53 | depthmap, | |
| 54 | focus = 0.5, | |
| 55 | focallength = 100, | |
| 56 | fstop = 4, | |
| 57 | filename = NULL, | |
| 58 | preview = TRUE, | |
| 59 | preview_focus = FALSE, | |
| 60 | bokehshape = "circle", | |
| 61 | bokehintensity = 1, | |
| 62 | bokehlimit = 0.8, | |
| 63 | rotation = 0, | |
| 64 | aberration = 0, | |
| 65 | progress = interactive(), | |
| 66 | ... | |
| 67 | ) { | |
| 68 | ! | temp_image = ray_read_image(image, reset_camera_settings = TRUE) #Always output RGBA array |
| 69 | #Check if file or image before below: | |
| 70 | ! | imagetype = attr(temp_image, "filetype") |
| 71 | ||
| 72 | ! | depthmap = ray_read_image( |
| 73 | ! | depthmap, |
| 74 | ! | convert_to_array = FALSE, |
| 75 | ! | reset_camera_settings = TRUE |
| 76 | ) | |
| 77 | ! | depthtype = attr(depthmap, "filetype") |
| 78 | ||
| 79 | ! | if (preview_focus) { |
| 80 | ! | preview_focus(image, depthmap, focus, imagetype, depthtype) |
| 81 | ! | return(invisible()) |
| 82 | } | |
| 83 | ! | if (is.matrix(bokehshape)) { |
| 84 | ! | custombokeh = bokehshape |
| 85 | ! | bokehshape = 2L |
| 86 | } else { | |
| 87 | ! | if (bokehshape == "circle") { |
| 88 | ! | bokehshape = 0L |
| 89 | } else { | |
| 90 | ! | bokehshape = 1L |
| 91 | } | |
| 92 | ! | custombokeh = matrix(1, 1, 1) |
| 93 | } | |
| 94 | ! | if (aberration >= 1 || aberration <= -1) { |
| 95 | ! | stop("aberration value must be less than 1 and greater than -1") |
| 96 | } | |
| 97 | ||
| 98 | ! | if (length(dim(depthmap)) == 3) { |
| 99 | ! | depthmap = depthmap[,, 1] |
| 100 | } | |
| 101 | ||
| 102 | ! | depthmap[is.na(depthmap)] = max(depthmap, na.rm = TRUE) * 2 |
| 103 | ||
| 104 | ! | for (i in 1:3) { |
| 105 | ! | max_size = min(c(max(dim(depthmap)), 500)) |
| 106 | ! | if (i == 1) { |
| 107 | ! | depthmap2 = calc_bokeh_size( |
| 108 | ! | depthmap, |
| 109 | ! | focus, |
| 110 | ! | focallength, |
| 111 | ! | fstop, |
| 112 | ! | 1 + aberration |
| 113 | ) | |
| 114 | ! | } else if (i == 2) { |
| 115 | ! | depthmap2 = calc_bokeh_size(depthmap, focus, focallength, fstop, 1) |
| 116 | } else { | |
| 117 | ! | depthmap2 = calc_bokeh_size( |
| 118 | ! | depthmap, |
| 119 | ! | focus, |
| 120 | ! | focallength, |
| 121 | ! | fstop, |
| 122 | ! | 1 - aberration |
| 123 | ) | |
| 124 | } | |
| 125 | ! | if (any(dim(depthmap2)[1:2] != dim(temp_image)[1:2])) { |
| 126 | ! | stop(sprintf( |
| 127 | ! | "{rayimage}: dimensions of image (%ix%i) and depth map (%ix%i) don't match", |
| 128 | ! | dim(temp_image)[1], |
| 129 | ! | dim(temp_image)[2], |
| 130 | ! | dim(depthmap2)[1], |
| 131 | ! | dim(depthmap2)[2] |
| 132 | )) | |
| 133 | } | |
| 134 | ! | depthmap2[depthmap2 > max_size] = max_size |
| 135 | ! | temp_image[,, i] = psf( |
| 136 | ! | temp_image[,, i], |
| 137 | ! | depthmap2, |
| 138 | ! | depthmap, |
| 139 | ! | focus, |
| 140 | ! | bokehshape, |
| 141 | ! | custombokeh = custombokeh, |
| 142 | ! | bokehintensity, |
| 143 | ! | bokehlimit, |
| 144 | ! | rotation, |
| 145 | ! | progbar = progress, |
| 146 | ! | channel = i |
| 147 | ) | |
| 148 | } | |
| 149 | ! | handle_image_output(temp_image, filename = filename, preview = preview) |
| 150 | } |
| 1 | #' @title Build RGB-to-XYZ matrices from primaries + white | |
| 2 | #' @param primaries Default `list(r=c(0.713,0.293), g=c(0.165,0.830), b=c(0.128,0.044))`. xy chromaticities (AP1). | |
| 3 | #' @param white_xy Default `c(0.32168,0.33767)`. White xy (D60). | |
| 4 | #' @return List with 3x3 numeric matrices: `rgb_to_xyz`, `xyz_to_rgb`. | |
| 5 | #' @keywords internal | |
| 6 | make_rgb_xyz_matrices = function( | |
| 7 | primaries = list( | |
| 8 | r = c(0.713, 0.293), | |
| 9 | g = c(0.165, 0.830), | |
| 10 | b = c(0.128, 0.044) | |
| 11 | ), | |
| 12 | white_xy = c(0.32168, 0.33767) # D60 | |
| 13 | ) { | |
| 14 | 2x | xy_to_XYZ = function(xy) c(xy[1] / xy[2], 1, (1 - xy[1] - xy[2]) / xy[2]) |
| 15 | 2x | Xr = xy_to_XYZ(primaries$r) |
| 16 | 2x | Xg = xy_to_XYZ(primaries$g) |
| 17 | 2x | Xb = xy_to_XYZ(primaries$b) |
| 18 | 2x | M = cbind(Xr, Xg, Xb) |
| 19 | 2x | W = xy_to_XYZ(white_xy) |
| 20 | 2x | S = solve(M, W) |
| 21 | 2x | rgb_to_xyz = M %*% diag(S) |
| 22 | 2x | xyz_to_rgb = solve(rgb_to_xyz) |
| 23 | 2x | list(rgb_to_xyz = rgb_to_xyz, xyz_to_rgb = xyz_to_rgb) |
| 24 | } | |
| 25 | ||
| 26 | #' @title Build a colorspace descriptor | |
| 27 | #' @param name Default `"ACEScg"`. | |
| 28 | #' @param primaries Default AP1. | |
| 29 | #' @param white_xy Default D60. | |
| 30 | #' @return list(name, rgb_to_xyz, xyz_to_rgb, white_xyz, white_name) | |
| 31 | #' @keywords internal | |
| 32 | make_colorspace = function( | |
| 33 | name = "ACEScg", | |
| 34 | primaries = list( | |
| 35 | r = c(0.713, 0.293), | |
| 36 | g = c(0.165, 0.830), | |
| 37 | b = c(0.128, 0.044) | |
| 38 | ), | |
| 39 | white_xy = c(0.32168, 0.33767), # D60 | |
| 40 | white_name = "D60" | |
| 41 | ) { | |
| 42 | 2x | mats = make_rgb_xyz_matrices(primaries = primaries, white_xy = white_xy) |
| 43 | 2x | xy_to_XYZ = function(xy) c(xy[1] / xy[2], 1, (1 - xy[1] - xy[2]) / xy[2]) |
| 44 | 2x | list( |
| 45 | 2x | name = name, |
| 46 | 2x | primaries = primaries, |
| 47 | 2x | rgb_to_xyz = mats$rgb_to_xyz, |
| 48 | 2x | xyz_to_rgb = mats$xyz_to_rgb, |
| 49 | 2x | white_xyz = xy_to_XYZ(white_xy), |
| 50 | 2x | white_name = white_name |
| 51 | ) | |
| 52 | } | |
| 53 | ||
| 54 | #' Prebuilt RGB Working/Display Color Spaces | |
| 55 | #' | |
| 56 | #' @title Prebuilt RGB Working/Display Color Spaces | |
| 57 | #' | |
| 58 | #' @description | |
| 59 | #' These objects are **color space descriptors** used by `rayimage` to tag images | |
| 60 | #' and to convert between RGB spaces. Each descriptor is a named list with: | |
| 61 | #' | |
| 62 | #' - `name`: Character. Human-readable name of the space. | |
| 63 | #' - `primaries`: List with `r`, `g`, `b` entries giving xy chromaticities. | |
| 64 | #' - `rgb_to_xyz`: 3x3 numeric matrix (linear RGB -> CIE XYZ, Y=1 white). | |
| 65 | #' - `xyz_to_rgb`: 3x3 numeric matrix (CIE XYZ -> linear RGB). | |
| 66 | #' - `white_xyz`: Length-3 numeric XYZ of the reference white (normalized s.t. Y = 1). | |
| 67 | #' - `white_name`: Character label for the white (e.g., `"D60"`, `"D65"`). | |
| 68 | #' | |
| 69 | #' These are used as: | |
| 70 | #' - `attr(img, "colorspace")`: the current working/display space for an image. | |
| 71 | #' - `attr(img, "white_current")`: the current assumed scene/display white (XYZ, Y=1). | |
| 72 | #' | |
| 73 | #' @details | |
| 74 | #' - **CS_ACESCG**: ACEScg (AP1 primaries, D60, scene-linear). Recommended working space. | |
| 75 | #' - **CS_SRGB**: sRGB/Rec.709 (D65). Typical display space; used for PNG/JPEG/TIFF output. | |
| 76 | #' - **CS_P3D65**: Display P3 (D65). Wide-gamut display space. | |
| 77 | #' - **CS_BT2020**: BT.2020 (D65). Very wide-gamut; common for HDR mastering. | |
| 78 | #' - **CS_ADOBE**: Adobe RGB (D65). Photo workflows. | |
| 79 | #' | |
| 80 | #' @seealso | |
| 81 | #' - [render_convert_colorspace()] to convert images between spaces. | |
| 82 | #' - [render_white_balance()] for Bradford CAT within a working space. | |
| 83 | #' - [plot_image()], [ray_write_image()] for display/output conversion. | |
| 84 | #' | |
| 85 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 86 | #' # Tag a raw array as sRGB, then convert to ACEScg: | |
| 87 | #' arr = array(runif(64*64*4), dim = c(64, 64, 4)) | |
| 88 | #' ri = ray_read_image(arr, assume_colorspace = CS_SRGB, assume_white = CS_SRGB$white_xyz) | |
| 89 | #' riA = render_convert_colorspace(ri, to_mats = CS_ACESCG) | |
| 90 | #' plot_image(riA) # display-converted to sRGB automatically | |
| 91 | #' | |
| 92 | #' # Convert an sRGB JPEG to ACEScg on ingest: | |
| 93 | #' # img = ray_read_image("photo.jpg", normalize = FALSE) | |
| 94 | #' # img_aces = render_convert_colorspace(img, to_mats = CS_ACESCG) | |
| 95 | #' | |
| 96 | #' @name colorspace_descriptors | |
| 97 | NULL | |
| 98 | ||
| 99 | #' @rdname colorspace_descriptors | |
| 100 | #' @export | |
| 101 | CS_ACESCG = make_colorspace( | |
| 102 | name = "ACEScg", | |
| 103 | primaries = list( | |
| 104 | r = c(0.713, 0.293), | |
| 105 | g = c(0.165, 0.830), | |
| 106 | b = c(0.128, 0.044) | |
| 107 | ), | |
| 108 | white_xy = c(0.32168, 0.33767), # D60 | |
| 109 | white_name = "D60" | |
| 110 | ) | |
| 111 | ||
| 112 | #' @rdname colorspace_descriptors | |
| 113 | #' @export | |
| 114 | CS_SRGB = make_colorspace( | |
| 115 | name = "sRGB", | |
| 116 | primaries = list( | |
| 117 | r = c(0.64, 0.33), | |
| 118 | g = c(0.30, 0.60), | |
| 119 | b = c(0.15, 0.06) | |
| 120 | ), | |
| 121 | white_xy = c(0.3127, 0.3290), # D65 | |
| 122 | white_name = "D65" | |
| 123 | ) | |
| 124 | ||
| 125 | #' @rdname colorspace_descriptors | |
| 126 | #' @export | |
| 127 | CS_P3D65 = make_colorspace( | |
| 128 | name = "P3-D65", | |
| 129 | primaries = list( | |
| 130 | r = c(0.680, 0.320), | |
| 131 | g = c(0.265, 0.690), | |
| 132 | b = c(0.150, 0.060) | |
| 133 | ), | |
| 134 | white_xy = c(0.3127, 0.3290), # D65 | |
| 135 | white_name = "D65" | |
| 136 | ) | |
| 137 | ||
| 138 | #' @rdname colorspace_descriptors | |
| 139 | #' @export | |
| 140 | CS_BT2020 = make_colorspace( | |
| 141 | name = "BT.2020", | |
| 142 | primaries = list( | |
| 143 | r = c(0.708, 0.292), | |
| 144 | g = c(0.170, 0.797), | |
| 145 | b = c(0.131, 0.046) | |
| 146 | ), | |
| 147 | white_xy = c(0.3127, 0.3290), # D65 | |
| 148 | white_name = "D65" | |
| 149 | ) | |
| 150 | ||
| 151 | #' @rdname colorspace_descriptors | |
| 152 | #' @export | |
| 153 | CS_ADOBE = make_colorspace( | |
| 154 | name = "AdobeRGB", | |
| 155 | primaries = list( | |
| 156 | r = c(0.64, 0.33), | |
| 157 | g = c(0.21, 0.71), | |
| 158 | b = c(0.15, 0.06) | |
| 159 | ), | |
| 160 | white_xy = c(0.3127, 0.3290), # D65 | |
| 161 | white_name = "D65" | |
| 162 | ) |
| 1 | #'@title Plot Native Raster with Custom Aspect Ratio | |
| 2 | #' | |
| 3 | #'@keywords internal | |
| 4 | plot_asp_native_raster = function( | |
| 5 | nr, | |
| 6 | asp = 1, | |
| 7 | show = FALSE, | |
| 8 | return_grob = FALSE, | |
| 9 | gp = grid::gpar(), | |
| 10 | angle = 0 | |
| 11 | ) { | |
| 12 | 36x | stopifnot(asp > 0) |
| 13 | 36x | native_dim = dim(nr) |
| 14 | 36x | image_width = native_dim[2] |
| 15 | 36x | image_height = native_dim[1] |
| 16 | 36x | asp = asp * image_width / image_height |
| 17 | 36x | if (asp > 1) { |
| 18 | ! | gl = grid::grid.layout( |
| 19 | ! | 1, |
| 20 | ! | 1, |
| 21 | ! | widths = grid::unit(1, "null"), |
| 22 | ! | heights = grid::unit(1 / asp, "null"), |
| 23 | ! | respect = TRUE |
| 24 | ) | |
| 25 | } else { | |
| 26 | 36x | gl = grid::grid.layout( |
| 27 | 36x | 1, |
| 28 | 36x | 1, |
| 29 | 36x | widths = grid::unit(1 * asp, "null"), |
| 30 | 36x | heights = grid::unit(1, "null"), |
| 31 | 36x | respect = TRUE |
| 32 | ) | |
| 33 | } | |
| 34 | ||
| 35 | 36x | needs_rotation = !isTRUE(all.equal(angle %% 360, 0)) |
| 36 | 36x | clip_setting = if (needs_rotation) "off" else "inherit" |
| 37 | ||
| 38 | 36x | top.vp = grid::viewport( |
| 39 | 36x | layout = gl, |
| 40 | 36x | name = "grid_asp_container", |
| 41 | 36x | clip = clip_setting |
| 42 | ) | |
| 43 | 36x | image_vp = grid::viewport( |
| 44 | 36x | name = "image", |
| 45 | 36x | layout.pos.col = 1, |
| 46 | 36x | layout.pos.row = 1, |
| 47 | 36x | xscale = c(0, image_width), |
| 48 | 36x | yscale = c(image_height, 0), |
| 49 | 36x | gp = gp, |
| 50 | 36x | clip = clip_setting |
| 51 | ) | |
| 52 | ||
| 53 | 36x | image_grob = grid::rasterGrob( |
| 54 | 36x | nr, |
| 55 | 36x | interpolate = FALSE, |
| 56 | 36x | width = grid::unit(1, "npc"), |
| 57 | 36x | height = grid::unit(1, "npc"), |
| 58 | 36x | gp = gp |
| 59 | ) | |
| 60 | 36x | if (needs_rotation) { |
| 61 | ! | angle_norm = abs(angle) %% 180 |
| 62 | ! | if (angle_norm > 90) { |
| 63 | ! | angle_norm = 180 - angle_norm |
| 64 | } | |
| 65 | ! | angle_rad = angle_norm * pi / 180 |
| 66 | ! | width_rot = image_width * cos(angle_rad) + image_height * sin(angle_rad) |
| 67 | ! | height_rot = image_width * sin(angle_rad) + image_height * cos(angle_rad) |
| 68 | ! | scale_factor = max(width_rot / image_width, height_rot / image_height) |
| 69 | ! | if (!is.finite(scale_factor) || scale_factor <= 0) { |
| 70 | ! | scale_factor = 1 |
| 71 | } | |
| 72 | ! | image_grob = grid::editGrob( |
| 73 | ! | image_grob, |
| 74 | ! | vp = grid::viewport( |
| 75 | ! | angle = angle, |
| 76 | ! | clip = "off", |
| 77 | ! | width = grid::unit(1 / scale_factor, "npc"), |
| 78 | ! | height = grid::unit(1 / scale_factor, "npc") |
| 79 | ) | |
| 80 | ) | |
| 81 | } | |
| 82 | ||
| 83 | 36x | if (return_grob) { |
| 84 | ! | image_tree = grid::gTree( |
| 85 | ! | children = grid::gList(image_grob), |
| 86 | ! | vp = image_vp |
| 87 | ) | |
| 88 | ! | return(grid::gTree( |
| 89 | ! | children = grid::gList(image_tree), |
| 90 | ! | vp = top.vp |
| 91 | )) | |
| 92 | } | |
| 93 | ||
| 94 | 36x | pushed = 0L |
| 95 | 36x | grid::pushViewport(top.vp) |
| 96 | 36x | pushed = pushed + 1L |
| 97 | ||
| 98 | 36x | grid::pushViewport(image_vp) |
| 99 | 36x | pushed = pushed + 1L |
| 100 | ||
| 101 | 36x | on.exit( |
| 102 | { | |
| 103 | 36x | if (pushed > 0L) { |
| 104 | 36x | try(grid::popViewport(pushed), silent = TRUE) |
| 105 | } | |
| 106 | }, | |
| 107 | 36x | add = TRUE |
| 108 | ) | |
| 109 | ||
| 110 | 36x | grid::grid.draw(image_grob) |
| 111 | 36x | invisible() |
| 112 | } |
| 1 | #'@title Generate 2D Gaussian Distribution | |
| 2 | #' | |
| 3 | #'@description Generates a 2D gaussian distribution, with an optional | |
| 4 | #'argument to take the gaussian to a user-defined power. | |
| 5 | #' | |
| 6 | #'@param sd Default `1`. Standard deviation of the normal distribution | |
| 7 | #'@param power Default `1`. Power to take the distribution. Higher values will result in a sharper peak. | |
| 8 | #'@param dim Default `c(11, 11)`. The dimensions of the matrix. | |
| 9 | #'@param width Default `3` (`-10` to `10`). The range in which to compute the distribution. | |
| 10 | #'@param rescale_unity Default `FALSE`. If `TRUE`, this will rescale the max value to one. Useful | |
| 11 | #'if wanting to plot the distribution with [plot_image()]. | |
| 12 | #'@import stats | |
| 13 | #'@export | |
| 14 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 15 | #'image(generate_2d_gaussian(1,1,31), asp=1) | |
| 16 | generate_2d_gaussian = function( | |
| 17 | sd = 1, | |
| 18 | power = 1, | |
| 19 | dim = c(11, 11), | |
| 20 | width = 3, | |
| 21 | rescale_unity = FALSE | |
| 22 | ) { | |
| 23 | ! | if (length(dim) == 1) { |
| 24 | ! | dim = c(dim, dim) |
| 25 | } | |
| 26 | ! | mindim = min(dim) |
| 27 | ! | xy_ratio = dim[1] / dim[2] |
| 28 | ! | if (xy_ratio > 1) { |
| 29 | ! | x = seq(-width * xy_ratio, width * xy_ratio, length.out = dim[1]) |
| 30 | ! | y = seq(-width, width, length.out = dim[2]) |
| 31 | } else { | |
| 32 | ! | x = seq(-width, width, length.out = dim[1]) |
| 33 | ! | y = seq(-width / xy_ratio, width / xy_ratio, length.out = dim[2]) |
| 34 | } | |
| 35 | ! | testmat = matrix(0, length(x), length(y)) |
| 36 | ! | if (sd == 0) { |
| 37 | ! | sd == 0.00001 |
| 38 | } | |
| 39 | ! | if (length(x) > 0 && length(y) > 0) { |
| 40 | ! | for (i in 1:length(x)) { |
| 41 | ! | for (j in 1:length(y)) { |
| 42 | ! | testmat[i, j] = (dnorm(power * x[i], mean = 0, sd = sd) * |
| 43 | ! | dnorm(power * y[j], mean = 0, sd = sd)) |
| 44 | } | |
| 45 | } | |
| 46 | } else { | |
| 47 | ! | stop("Kernel dimension too small") |
| 48 | } | |
| 49 | ! | if (rescale_unity) { |
| 50 | ! | temp = testmat / sum(testmat) |
| 51 | ! | return(temp / max(temp)) |
| 52 | } | |
| 53 | ! | testmat / sum(testmat) |
| 54 | } |
| 1 | #' Flip Left-Right | |
| 2 | #' | |
| 3 | #' @param x Matrix | |
| 4 | #' | |
| 5 | #' @return Flipped matrix | |
| 6 | #' @keywords internal | |
| 7 | #' | |
| 8 | #' @examples | |
| 9 | #' #Fake example | |
| 10 | fliplr = function(x) { | |
| 11 | ! | if (length(dim(x)) == 2) { |
| 12 | ! | x[, ncol(x):1] |
| 13 | } else { | |
| 14 | ! | x[, ncol(x):1, ] |
| 15 | } | |
| 16 | } | |
| 17 | ||
| 18 | ||
| 19 | #' Flip Up-Down | |
| 20 | #' | |
| 21 | #' @param x Matrix | |
| 22 | #' | |
| 23 | #' @return Flipped matrix | |
| 24 | #' @keywords internal | |
| 25 | #' | |
| 26 | #' @examples | |
| 27 | #' #Fake example | |
| 28 | flipud = function(x) { | |
| 29 | ! | if (length(dim(x)) == 2) { |
| 30 | ! | x[nrow(x):1, ] |
| 31 | } else { | |
| 32 | ! | x[nrow(x):1, , ] |
| 33 | } | |
| 34 | } |
| 1 | rgb_to_hex = function(x) { | |
| 2 | if (is.null(dim(x))) { | |
| 3 | x = matrix(x, ncol = length(x), byrow = TRUE) | |
| 4 | } | |
| 5 | if (!(ncol(x) %in% c(3, 4))) { | |
| 6 | stop("rgb_to_hex(): expected 3 or 4 columns (R,G,B[,A]).") | |
| 7 | } | |
| 8 | x = pmin(pmax(x, 0), 1) | |
| 9 | ints = round(x * 255) | |
| 10 | paste0( | |
| 11 | "#", | |
| 12 | apply(ints, 1, function(row) { | |
| 13 | paste(sprintf("%02X", row), collapse = "") | |
| 14 | }) | |
| 15 | ) | |
| 16 | } | |
| 17 | ||
| 18 | #' Convert Color | |
| 19 | #' | |
| 20 | #' @param color The color to convert. Can be either an R color string, or a | |
| 21 | #' numeric scalar, RGB vector, RGBA vector, or RGB/RGBA matrix with values | |
| 22 | #' between `0` and `1`. | |
| 23 | #' @param as_hex Default `FALSE`. If `TRUE`, return hex colors. | |
| 24 | #' @param single Default `FALSE`. If `TRUE`, require exactly one color. | |
| 25 | #' | |
| 26 | #' @return RGB or RGBA color vector, or a color matrix for multiple colors. | |
| 27 | #' @keywords internal | |
| 28 | #' | |
| 29 | #' @examples | |
| 30 | #' #none | |
| 31 | convert_color = function(color, as_hex = FALSE, single = FALSE) { | |
| 32 | 67x | if (is.null(color) || length(color) == 0) { |
| 33 | ! | stop("invalid color") |
| 34 | } | |
| 35 | 67x | if (is.character(color)) { |
| 36 | 58x | color = t(grDevices::col2rgb(color, alpha = TRUE)) / 255 |
| 37 | } else { | |
| 38 | 9x | if (!is.numeric(color)) { |
| 39 | ! | stop("invalid color") |
| 40 | } | |
| 41 | 9x | color_dim = dim(color) |
| 42 | 9x | if (is.null(color_dim)) { |
| 43 | 9x | if (length(color) == 1) { |
| 44 | 1x | color = rep(color, 3) |
| 45 | } | |
| 46 | if ( | |
| 47 | 9x | !(length(color) %in% |
| 48 | 9x | c(3, 4) || |
| 49 | 9x | length(color) %% 3 == 0 || |
| 50 | 9x | length(color) %% 4 == 0) |
| 51 | ) { | |
| 52 | 2x | stop("invalid color") |
| 53 | } | |
| 54 | 7x | color_channels = if (length(color) %% 3 == 0) 3 else 4 |
| 55 | 7x | color = matrix( |
| 56 | 7x | color, |
| 57 | 7x | ncol = color_channels, |
| 58 | 7x | byrow = TRUE |
| 59 | ) | |
| 60 | } else { | |
| 61 | ! | if (length(color_dim) != 2 || !(color_dim[2] %in% c(3, 4))) { |
| 62 | ! | stop("invalid color") |
| 63 | } | |
| 64 | } | |
| 65 | } | |
| 66 | 65x | if (!all(is.finite(color))) { |
| 67 | ! | stop("invalid color") |
| 68 | } | |
| 69 | 65x | if (!all(color >= 0 & color <= 1)) { |
| 70 | ! | stop("invalid color") |
| 71 | } | |
| 72 | 65x | if (isTRUE(single) && nrow(color) != 1L) { |
| 73 | ! | stop("invalid color") |
| 74 | } | |
| 75 | 65x | if (as_hex) { |
| 76 | 27x | return(rgb_to_hex(color)) |
| 77 | } | |
| 78 | # return vector for single row, matrix otherwise | |
| 79 | ! | if (nrow(color) == 1L) as.numeric(color[1, ]) else color |
| 80 | } |
| 1 | #'@title Generate 2D Disk | |
| 2 | #' | |
| 3 | #'@description Generates a 2D disk with a gradual falloff. | |
| 4 | #' | |
| 5 | #'Disk generated using the following formula: | |
| 6 | #' | |
| 7 | #'\ifelse{html}{\out{(-22.35 * cos(1.68 * r<sup>2</sup>) + 85.91 * sin(1.68 * r<sup>2</sup>) ) * exp(-4.89 * r<sup>2</sup>) + | |
| 8 | #'(35.91 * cos(4.99 * r<sup>2</sup>) - 28.87 * sin(4.99 * r<sup>2</sup>)) * exp(-4.71 * r<sup>2</sup>) + | |
| 9 | #'(-13.21 * cos(8.24 * r<sup>2</sup>) - 1.57 * sin(8.24 * r<sup>2</sup>)) * exp(-4.05 * r<sup>2</sup>) + | |
| 10 | #'(0.50 * cos(11.90 * r<sup>2</sup>) + 1.81 * sin(11.90 * r<sup>2</sup>)) * exp(-2.92 * r<sup>2</sup>) + | |
| 11 | #'(0.13 * cos(16.11 * r<sup>2</sup>) - 0.01 * sin(16.11 * r<sup>2</sup>)) * exp(-1.51 * r<sup>2</sup>)}}{(-22.35 cos(1.68 r^2) + 85.91 sin(1.68 r^2) ) exp(-4.89 r^2) + | |
| 12 | #'(35.91 cos(4.99 r^2) - 28.87 sin(4.99 r^2)) exp(-4.71 r^2) + | |
| 13 | #'(-13.21 cos(8.24 r^2) - 1.57 sin(8.24 r^2)) exp(-4.05 r^2) + | |
| 14 | #'(0.50 cos(11.90 r^2) + 1.81 sin(11.90 r^2)) exp(-2.92 r^2) + | |
| 15 | #'(0.13 cos(16.11 r^2) - 0.01 sin(16.11 r^2)) exp(-1.51 r^2)} | |
| 16 | #' | |
| 17 | #'The origin of the coordinate system is the center of the matrix. | |
| 18 | #' | |
| 19 | #'@param dim Default `c(11, 11)`. The dimensions of the matrix. | |
| 20 | #'@param radius Default `1`. Radius of the disk, compared to the dimensions. Should be less than one. | |
| 21 | #'@param rescale_unity Default `FALSE`. If `TRUE`, this will rescale the max value to one. Useful | |
| 22 | #'if wanting to plot the distribution with [plot_image()]. | |
| 23 | #'@export | |
| 24 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 25 | #'image(generate_2d_disk(101), asp=1) | |
| 26 | generate_2d_disk = function( | |
| 27 | dim = c(11, 11), | |
| 28 | radius = 1, | |
| 29 | rescale_unity = FALSE | |
| 30 | ) { | |
| 31 | ! | dim = rev(dim) |
| 32 | ! | mindim = min(dim) |
| 33 | ! | add_offset_x = FALSE |
| 34 | ! | add_offset_y = FALSE |
| 35 | ! | if (length(dim) == 2) { |
| 36 | ! | if (dim[2] - dim[1] > 0) { |
| 37 | ! | if (abs(dim[2] - dim[1]) %% 2 != 0) { |
| 38 | ! | add_offset_x = TRUE |
| 39 | } | |
| 40 | ! | } else if (dim[2] - dim[1] < 0) { |
| 41 | ! | if (abs(dim[2] - dim[1]) %% 2 != 0) { |
| 42 | ! | add_offset_y = TRUE |
| 43 | } | |
| 44 | } | |
| 45 | } | |
| 46 | ! | disk = generate_disk((1 / radius) * 1.18, mindim, add_offset_x, add_offset_y) |
| 47 | ! | if (length(dim) == 2) { |
| 48 | ! | disk = pad_to_fit(dim, disk) |
| 49 | } | |
| 50 | ! | disk = (disk - min(disk)) / (max(disk) - min(disk)) |
| 51 | ! | disk = disk / sum(disk) |
| 52 | ! | if (rescale_unity) { |
| 53 | ! | return(disk / max(disk)) |
| 54 | } | |
| 55 | ! | return(disk) |
| 56 | } |
| 1 | #' Internal wrapper for stb_image C++ loader | |
| 2 | #' | |
| 3 | #' @description | |
| 4 | #' Internal helper that loads an image via the C++ `load_image_stb()` function | |
| 5 | #' and returns a 3D RGBA numeric array with dimensions `c(height, width, channels)`. | |
| 6 | #' | |
| 7 | #' @param filename Default `NULL`. Path to an image file to load. | |
| 8 | #' @param desired_channels Default `4L`. Number of channels to request from the loader. | |
| 9 | #' | |
| 10 | #' @return A numeric 3D array (height, width, `desired_channels`). | |
| 11 | #' @keywords internal | |
| 12 | #' @noRd | |
| 13 | read_image_stb = function(filename = NULL, desired_channels = 4L) { | |
| 14 | 7x | if (!is.character(filename) || length(filename) != 1L) { |
| 15 | ! | stop("'read_image_stb' expects a single filename string.") |
| 16 | } | |
| 17 | ||
| 18 | 7x | filename = normalizePath(filename, winslash = "/", mustWork = TRUE) |
| 19 | ||
| 20 | # Dummy values required by the Rcpp-exported interface | |
| 21 | 7x | width = 0L |
| 22 | 7x | height = 0L |
| 23 | 7x | channels = 0L |
| 24 | ||
| 25 | 7x | img = load_image_stb( |
| 26 | 7x | filename = filename, |
| 27 | 7x | width = width, |
| 28 | 7x | height = height, |
| 29 | 7x | channels = channels, |
| 30 | 7x | desired_channels = as.integer(desired_channels) |
| 31 | ) | |
| 32 | ||
| 33 | 7x | if (!is.numeric(img)) { |
| 34 | ! | stop("stb loader did not return a numeric array.") |
| 35 | } | |
| 36 | 7x | if (is.null(dim(img)) || length(dim(img)) != 3L) { |
| 37 | ! | stop("stb loader did not return a 3D array.") |
| 38 | } | |
| 39 | 7x | if (dim(img)[3L] != desired_channels) { |
| 40 | ! | stop( |
| 41 | ! | sprintf( |
| 42 | ! | "stb loader returned %d channels; expected %d.", |
| 43 | ! | dim(img)[3L], |
| 44 | ! | desired_channels |
| 45 | ) | |
| 46 | ) | |
| 47 | } | |
| 48 | ||
| 49 | 7x | storage.mode(img) = "double" |
| 50 | 7x | img |
| 51 | } |
| 1 | #'@title Make Vignette Overlay | |
| 2 | #' | |
| 3 | #'@description Makes an overlay to simulate vignetting in a camera | |
| 4 | #' | |
| 5 | #'@param width Width of the image. | |
| 6 | #'@param height Height of the image. | |
| 7 | #'@param intensity Default `0.4`. `1` is max intensity, `0` is min. | |
| 8 | #'@param radius Default `NULL`. Max of height or width, divided by 2. | |
| 9 | #'@param radius_multiplier Default `1.3`. | |
| 10 | #'@param color Default `black`. | |
| 11 | #'@keywords internal | |
| 12 | make_vignette_overlay = function( | |
| 13 | width, | |
| 14 | height, | |
| 15 | intensity = 0.3, | |
| 16 | radius_multiplier = 1.3, | |
| 17 | radius = NULL, | |
| 18 | color = "#000000" | |
| 19 | ) { | |
| 20 | ! | value = array( |
| 21 | ! | 0, |
| 22 | ! | dim = c( |
| 23 | ! | floor(width * radius_multiplier), |
| 24 | ! | floor(height * radius_multiplier), |
| 25 | ! | 4 |
| 26 | ) | |
| 27 | ) | |
| 28 | ! | hex_color = convert_color(color, as_hex = TRUE) |
| 29 | ! | color = convert_color(color) |
| 30 | ! | value[,, 4] = gen_ellipse( |
| 31 | ! | intensity, |
| 32 | ! | floor(width * radius_multiplier), |
| 33 | ! | floor(height * radius_multiplier) |
| 34 | ) | |
| 35 | ! | value[,, 1] = color[1] |
| 36 | ! | value[,, 2] = color[2] |
| 37 | ! | value[,, 3] = color[3] |
| 38 | ||
| 39 | ! | tempcircle = tempfile(fileext = ".png") |
| 40 | ! | png::writePNG(value, tempcircle) |
| 41 | ! | imageval = magick::image_read(tempcircle) |
| 42 | ! | if (radius_multiplier >= 1) { |
| 43 | ! | imageval |> |
| 44 | ! | magick::image_blur(radius = radius / 2, sigma = radius / 4) |> |
| 45 | ! | magick::image_crop(sprintf( |
| 46 | ! | "%ix%i+%i+%i", |
| 47 | ! | height, |
| 48 | ! | width, |
| 49 | ! | floor((height * radius_multiplier - height) / 2), |
| 50 | ! | floor((width * radius_multiplier - width) / 2) |
| 51 | )) |> | |
| 52 | ! | magick::image_write(tempcircle) |
| 53 | } else { | |
| 54 | ! | imageval |> |
| 55 | ! | magick::image_border( |
| 56 | ! | geometry = sprintf( |
| 57 | ! | "%ix%i", |
| 58 | ! | (height - floor(height * radius_multiplier)) / 2, |
| 59 | ! | (width - floor(width * radius_multiplier)) / 2 |
| 60 | ), | |
| 61 | ! | color = hex_color |
| 62 | ) |> | |
| 63 | ! | magick::image_blur(radius = radius / 2, sigma = radius / 4) |> |
| 64 | ! | magick::image_write(tempcircle) |
| 65 | } | |
| 66 | ! | return(tempcircle) |
| 67 | } |
| 1 | #'@title Clamp Image | |
| 2 | #' | |
| 3 | #'@description Clamps an image to a user-specified range, ignoring the alpha channel. | |
| 4 | #' | |
| 5 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 6 | #'@param min_value Default `0`. Minimum value to clamp the RGB channels in the image to. | |
| 7 | #'@param max_value Default `1`. Maximum value to clamp the RGB channels in the image to. | |
| 8 | #'@param filename Default `NA`. Filename | |
| 9 | #'@param preview Default `FALSE`. If `TRUE`, it will display the image in addition | |
| 10 | #'to returning it. | |
| 11 | #'@param ... Arguments to pass to either `jpeg::readJPEG`, `png::readPNG`, or `tiff::readTIFF`. | |
| 12 | #' | |
| 13 | #'@return A `rayimg` RGBA array. | |
| 14 | #'@import grDevices | |
| 15 | #'@export | |
| 16 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 17 | #'#The image of the unchanged image | |
| 18 | #'range(dragon) | |
| 19 | #'#Clamp the maximum and minimum values to one and zero | |
| 20 | #'render_clamp(dragon) |> | |
| 21 | #' range() | |
| 22 | render_clamp = function( | |
| 23 | image, | |
| 24 | min_value = 0, | |
| 25 | max_value = 1, | |
| 26 | filename = NA, | |
| 27 | preview = FALSE, | |
| 28 | ... | |
| 29 | ) { | |
| 30 | 174x | image = ray_read_image(image, reset_camera_settings = TRUE) #Always output RGBA array |
| 31 | 174x | imagetype = attr(image, "filetype") |
| 32 | 174x | img_source_linear = attr(image, "source_linear") |
| 33 | 174x | colorspace = attr(image, "colorspace") |
| 34 | 174x | white_current = attr(image, "white_current") |
| 35 | ||
| 36 | 174x | d = dim(image) |
| 37 | 174x | alpha_idx = NA |
| 38 | 174x | if (length(d) == 3) { |
| 39 | 112x | if (d[3] == 4) { |
| 40 | 111x | alpha_idx = 4 |
| 41 | } | |
| 42 | 112x | if (d[3] == 2) { |
| 43 | ! | alpha_idx = 2 |
| 44 | } | |
| 45 | } | |
| 46 | 174x | array_image = unclass(image) |
| 47 | 174x | if (length(d) == 2) { |
| 48 | 62x | array_image[image < min_value] = min_value |
| 49 | 62x | array_image[image > max_value] = max_value |
| 50 | 62x | array_image = array(array_image, dim = d) |
| 51 | } else { | |
| 52 | 112x | if (is.na(alpha_idx)) { |
| 53 | 1x | num_chans = 1:3 |
| 54 | } else { | |
| 55 | 111x | num_chans = seq_len(alpha_idx - 1) |
| 56 | } | |
| 57 | 112x | array_image = unclass(image) |
| 58 | 112x | for (chan in num_chans) { |
| 59 | 336x | tmp_chan = array_image[,, chan] |
| 60 | 336x | mat_d = dim(tmp_chan) |
| 61 | 336x | tmp_chan[array_image[,, chan] < min_value] = min_value |
| 62 | 336x | tmp_chan[array_image[,, chan] > max_value] = max_value |
| 63 | 336x | array_image[,, chan] = array(tmp_chan, dim = mat_d) |
| 64 | } | |
| 65 | } | |
| 66 | 174x | new_image = ray_read_image( |
| 67 | 174x | array_image, |
| 68 | 174x | filetype = imagetype, |
| 69 | 174x | source_linear = img_source_linear, |
| 70 | 174x | assume_colorspace = colorspace, |
| 71 | 174x | assume_white = white_current |
| 72 | ) | |
| 73 | 174x | handle_image_output(new_image, filename = filename, preview = preview) |
| 74 | } |
| 1 | #'@title Render Black and White | |
| 2 | #' | |
| 3 | #'@description Transforms an image to black and white, preserving luminance. | |
| 4 | #' | |
| 5 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 6 | #'@param rgb_coef Default `c(0.2126, 0.7152, 0.0722)`. | |
| 7 | #'Length-3 numeric vector listing coefficients to convert RGB to luminance. | |
| 8 | #'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead. | |
| 9 | #'@param preview Default `FALSE`. Whether to plot the convolved image, or just to return the values. | |
| 10 | #'@return A `rayimg` RGBA array. | |
| 11 | #'@export | |
| 12 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 13 | #'#Plot the image with a title | |
| 14 | #'dragon |> | |
| 15 | #' render_title("Dragon", title_offset=c(10,10), title_bar_color="black", | |
| 16 | #' title_size=20, title_color = "white") |> | |
| 17 | #' render_bw(preview = TRUE) | |
| 18 | render_bw = function( | |
| 19 | image, | |
| 20 | rgb_coef = c(0.2126, 0.7152, 0.0722), | |
| 21 | filename = NULL, | |
| 22 | preview = FALSE | |
| 23 | ) { | |
| 24 | ! | stopifnot(length(rgb_coef) == 3 && is.numeric(rgb_coef)) |
| 25 | ! | src = ray_read_image(image, reset_camera_settings = TRUE) |
| 26 | ! | imagetype = attr(src, "filetype") |
| 27 | ! | img_source_linear = attr(src, "source_linear") |
| 28 | ! | colorspace = attr(src, "colorspace") |
| 29 | ! | white_current = attr(src, "white_current") |
| 30 | ||
| 31 | ! | d = dim(src) |
| 32 | ! | is_array = length(d) == 3 |
| 33 | ||
| 34 | ! | if (attr(src, "filetype") == "matrix" || (is_array && d[3] == 2)) { |
| 35 | ! | return(handle_image_output(src, filename = filename, preview = preview)) |
| 36 | } | |
| 37 | ||
| 38 | # luminance | |
| 39 | ! | lum = rgb_coef[1] * |
| 40 | ! | src[,, 1] + |
| 41 | ! | rgb_coef[2] * src[,, 2] + |
| 42 | ! | rgb_coef[3] * src[,, 3] |
| 43 | ||
| 44 | ! | if (length(dim(src)) == 2) { |
| 45 | ! | out = lum |
| 46 | } else { | |
| 47 | ! | out = array(1, dim = c(d[1], d[2], 2)) |
| 48 | ! | out[,, 1] = lum |
| 49 | ! | out[,, 2] = if (d[3] == 4L) src[,, 4] else 1 |
| 50 | } | |
| 51 | ||
| 52 | ! | out = ray_read_image( |
| 53 | ! | out, |
| 54 | ! | filetype = imagetype, |
| 55 | ! | source_linear = img_source_linear, |
| 56 | ! | assume_colorspace = colorspace, |
| 57 | ! | assume_white = white_current |
| 58 | ) | |
| 59 | ||
| 60 | ! | handle_image_output(out, filename = filename, preview = preview) |
| 61 | } |
| 1 | #'@title Generate 2D exponential Distribution | |
| 2 | #' | |
| 3 | #'@description Generates a 2D exponential distribution, with an optional | |
| 4 | #'argument to take the exponential to a user-defined power. | |
| 5 | #' | |
| 6 | #'@param falloff Default `1`. Falloff of the exponential. | |
| 7 | #'@param dim Default `c(11, 11)`. The dimensions of the matrix. | |
| 8 | #'@param width Default `3` (`-10` to `10`). The range in which to compute the distribution. | |
| 9 | #'@param rescale_unity Default `FALSE`. If `TRUE`, this will rescale the max value to one. Useful | |
| 10 | #'if wanting to plot the distribution with [plot_image()]. | |
| 11 | #'@import stats | |
| 12 | #'@export | |
| 13 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 14 | #'image(generate_2d_exponential(1,31,3), asp=1) | |
| 15 | generate_2d_exponential = function( | |
| 16 | falloff = 1, | |
| 17 | dim = c(11, 11), | |
| 18 | width = 3, | |
| 19 | rescale_unity = FALSE | |
| 20 | ) { | |
| 21 | ! | if (length(dim) == 1) { |
| 22 | ! | dim = c(dim, dim) |
| 23 | } | |
| 24 | ! | xy_ratio = dim[1] / dim[2] |
| 25 | ! | if (xy_ratio > 1) { |
| 26 | ! | x = seq(-width * xy_ratio, width * xy_ratio, length.out = dim[1]) |
| 27 | ! | y = seq(-width, width, length.out = dim[2]) |
| 28 | } else { | |
| 29 | ! | x = seq(-width, width, length.out = dim[1]) |
| 30 | ! | y = seq(-width / xy_ratio, width / xy_ratio, length.out = dim[2]) |
| 31 | } | |
| 32 | ! | testmat = matrix(0, dim[1], dim[2]) |
| 33 | ! | for (i in 1:length(x)) { |
| 34 | ! | for (j in 1:length(y)) { |
| 35 | ! | testmat[i, j] = (dexp(sqrt(x[i]^2 + y[j]^2), rate = 1 / falloff)) |
| 36 | } | |
| 37 | } | |
| 38 | ! | if (rescale_unity) { |
| 39 | ! | temp = testmat / sum(testmat) |
| 40 | ! | return(temp / max(temp)) |
| 41 | } | |
| 42 | ! | testmat / sum(testmat) |
| 43 | } |
| 1 | #' @title Convert to Native Raster | |
| 2 | #' | |
| 3 | #' @description Converts a matrix or image array to a native raster. | |
| 4 | #' | |
| 5 | #' @param input Matrix or image array to convert to a native raster. | |
| 6 | #' @keywords internal | |
| 7 | convert_to_native_raster = function(input) { | |
| 8 | 62x | ncol = ncol(input) |
| 9 | 62x | nrow = nrow(input) |
| 10 | 62x | if (length(dim(input)) == 3) { |
| 11 | 62x | if (dim(input)[3] == 3) { |
| 12 | ! | channels = 3 |
| 13 | ! | nr = encode_native_image_rcpp_3(input[,, 1], input[,, 2], input[,, 3]) |
| 14 | 62x | } else if (dim(input)[3] == 4) { |
| 15 | 62x | channels = 4 |
| 16 | 62x | nr = encode_native_image_rcpp_4( |
| 17 | 62x | input[,, 1], |
| 18 | 62x | input[,, 2], |
| 19 | 62x | input[,, 3], |
| 20 | 62x | input[,, 4] |
| 21 | ) | |
| 22 | ! | } else if (dim(input)[3] == 2) { |
| 23 | ! | channels = 3 |
| 24 | ! | nr = encode_native_image_rcpp_4( |
| 25 | ! | input[,, 1], |
| 26 | ! | input[,, 1], |
| 27 | ! | input[,, 1], |
| 28 | ! | input[,, 2] |
| 29 | ) | |
| 30 | } else { | |
| 31 | ! | stop(sprintf( |
| 32 | ! | "Dimension of array (%d/%d/%d) do not correspond to any image types", |
| 33 | ! | dim(input)[1], |
| 34 | ! | dim(input)[2], |
| 35 | ! | dim(input)[3] |
| 36 | )) | |
| 37 | } | |
| 38 | ! | } else if (length(dim(input)) == 2) { |
| 39 | ! | channels = 3 |
| 40 | ! | nr = encode_native_image_rcpp_1(input) |
| 41 | } else { | |
| 42 | ! | stop(sprintf("Dimensions of array do not correspond to any image types")) |
| 43 | } | |
| 44 | 62x | class(nr) = "nativeRaster" |
| 45 | 62x | dim(nr) = c(nrow, ncol) |
| 46 | 62x | attr(nr, "channels") = channels |
| 47 | 62x | return(nr) |
| 48 | } |
| 1 | #'@title Plot Image | |
| 2 | #' | |
| 3 | #'@description Displays the image in the current device. | |
| 4 | #' | |
| 5 | #'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image. | |
| 6 | #'@param draw_grid Default `FALSE`. If `TRUE`, this will draw a grid in the background to help | |
| 7 | #'disambiguate the actual image from the device (helpful if the image background is the same as the | |
| 8 | #'device's background). | |
| 9 | #'@param asp Default `1`. Aspect ratio of the pixels in the plot. For example, an aspect ratio of `4/3` will | |
| 10 | #'slightly widen the image. | |
| 11 | #'@param new_page Default `TRUE`. Whether to call `grid::grid.newpage()` before plotting the image. | |
| 12 | #'@param ignore_alpha Default `FALSE`. Whether to ignore the alpha channel when plotting. | |
| 13 | #'@param return_grob Default `FALSE`. Whether to return the grob object. | |
| 14 | #'@param gp A `grid::gpar()` object to include for the grid viewport displaying the image. | |
| 15 | #'@param angle Default `0`. Counter-clockwise rotation (in degrees) applied before plotting. | |
| 16 | #'@param show_linear Default `FALSE`. Most data should be gamma corrected before displaying on a screen. | |
| 17 | #' Set to `TRUE` to turn off this gamma correction. | |
| 18 | #'@export | |
| 19 | #'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 20 | #'#Plot the dragon array | |
| 21 | #'plot_image(dragon) | |
| 22 | #'#Make pixels twice as wide as tall | |
| 23 | #'plot_image(dragon, asp = 2) | |
| 24 | #'#Plot non-square images | |
| 25 | #'plot_image(dragon[1:100,,]) | |
| 26 | #'#Make pixels twice as tall as wide | |
| 27 | #'plot_image(dragon[1:100,,], asp = 1/2) | |
| 28 | plot_image = function( | |
| 29 | image, | |
| 30 | draw_grid = FALSE, | |
| 31 | ignore_alpha = FALSE, | |
| 32 | asp = 1, | |
| 33 | new_page = TRUE, | |
| 34 | return_grob = FALSE, | |
| 35 | gp = grid::gpar(), | |
| 36 | angle = 0, | |
| 37 | show_linear = FALSE | |
| 38 | ) { | |
| 39 | 36x | prepared = prepare_native_raster( |
| 40 | 36x | image, |
| 41 | 36x | angle = angle, |
| 42 | 36x | show_linear = show_linear |
| 43 | ) | |
| 44 | 36x | nr = prepared$native_raster |
| 45 | ||
| 46 | 36x | if (new_page) { |
| 47 | 36x | grid::grid.newpage() |
| 48 | } | |
| 49 | 36x | image_dim = prepared$display_dim |
| 50 | ||
| 51 | 36x | if (draw_grid) { |
| 52 | ! | draw_grid_fxn = function() { |
| 53 | ! | grid::pushViewport( |
| 54 | ! | grid::viewport( |
| 55 | ! | layout = grid::grid.layout( |
| 56 | ! | 1, |
| 57 | ! | 1, |
| 58 | ! | widths = grid::unit(image_dim[1], "pt"), |
| 59 | ! | heights = grid::unit(image_dim[2], "pt") |
| 60 | ), | |
| 61 | ! | gp = gp |
| 62 | ) | |
| 63 | ) | |
| 64 | ! | grid_density = 0.01 |
| 65 | ! | for (i in seq(-2, 2, by = grid_density)) { |
| 66 | ! | grid::grid.lines( |
| 67 | ! | x = c(0, 1), |
| 68 | ! | y = c(i, i + 1), |
| 69 | ! | default.units = "npc", |
| 70 | ! | gp = grid::gpar(col = "grey") |
| 71 | ) | |
| 72 | ! | grid::grid.lines( |
| 73 | ! | x = c(0, 1), |
| 74 | ! | y = c(i, i - 1), |
| 75 | ! | default.units = "npc", |
| 76 | ! | gp = grid::gpar(col = "grey") |
| 77 | ) | |
| 78 | } | |
| 79 | ! | grid::popViewport() |
| 80 | } | |
| 81 | ! | draw_grid_fxn() |
| 82 | } | |
| 83 | 36x | return(plot_asp_native_raster( |
| 84 | 36x | nr, |
| 85 | 36x | asp = asp, |
| 86 | 36x | return_grob = return_grob, |
| 87 | 36x | gp = gp |
| 88 | )) | |
| 89 | } |
| 1 | #' @title Get String Dimensions | |
| 2 | #' | |
| 3 | #' @description | |
| 4 | #' Calculates font metrics for a specified font, font size, and style. | |
| 5 | #' | |
| 6 | #' @param string The string to be measured. | |
| 7 | #' @param font Default `"sans"`. | |
| 8 | #' @param size A numeric value specifying the size of the font in points. | |
| 9 | #' @param align Default `"left"``. The string alignment. | |
| 10 | #' @param ... Other arguments to pass to `systemfonts::shape_string()`` | |
| 11 | #' | |
| 12 | #' @return A data.frame listing the string dimensions. | |
| 13 | #' | |
| 14 | #' @details | |
| 15 | #' The function renders specific characters (`"d"` for ascender, `"g"` for descender, `"x"` for neutral) using the specified font parameters. It calculates the bounding box of each character to determine the necessary adjustments for accurate text positioning. | |
| 16 | #' | |
| 17 | #' @import grDevices grid png | |
| 18 | #' @export | |
| 19 | #' @examples | |
| 20 | #' # Get height of basic sans font | |
| 21 | #' get_string_dimensions("This is a string", size=24) | |
| 22 | get_string_dimensions = function( | |
| 23 | string, | |
| 24 | font = "sans", | |
| 25 | size = 12, | |
| 26 | align = "center", | |
| 27 | ... | |
| 28 | ) { | |
| 29 | 8x | size_metrics = systemfonts::shape_string( |
| 30 | 8x | string, |
| 31 | 8x | family = font, |
| 32 | 8x | size = size, |
| 33 | 8x | align = align, |
| 34 | ... | |
| 35 | 8x | )[["metrics"]] |
| 36 | 8x | return(size_metrics) |
| 37 | } |
| 1 | #'@title Calculate Bokeh Size | |
| 2 | #' | |
| 3 | #'@description Calculates the amount of blurring at each point with camera characteristics. | |
| 4 | #' | |
| 5 | #'@param z Depth matrix. | |
| 6 | #'@param zfocus Depth in which to blur. Minimum 0, maximum 1. | |
| 7 | #'@param f Focal length of the virtual camera. . | |
| 8 | #'@param N F-stop. Focal length of the virtual camera. | |
| 9 | #'@keywords internal | |
| 10 | #'@return Matrix of bokeh sizes. | |
| 11 | calc_bokeh_size = function(z, zfocus, f, N, ramp) { | |
| 12 | ! | ifelse( |
| 13 | ! | z - zfocus < 0, |
| 14 | ! | abs(f^2 * abs(z - zfocus) * ramp / ((zfocus - f) * z * N)), |
| 15 | ! | abs(f^2 * abs(z - zfocus) / ((zfocus - f) * z * N * ramp)) |
| 16 | ) | |
| 17 | } |
| 1 | #include <Rcpp.h> | |
| 2 | using namespace Rcpp; | |
| 3 | ||
| 4 | //Boolean distance code partly derived from "Distance Transforms of Sampled Functions" | |
| 5 | //(Pedro F. Felzenszwalb and Daniel P. Huttenlocher) | |
| 6 | ||
| 7 | #define INF 1E20; | |
| 8 | ||
| 9 | template <class T> | |
| 10 | 414x | inline T square(const T &x) { return x*x; }; |
| 11 | ||
| 12 | 48x | static NumericVector dt(NumericVector f, int n) { |
| 13 | 48x | NumericVector d(n); |
| 14 | 48x | IntegerVector v(n); |
| 15 | 48x | NumericVector z(n+1); |
| 16 | 48x | int k = 0; |
| 17 | 48x | v[0] = 0; |
| 18 | 48x | z[0] = -INF; |
| 19 | 48x | z[1] = +INF; |
| 20 | 146x | for (int q = 1; q <= n-1; q++) { |
| 21 | 98x | float s = ((f[q]+square(q))-(f[v[k]]+square(v[k])))/(2*q-2*v[k]); |
| 22 | 134x | while (s <= z[k]) { |
| 23 | 36x | k--; |
| 24 | 36x | s = ((f[q]+square(q))-(f[v[k]]+square(v[k])))/(2*q-2*v[k]); |
| 25 | } | |
| 26 | 98x | k++; |
| 27 | 98x | v[k] = q; |
| 28 | 98x | z[k] = s; |
| 29 | 98x | z[k+1] = +INF; |
| 30 | } | |
| 31 | ||
| 32 | 48x | k = 0; |
| 33 | 194x | for (int q = 0; q <= n-1; q++) { |
| 34 | 200x | while (z[k+1] < q) { |
| 35 | 54x | k++; |
| 36 | } | |
| 37 | 146x | d[q] = square(q-v[k]) + f[v[k]]; |
| 38 | } | |
| 39 | 48x | return(d); |
| 40 | } | |
| 41 | ||
| 42 | 7x | static void dt(NumericMatrix& im) { |
| 43 | 7x | int width = im.nrow(); |
| 44 | 7x | int height = im.ncol(); |
| 45 | 7x | NumericVector f(std::max(width,height)); |
| 46 | ||
| 47 | // transform along columns | |
| 48 | 26x | for (int x = 0; x < width; x++) { |
| 49 | 92x | for (int y = 0; y < height; y++) { |
| 50 | 73x | f(y) = im(x, y); |
| 51 | } | |
| 52 | 19x | NumericVector d = dt(f, height); |
| 53 | 92x | for (int y = 0; y < height; y++) { |
| 54 | 73x | im(x, y) = d(y); |
| 55 | } | |
| 56 | } | |
| 57 | ||
| 58 | // transform along rows | |
| 59 | 36x | for (int y = 0; y < height; y++) { |
| 60 | 102x | for (int x = 0; x < width; x++) { |
| 61 | 73x | f(x) = im(x, y); |
| 62 | } | |
| 63 | 29x | NumericVector d = dt(f, width); |
| 64 | 102x | for (int x = 0; x < width; x++) { |
| 65 | 73x | im(x, y) = d(x); |
| 66 | } | |
| 67 | } | |
| 68 | } | |
| 69 | ||
| 70 | // [[Rcpp::export]] | |
| 71 | 7x | NumericMatrix get_boolean_distance(LogicalMatrix input) { |
| 72 | 7x | int width = input.nrow(); |
| 73 | 7x | int height = input.ncol(); |
| 74 | ||
| 75 | 7x | NumericMatrix out(width, height); |
| 76 | 36x | for (int y = 0; y < height; y++) { |
| 77 | 102x | for (int x = 0; x < width; x++) { |
| 78 | 73x | if (input(x, y) == 1) { |
| 79 | 26x | out(x, y) = 0; |
| 80 | } else { | |
| 81 | 47x | out(x, y) = INF; |
| 82 | } | |
| 83 | } | |
| 84 | } | |
| 85 | 7x | dt(out); |
| 86 | 26x | for(int i = 0; i < width; i++) { |
| 87 | 92x | for(int j = 0; j < height; j++) { |
| 88 | 73x | out(i,j) = sqrt(out(i,j)); |
| 89 | } | |
| 90 | } | |
| 91 | 7x | return(out); |
| 92 | } | |
| 93 |
| 1 | #include <Rcpp.h> | |
| 2 | using namespace Rcpp; | |
| 3 | ||
| 4 | #define R_RGBA(r,g,b,a) ((r)|((g)<<8)|((b)<<16)|((a)<<24)) | |
| 5 | ||
| 6 | // [[Rcpp::export]] | |
| 7 | ! | IntegerVector encode_native_image_rcpp_1(NumericMatrix& bw_image) { |
| 8 | ! | int n = bw_image.nrow() * bw_image.ncol(); |
| 9 | ! | IntegerVector native_vector(n); |
| 10 | ! | for (int i = 0; i < bw_image.ncol(); i++) { |
| 11 | ! | for (int j = 0; j < bw_image.nrow(); j++) { |
| 12 | ! | native_vector[i + j * bw_image.ncol()] = R_RGBA( |
| 13 | int(bw_image(j,i) * 255), | |
| 14 | int(bw_image(j,i) * 255), | |
| 15 | int(bw_image(j,i) * 255), | |
| 16 | 255); | |
| 17 | } | |
| 18 | } | |
| 19 | ! | return native_vector; |
| 20 | } | |
| 21 | ||
| 22 | // [[Rcpp::export]] | |
| 23 | ! | IntegerVector encode_native_image_rcpp_3(NumericMatrix& r_image, |
| 24 | NumericMatrix& g_image, | |
| 25 | NumericMatrix& b_image) { | |
| 26 | ! | int n = r_image.nrow() * r_image.ncol(); |
| 27 | ! | IntegerVector native_vector(n); |
| 28 | ! | for (int i = 0; i < r_image.ncol(); i++) { |
| 29 | ! | for (int j = 0; j < r_image.nrow(); j++) { |
| 30 | ! | native_vector[i + j * r_image.ncol()] = R_RGBA( |
| 31 | int(r_image(j,i) * 255), | |
| 32 | int(g_image(j,i) * 255), | |
| 33 | int(b_image(j,i) * 255), | |
| 34 | 255); | |
| 35 | } | |
| 36 | } | |
| 37 | ! | return native_vector; |
| 38 | } | |
| 39 | ||
| 40 | // [[Rcpp::export]] | |
| 41 | 62x | IntegerVector encode_native_image_rcpp_4(NumericMatrix& r_image, |
| 42 | NumericMatrix& g_image, | |
| 43 | NumericMatrix& b_image, | |
| 44 | NumericMatrix& a_image) { | |
| 45 | 62x | int n = r_image.nrow() * r_image.ncol(); |
| 46 | 62x | IntegerVector native_vector(n); |
| 47 | 3430x | for (int i = 0; i < r_image.ncol(); i++) { |
| 48 | 210752x | for (int j = 0; j < r_image.nrow(); j++) { |
| 49 | 207384x | native_vector[i + j * r_image.ncol()] = R_RGBA( |
| 50 | int(r_image(j,i) * 255), | |
| 51 | int(g_image(j,i) * 255), | |
| 52 | int(b_image(j,i) * 255), | |
| 53 | int(a_image(j,i) * 255)); | |
| 54 | } | |
| 55 | } | |
| 56 | 62x | return native_vector; |
| 57 | } |
| 1 | #include <algorithm> | |
| 2 | #include <cmath> | |
| 3 | #include <cstddef> | |
| 4 | #include <cstdint> | |
| 5 | #include <cstring> | |
| 6 | #include <string> | |
| 7 | #include <vector> | |
| 8 | ||
| 9 | #include <Rcpp.h> | |
| 10 | ||
| 11 | #define TINY_DNG_LOADER_IMPLEMENTATION | |
| 12 | #define TINY_DNG_LOADER_NO_STB_IMAGE_INCLUDE | |
| 13 | #define TINY_DNG_LOADER_USE_STB_IMAGE | |
| 14 | #include <stbimageheaders/stb_image.h> | |
| 15 | #include <tinydng/tiny_dng_loader.h> | |
| 16 | ||
| 17 | #define TINY_DNG_WRITER_IMPLEMENTATION | |
| 18 | #include <tinydng/tiny_dng_writer.h> | |
| 19 | ||
| 20 | namespace { | |
| 21 | ||
| 22 | 14x | bool HasListElement(const Rcpp::List& list, const char* name) { |
| 23 | 14x | return list.containsElementNamed(name); |
| 24 | } | |
| 25 | ||
| 26 | 2x | Rcpp::NumericVector GetNumericVector(const Rcpp::List& list, const char* name) { |
| 27 | 2x | if (!HasListElement(list, name)) { |
| 28 | ! | return Rcpp::NumericVector(); |
| 29 | } | |
| 30 | 4x | return Rcpp::as<Rcpp::NumericVector>(list[name]); |
| 31 | } | |
| 32 | ||
| 33 | ! | Rcpp::IntegerVector GetIntegerVector(const Rcpp::List& list, const char* name) { |
| 34 | ! | if (!HasListElement(list, name)) { |
| 35 | ! | return Rcpp::IntegerVector(); |
| 36 | } | |
| 37 | ! | return Rcpp::as<Rcpp::IntegerVector>(list[name]); |
| 38 | } | |
| 39 | ||
| 40 | ! | bool HasNaNumeric(const Rcpp::NumericVector& vec, int required) { |
| 41 | ! | if (vec.size() < required) { |
| 42 | ! | return true; |
| 43 | } | |
| 44 | ! | for (int i = 0; i < required; ++i) { |
| 45 | ! | if (Rcpp::NumericVector::is_na(vec[i])) { |
| 46 | ! | return true; |
| 47 | } | |
| 48 | } | |
| 49 | ! | return false; |
| 50 | } | |
| 51 | ||
| 52 | ! | bool HasNaInteger(const Rcpp::IntegerVector& vec, int required) { |
| 53 | ! | if (vec.size() < required) { |
| 54 | ! | return true; |
| 55 | } | |
| 56 | ! | for (int i = 0; i < required; ++i) { |
| 57 | ! | if (vec[i] == NA_INTEGER) { |
| 58 | ! | return true; |
| 59 | } | |
| 60 | } | |
| 61 | ! | return false; |
| 62 | } | |
| 63 | ||
| 64 | 512x | double Clamp01(double v) { |
| 65 | 512x | if (v < 0.0) return 0.0; |
| 66 | 512x | if (v > 1.0) return 1.0; |
| 67 | 512x | return v; |
| 68 | } | |
| 69 | ||
| 70 | 2x | double DefaultWhiteLevel(int bits_per_sample) { |
| 71 | 2x | if (bits_per_sample <= 0) { |
| 72 | ! | return 0.0; |
| 73 | } | |
| 74 | 2x | return std::pow(2.0, static_cast<double>(bits_per_sample)) - 1.0; |
| 75 | } | |
| 76 | ||
| 77 | const int kTagLinearizationTable = 50712; | |
| 78 | const int kTagBaselineExposure = 50730; | |
| 79 | ||
| 80 | 1x | void AppendWarn(std::string* warn, const std::string& msg) { |
| 81 | 1x | if (!warn || msg.empty()) { |
| 82 | ! | return; |
| 83 | } | |
| 84 | 1x | if (!warn->empty()) { |
| 85 | ! | (*warn) += " "; |
| 86 | } | |
| 87 | 1x | (*warn) += msg; |
| 88 | } | |
| 89 | ||
| 90 | 10x | const tinydng::FieldData* FindCustomField(const tinydng::DNGImage& image, |
| 91 | int tag) { | |
| 92 | 20x | for (const auto& field : image.custom_fields) { |
| 93 | ! | if (field.tag == tag) { |
| 94 | ! | return &field; |
| 95 | } | |
| 96 | } | |
| 97 | 10x | return nullptr; |
| 98 | } | |
| 99 | ||
| 100 | 5x | const tinydng::FieldData* FindCustomFieldAny( |
| 101 | const std::vector<tinydng::DNGImage>& images, | |
| 102 | int tag, | |
| 103 | std::size_t* image_idx) { | |
| 104 | 10x | for (std::size_t i = 0; i < images.size(); ++i) { |
| 105 | 5x | const tinydng::FieldData* field = FindCustomField(images[i], tag); |
| 106 | 5x | if (field) { |
| 107 | ! | if (image_idx) { |
| 108 | ! | *image_idx = i; |
| 109 | } | |
| 110 | ! | return field; |
| 111 | } | |
| 112 | } | |
| 113 | 5x | return nullptr; |
| 114 | } | |
| 115 | ||
| 116 | ! | bool ReadCustomShort(const tinydng::FieldData& field, uint16_t* value) { |
| 117 | ! | if ((field.type != tinydng::TYPE_SHORT) && |
| 118 | ! | (field.type != tinydng::TYPE_SSHORT)) { |
| 119 | ! | return false; |
| 120 | } | |
| 121 | ! | if (field.data.size() < sizeof(uint16_t)) { |
| 122 | ! | return false; |
| 123 | } | |
| 124 | ! | uint16_t out = 0; |
| 125 | ! | std::memcpy(&out, field.data.data(), sizeof(uint16_t)); |
| 126 | ! | if (value) { |
| 127 | ! | *value = out; |
| 128 | } | |
| 129 | ! | return true; |
| 130 | } | |
| 131 | ||
| 132 | ! | bool ReadCustomRational(const tinydng::FieldData& field, |
| 133 | double* value, | |
| 134 | bool signed_value) { | |
| 135 | ! | if (field.data.size() < sizeof(uint32_t) * 2) { |
| 136 | ! | return false; |
| 137 | } | |
| 138 | ! | uint32_t num_u = 0; |
| 139 | ! | uint32_t den_u = 0; |
| 140 | ! | std::memcpy(&num_u, field.data.data(), sizeof(uint32_t)); |
| 141 | ! | std::memcpy(&den_u, field.data.data() + sizeof(uint32_t), sizeof(uint32_t)); |
| 142 | ! | if (den_u == 0) { |
| 143 | ! | return false; |
| 144 | } | |
| 145 | ! | double num = signed_value ? static_cast<double>(static_cast<int32_t>(num_u)) |
| 146 | ! | : static_cast<double>(num_u); |
| 147 | ! | double den = signed_value ? static_cast<double>(static_cast<int32_t>(den_u)) |
| 148 | ! | : static_cast<double>(den_u); |
| 149 | ! | if (value) { |
| 150 | ! | *value = num / den; |
| 151 | } | |
| 152 | ! | return true; |
| 153 | } | |
| 154 | ||
| 155 | ! | std::vector<uint16_t> ExtractLinearizationTable( |
| 156 | const tinydng::FieldData& field) { | |
| 157 | ! | std::vector<uint16_t> table; |
| 158 | ! | if (field.type != tinydng::TYPE_SHORT) { |
| 159 | ! | return table; |
| 160 | } | |
| 161 | ! | if (field.data.size() < sizeof(uint16_t)) { |
| 162 | ! | return table; |
| 163 | } | |
| 164 | ! | std::size_t count = field.data.size() / sizeof(uint16_t); |
| 165 | ! | table.reserve(count); |
| 166 | ! | for (std::size_t i = 0; i < count; ++i) { |
| 167 | ! | uint16_t value = 0; |
| 168 | ! | std::memcpy(&value, field.data.data() + i * sizeof(uint16_t), |
| 169 | sizeof(uint16_t)); | |
| 170 | ! | table.push_back(value); |
| 171 | } | |
| 172 | ! | return table; |
| 173 | } | |
| 174 | ||
| 175 | 4x | std::vector<double> RowMajorToR(const std::vector<double>& values, |
| 176 | int width, | |
| 177 | int height, | |
| 178 | int spp) { | |
| 179 | 4x | std::vector<double> out(values.size()); |
| 180 | 26x | for (int y = 0; y < height; ++y) { |
| 181 | 292x | for (int x = 0; x < width; ++x) { |
| 182 | 540x | for (int c = 0; c < spp; ++c) { |
| 183 | 270x | std::size_t src_idx = (static_cast<std::size_t>(y) * |
| 184 | 270x | static_cast<std::size_t>(width) + static_cast<std::size_t>(x)) * |
| 185 | 270x | static_cast<std::size_t>(spp) + static_cast<std::size_t>(c); |
| 186 | 270x | std::size_t dst_idx = static_cast<std::size_t>(y) + |
| 187 | 270x | static_cast<std::size_t>(height) * |
| 188 | 270x | (static_cast<std::size_t>(x) + static_cast<std::size_t>(width) * |
| 189 | 270x | static_cast<std::size_t>(c)); |
| 190 | 270x | out[dst_idx] = values[src_idx]; |
| 191 | } | |
| 192 | } | |
| 193 | } | |
| 194 | 4x | return out; |
| 195 | } | |
| 196 | ||
| 197 | 3x | std::vector<double> RToRowMajor(const Rcpp::NumericVector& pixels, |
| 198 | int width, | |
| 199 | int height, | |
| 200 | int spp) { | |
| 201 | 3x | std::vector<double> out(static_cast<std::size_t>(width) * |
| 202 | 3x | static_cast<std::size_t>(height) * static_cast<std::size_t>(spp)); |
| 203 | 11x | for (int y = 0; y < height; ++y) { |
| 204 | 36x | for (int x = 0; x < width; ++x) { |
| 205 | 56x | for (int c = 0; c < spp; ++c) { |
| 206 | 28x | std::size_t src_idx = static_cast<std::size_t>(y) + |
| 207 | 28x | static_cast<std::size_t>(height) * |
| 208 | 28x | (static_cast<std::size_t>(x) + static_cast<std::size_t>(width) * |
| 209 | 28x | static_cast<std::size_t>(c)); |
| 210 | 28x | std::size_t dst_idx = (static_cast<std::size_t>(y) * |
| 211 | 28x | static_cast<std::size_t>(width) + static_cast<std::size_t>(x)) * |
| 212 | 28x | static_cast<std::size_t>(spp) + static_cast<std::size_t>(c); |
| 213 | 28x | out[dst_idx] = pixels[src_idx]; |
| 214 | } | |
| 215 | } | |
| 216 | } | |
| 217 | 3x | return out; |
| 218 | } | |
| 219 | ||
| 220 | 1x | bool ActiveAreaValid(const int active_area[4], int width, int height) { |
| 221 | 1x | int top = active_area[0]; |
| 222 | 1x | int left = active_area[1]; |
| 223 | 1x | int bottom = active_area[2]; |
| 224 | 1x | int right = active_area[3]; |
| 225 | 1x | if (top < 0 || left < 0 || bottom <= top || right <= left) { |
| 226 | ! | return false; |
| 227 | } | |
| 228 | 1x | if (bottom > height || right > width) { |
| 229 | ! | return false; |
| 230 | } | |
| 231 | 1x | return true; |
| 232 | } | |
| 233 | ||
| 234 | 1x | bool ApplyActiveAreaCrop(const std::vector<double>& values, |
| 235 | int width, | |
| 236 | int height, | |
| 237 | int spp, | |
| 238 | const int active_area[4], | |
| 239 | std::vector<double>* out_values, | |
| 240 | int* out_width, | |
| 241 | int* out_height) { | |
| 242 | 1x | if (!ActiveAreaValid(active_area, width, height)) { |
| 243 | ! | return false; |
| 244 | } | |
| 245 | 1x | int top = active_area[0]; |
| 246 | 1x | int left = active_area[1]; |
| 247 | 1x | int bottom = active_area[2]; |
| 248 | 1x | int right = active_area[3]; |
| 249 | 1x | int crop_height = bottom - top; |
| 250 | 1x | int crop_width = right - left; |
| 251 | ||
| 252 | 1x | std::vector<double> cropped(static_cast<std::size_t>(crop_width) * |
| 253 | 1x | static_cast<std::size_t>(crop_height) * static_cast<std::size_t>(spp)); |
| 254 | ||
| 255 | 3x | for (int y = 0; y < crop_height; ++y) { |
| 256 | 2x | int src_y = y + top; |
| 257 | 8x | for (int x = 0; x < crop_width; ++x) { |
| 258 | 6x | int src_x = x + left; |
| 259 | 12x | for (int c = 0; c < spp; ++c) { |
| 260 | 6x | std::size_t src_idx = (static_cast<std::size_t>(src_y) * |
| 261 | 6x | static_cast<std::size_t>(width) + static_cast<std::size_t>(src_x)) * |
| 262 | 6x | static_cast<std::size_t>(spp) + static_cast<std::size_t>(c); |
| 263 | 6x | std::size_t dst_idx = (static_cast<std::size_t>(y) * |
| 264 | 6x | static_cast<std::size_t>(crop_width) + static_cast<std::size_t>(x)) * |
| 265 | 6x | static_cast<std::size_t>(spp) + static_cast<std::size_t>(c); |
| 266 | 6x | cropped[dst_idx] = values[src_idx]; |
| 267 | } | |
| 268 | } | |
| 269 | } | |
| 270 | ||
| 271 | 1x | if (out_values) { |
| 272 | 1x | *out_values = std::move(cropped); |
| 273 | } | |
| 274 | 1x | if (out_width) { |
| 275 | 1x | *out_width = crop_width; |
| 276 | } | |
| 277 | 1x | if (out_height) { |
| 278 | 1x | *out_height = crop_height; |
| 279 | } | |
| 280 | 1x | return true; |
| 281 | } | |
| 282 | ||
| 283 | ! | double SampleGainMap(const tinydng::GainMap& gmap, |
| 284 | int x, | |
| 285 | int y, | |
| 286 | int plane, | |
| 287 | std::string* warn) { | |
| 288 | ! | if (gmap.map_points_v == 0 || gmap.map_points_h == 0 || |
| 289 | ! | gmap.map_planes == 0) { |
| 290 | ! | AppendWarn(warn, "GainMap has invalid dimensions."); |
| 291 | ! | return 1.0; |
| 292 | } | |
| 293 | ! | if (gmap.map_spacing_h <= 0.0 || gmap.map_spacing_v <= 0.0) { |
| 294 | ! | AppendWarn(warn, "GainMap spacing is invalid."); |
| 295 | ! | return 1.0; |
| 296 | } | |
| 297 | ! | double fx = (static_cast<double>(x) - gmap.map_origin_h) / gmap.map_spacing_h; |
| 298 | ! | double fy = (static_cast<double>(y) - gmap.map_origin_v) / gmap.map_spacing_v; |
| 299 | ||
| 300 | ! | if (fx < 0.0) fx = 0.0; |
| 301 | ! | if (fy < 0.0) fy = 0.0; |
| 302 | ! | double max_x = static_cast<double>(gmap.map_points_h - 1); |
| 303 | ! | double max_y = static_cast<double>(gmap.map_points_v - 1); |
| 304 | ! | if (fx > max_x) fx = max_x; |
| 305 | ! | if (fy > max_y) fy = max_y; |
| 306 | ||
| 307 | ! | int x0 = static_cast<int>(std::floor(fx)); |
| 308 | ! | int y0 = static_cast<int>(std::floor(fy)); |
| 309 | ! | int x1 = std::min(x0 + 1, static_cast<int>(gmap.map_points_h - 1)); |
| 310 | ! | int y1 = std::min(y0 + 1, static_cast<int>(gmap.map_points_v - 1)); |
| 311 | ! | double tx = fx - static_cast<double>(x0); |
| 312 | ! | double ty = fy - static_cast<double>(y0); |
| 313 | ||
| 314 | ! | auto idx = [&](int gx, int gy, int gp) { |
| 315 | ! | return (static_cast<std::size_t>(gy) * |
| 316 | ! | static_cast<std::size_t>(gmap.map_points_h) + |
| 317 | ! | static_cast<std::size_t>(gx)) * |
| 318 | ! | static_cast<std::size_t>(gmap.map_planes) + |
| 319 | ! | static_cast<std::size_t>(gp); |
| 320 | }; | |
| 321 | ||
| 322 | ! | if (plane < 0 || plane >= static_cast<int>(gmap.map_planes)) { |
| 323 | ! | return 1.0; |
| 324 | } | |
| 325 | ||
| 326 | ! | float g00 = gmap.pixels[idx(x0, y0, plane)]; |
| 327 | ! | float g10 = gmap.pixels[idx(x1, y0, plane)]; |
| 328 | ! | float g01 = gmap.pixels[idx(x0, y1, plane)]; |
| 329 | ! | float g11 = gmap.pixels[idx(x1, y1, plane)]; |
| 330 | ||
| 331 | ! | double gx0 = g00 + (g10 - g00) * tx; |
| 332 | ! | double gx1 = g01 + (g11 - g01) * tx; |
| 333 | ! | return gx0 + (gx1 - gx0) * ty; |
| 334 | } | |
| 335 | ||
| 336 | ! | bool ApplyGainMaps(const std::vector<tinydng::GainMap>& gainmaps, |
| 337 | int width, | |
| 338 | int height, | |
| 339 | int spp, | |
| 340 | std::vector<double>* values, | |
| 341 | std::string* warn) { | |
| 342 | ! | if (!values || gainmaps.empty()) { |
| 343 | ! | return false; |
| 344 | } | |
| 345 | ||
| 346 | ! | bool applied = false; |
| 347 | ! | for (const auto& gmap : gainmaps) { |
| 348 | ! | if (gmap.pixels.empty()) { |
| 349 | ! | continue; |
| 350 | } | |
| 351 | ||
| 352 | ! | int top = static_cast<int>(gmap.top); |
| 353 | ! | int left = static_cast<int>(gmap.left); |
| 354 | ! | int bottom = static_cast<int>(gmap.bottom); |
| 355 | ! | int right = static_cast<int>(gmap.right); |
| 356 | ||
| 357 | ! | if (bottom <= top || right <= left) { |
| 358 | ! | top = 0; |
| 359 | ! | left = 0; |
| 360 | ! | bottom = height; |
| 361 | ! | right = width; |
| 362 | } | |
| 363 | ||
| 364 | ! | int plane_start = static_cast<int>(gmap.plane); |
| 365 | ! | int plane_count = static_cast<int>(gmap.planes); |
| 366 | ! | if (plane_count <= 0) { |
| 367 | ! | plane_start = 0; |
| 368 | ! | plane_count = spp; |
| 369 | } | |
| 370 | ||
| 371 | ! | for (int y = top; y < bottom; ++y) { |
| 372 | ! | if (y < 0 || y >= height) { |
| 373 | ! | continue; |
| 374 | } | |
| 375 | ! | for (int x = left; x < right; ++x) { |
| 376 | ! | if (x < 0 || x >= width) { |
| 377 | ! | continue; |
| 378 | } | |
| 379 | ! | for (int c = 0; c < spp; ++c) { |
| 380 | ! | if (c < plane_start || c >= plane_start + plane_count) { |
| 381 | ! | continue; |
| 382 | } | |
| 383 | ! | int plane = (gmap.map_planes == 1) |
| 384 | ! | ? 0 |
| 385 | : (c - plane_start); | |
| 386 | ! | double gain = SampleGainMap(gmap, x, y, plane, warn); |
| 387 | ! | std::size_t idx = (static_cast<std::size_t>(y) * |
| 388 | ! | static_cast<std::size_t>(width) + static_cast<std::size_t>(x)) * |
| 389 | ! | static_cast<std::size_t>(spp) + static_cast<std::size_t>(c); |
| 390 | ! | (*values)[idx] *= gain; |
| 391 | } | |
| 392 | } | |
| 393 | } | |
| 394 | ! | applied = true; |
| 395 | } | |
| 396 | ! | return applied; |
| 397 | } | |
| 398 | ||
| 399 | } // namespace | |
| 400 | ||
| 401 | // [[Rcpp::export]] | |
| 402 | 1x | Rcpp::List read_dng_cpp(const std::string& filename, |
| 403 | bool normalize = true, | |
| 404 | std::string pick = "largest") { | |
| 405 | 1x | std::vector<tinydng::FieldInfo> custom_fields; |
| 406 | 1x | std::vector<tinydng::DNGImage> images; |
| 407 | 1x | std::string warn; |
| 408 | 1x | std::string err; |
| 409 | ||
| 410 | 5x | auto add_custom_field = [&](int tag, tinydng::DataType type, const char* name) { |
| 411 | 5x | tinydng::FieldInfo field; |
| 412 | 5x | field.tag = tag; |
| 413 | 5x | field.type = type; |
| 414 | 5x | field.name = name; |
| 415 | 5x | custom_fields.push_back(field); |
| 416 | }; | |
| 417 | ||
| 418 | 1x | add_custom_field(kTagLinearizationTable, tinydng::TYPE_SHORT, |
| 419 | "LinearizationTable"); | |
| 420 | 1x | add_custom_field(kTagBaselineExposure, tinydng::TYPE_SRATIONAL, |
| 421 | "BaselineExposure"); | |
| 422 | 1x | add_custom_field(tinydng::TAG_EXPOSURE_TIME, tinydng::TYPE_RATIONAL, |
| 423 | "ExposureTime"); | |
| 424 | 1x | add_custom_field(tinydng::TAG_ISO, tinydng::TYPE_SHORT, "ISOSpeedRatings"); |
| 425 | 1x | add_custom_field(tinydng::TAG_F_NUMBER, tinydng::TYPE_RATIONAL, "FNumber"); |
| 426 | ||
| 427 | 1x | bool ok = tinydng::LoadDNG(filename.c_str(), custom_fields, &images, &warn, &err); |
| 428 | 1x | if (!ok) { |
| 429 | ! | throw std::runtime_error(err.empty() ? "Failed to load DNG." : err); |
| 430 | } | |
| 431 | ||
| 432 | 1x | std::string pick_lower = pick; |
| 433 | 1x | std::transform(pick_lower.begin(), pick_lower.end(), pick_lower.begin(), |
| 434 | 7x | [](unsigned char c) { return static_cast<char>(std::tolower(c)); }); |
| 435 | 1x | if (pick_lower != "largest") { |
| 436 | ! | throw std::runtime_error("Only pick = \"largest\" is supported."); |
| 437 | } | |
| 438 | ||
| 439 | 1x | std::size_t best_idx = images.size(); |
| 440 | 1x | std::size_t best_pixels = 0; |
| 441 | 2x | for (std::size_t i = 0; i < images.size(); ++i) { |
| 442 | 1x | const tinydng::DNGImage& img = images[i]; |
| 443 | 1x | if (img.data.empty()) { |
| 444 | ! | continue; |
| 445 | } | |
| 446 | 1x | std::size_t pixels = static_cast<std::size_t>(img.width) * |
| 447 | 1x | static_cast<std::size_t>(img.height); |
| 448 | 1x | if (pixels > best_pixels) { |
| 449 | 1x | best_pixels = pixels; |
| 450 | 1x | best_idx = i; |
| 451 | } | |
| 452 | } | |
| 453 | ||
| 454 | 1x | if (best_idx == images.size()) { |
| 455 | ! | std::string msg = "No DNG image data found."; |
| 456 | ! | if (!warn.empty()) { |
| 457 | ! | msg += " Warning: " + warn; |
| 458 | } | |
| 459 | ! | if (!err.empty()) { |
| 460 | ! | msg += " Error: " + err; |
| 461 | } | |
| 462 | ! | throw std::runtime_error(msg); |
| 463 | } | |
| 464 | ||
| 465 | 1x | const tinydng::DNGImage& image = images[best_idx]; |
| 466 | 1x | short orientation = image.orientation; |
| 467 | 1x | if (orientation <= 0 || orientation == 1) { |
| 468 | 2x | for (std::size_t i = 0; i < images.size(); ++i) { |
| 469 | 1x | short candidate = images[i].orientation; |
| 470 | 1x | if (candidate > 1 && candidate <= 8) { |
| 471 | ! | orientation = candidate; |
| 472 | ! | break; |
| 473 | } | |
| 474 | } | |
| 475 | } | |
| 476 | 1x | if (image.width <= 0 || image.height <= 0 || image.samples_per_pixel <= 0) { |
| 477 | ! | throw std::runtime_error("Invalid DNG image dimensions."); |
| 478 | } | |
| 479 | ||
| 480 | 1x | int width = image.width; |
| 481 | 1x | int height = image.height; |
| 482 | 1x | int spp = image.samples_per_pixel; |
| 483 | 1x | int bps = image.bits_per_sample; |
| 484 | 1x | bool processing = normalize; |
| 485 | ||
| 486 | 1x | std::string warn_out = warn; |
| 487 | 1x | bool linearization_present = false; |
| 488 | 1x | bool linearization_applied = false; |
| 489 | 1x | bool active_area_applied = false; |
| 490 | 1x | bool opcodes_present = !image.opcodelist2_gainmap.empty(); |
| 491 | 1x | bool opcodes_applied = false; |
| 492 | 1x | bool baseline_exposure_seen = false; |
| 493 | 1x | bool baseline_exposure_undone = false; |
| 494 | 1x | double baseline_exposure = NA_REAL; |
| 495 | 1x | double exposure_time = NA_REAL; |
| 496 | 1x | double iso = NA_REAL; |
| 497 | 1x | double f_number = NA_REAL; |
| 498 | 1x | bool exposure_normalized_applied = false; |
| 499 | ||
| 500 | 1x | std::vector<uint16_t> linearization_table; |
| 501 | const tinydng::FieldData* linear_field = | |
| 502 | 1x | FindCustomField(image, kTagLinearizationTable); |
| 503 | 1x | if (!linear_field) { |
| 504 | 1x | linear_field = FindCustomFieldAny(images, kTagLinearizationTable, nullptr); |
| 505 | } | |
| 506 | 1x | if (linear_field) { |
| 507 | ! | linearization_present = true; |
| 508 | ! | linearization_table = ExtractLinearizationTable(*linear_field); |
| 509 | } | |
| 510 | ||
| 511 | const tinydng::FieldData* baseline_field = | |
| 512 | 1x | FindCustomField(image, kTagBaselineExposure); |
| 513 | 1x | if (!baseline_field) { |
| 514 | 1x | baseline_field = FindCustomFieldAny(images, kTagBaselineExposure, nullptr); |
| 515 | } | |
| 516 | 1x | if (baseline_field) { |
| 517 | ! | double value = 0.0; |
| 518 | ! | if (ReadCustomRational(*baseline_field, &value, true)) { |
| 519 | ! | baseline_exposure = value; |
| 520 | ! | baseline_exposure_seen = true; |
| 521 | } else { | |
| 522 | ! | AppendWarn(&warn_out, "BaselineExposure tag present but could not be read."); |
| 523 | } | |
| 524 | } | |
| 525 | ||
| 526 | const tinydng::FieldData* exposure_field = | |
| 527 | 1x | FindCustomField(image, tinydng::TAG_EXPOSURE_TIME); |
| 528 | 1x | if (!exposure_field) { |
| 529 | 1x | exposure_field = FindCustomFieldAny(images, tinydng::TAG_EXPOSURE_TIME, |
| 530 | nullptr); | |
| 531 | } | |
| 532 | 1x | if (exposure_field) { |
| 533 | ! | double value = 0.0; |
| 534 | ! | if (ReadCustomRational(*exposure_field, &value, false)) { |
| 535 | ! | exposure_time = value; |
| 536 | } else { | |
| 537 | ! | AppendWarn(&warn_out, "ExposureTime tag present but could not be read."); |
| 538 | } | |
| 539 | } | |
| 540 | ||
| 541 | const tinydng::FieldData* iso_field = | |
| 542 | 1x | FindCustomField(image, tinydng::TAG_ISO); |
| 543 | 1x | if (!iso_field) { |
| 544 | 1x | iso_field = FindCustomFieldAny(images, tinydng::TAG_ISO, nullptr); |
| 545 | } | |
| 546 | 1x | if (iso_field) { |
| 547 | ! | uint16_t value = 0; |
| 548 | ! | if (ReadCustomShort(*iso_field, &value)) { |
| 549 | ! | iso = static_cast<double>(value); |
| 550 | } else { | |
| 551 | ! | AppendWarn(&warn_out, "ISOSpeedRatings tag present but could not be read."); |
| 552 | } | |
| 553 | } | |
| 554 | ||
| 555 | const tinydng::FieldData* fnum_field = | |
| 556 | 1x | FindCustomField(image, tinydng::TAG_F_NUMBER); |
| 557 | 1x | if (!fnum_field) { |
| 558 | 1x | fnum_field = FindCustomFieldAny(images, tinydng::TAG_F_NUMBER, nullptr); |
| 559 | } | |
| 560 | 1x | if (fnum_field) { |
| 561 | ! | double value = 0.0; |
| 562 | ! | if (ReadCustomRational(*fnum_field, &value, false)) { |
| 563 | ! | f_number = value; |
| 564 | } | |
| 565 | } | |
| 566 | ||
| 567 | 1x | int bytes_per_sample = 0; |
| 568 | 1x | if (image.sample_format == tinydng::SAMPLEFORMAT_UINT) { |
| 569 | 1x | if (bps <= 8) { |
| 570 | ! | bytes_per_sample = 1; |
| 571 | 1x | } else if (bps <= 16) { |
| 572 | 1x | bytes_per_sample = 2; |
| 573 | } else { | |
| 574 | ! | throw std::runtime_error("Unsupported integer bit depth."); |
| 575 | } | |
| 576 | ! | } else if (image.sample_format == tinydng::SAMPLEFORMAT_IEEEFP) { |
| 577 | ! | if (bps == 32) { |
| 578 | ! | bytes_per_sample = 4; |
| 579 | } else { | |
| 580 | ! | throw std::runtime_error("Unsupported float bit depth."); |
| 581 | } | |
| 582 | } else { | |
| 583 | ! | throw std::runtime_error("Unsupported sample format."); |
| 584 | } | |
| 585 | ||
| 586 | 1x | std::size_t n_samples = static_cast<std::size_t>(width) * |
| 587 | 1x | static_cast<std::size_t>(height) * static_cast<std::size_t>(spp); |
| 588 | 1x | if (image.data.size() < n_samples * static_cast<std::size_t>(bytes_per_sample)) { |
| 589 | ! | throw std::runtime_error("DNG data buffer is smaller than expected."); |
| 590 | } | |
| 591 | ||
| 592 | 2x | std::vector<double> values(n_samples); |
| 593 | ||
| 594 | 1x | std::vector<double> black_levels(static_cast<std::size_t>(spp), 0.0); |
| 595 | std::vector<double> white_levels(static_cast<std::size_t>(spp), | |
| 596 | 1x | DefaultWhiteLevel(bps)); |
| 597 | 1x | double default_white = DefaultWhiteLevel(bps); |
| 598 | 2x | for (int c = 0; c < spp; ++c) { |
| 599 | 1x | if (c < 4) { |
| 600 | 1x | double black = static_cast<double>(image.black_level[c]); |
| 601 | 1x | double white = static_cast<double>(image.white_level[c]); |
| 602 | 1x | if (white > black) { |
| 603 | 1x | black_levels[c] = black; |
| 604 | 1x | white_levels[c] = white; |
| 605 | } else { | |
| 606 | ! | black_levels[c] = 0.0; |
| 607 | ! | white_levels[c] = default_white; |
| 608 | } | |
| 609 | } else { | |
| 610 | ! | black_levels[c] = 0.0; |
| 611 | ! | white_levels[c] = default_white; |
| 612 | } | |
| 613 | } | |
| 614 | ||
| 615 | // Processing order: linearization -> black/white normalize -> gain map -> | |
| 616 | // baseline exposure handling -> active area crop -> exposure normalization. | |
| 617 | 1x | const unsigned char* data = image.data.data(); |
| 618 | 1x | bool linearization_warned = false; |
| 619 | 17x | for (int y = 0; y < height; ++y) { |
| 620 | 272x | for (int x = 0; x < width; ++x) { |
| 621 | 512x | for (int c = 0; c < spp; ++c) { |
| 622 | 256x | std::size_t sample_idx = (static_cast<std::size_t>(y) * |
| 623 | 256x | static_cast<std::size_t>(width) + static_cast<std::size_t>(x)) * |
| 624 | 256x | static_cast<std::size_t>(spp) + static_cast<std::size_t>(c); |
| 625 | 256x | std::size_t offset = sample_idx * static_cast<std::size_t>(bytes_per_sample); |
| 626 | ||
| 627 | 256x | double raw_value = 0.0; |
| 628 | 256x | uint32_t int_value = 0; |
| 629 | 256x | if (image.sample_format == tinydng::SAMPLEFORMAT_UINT) { |
| 630 | 256x | if (bytes_per_sample == 1) { |
| 631 | ! | int_value = static_cast<uint32_t>(data[offset]); |
| 632 | ! | if (bps < 8) { |
| 633 | ! | int_value &= ((1u << bps) - 1u); |
| 634 | } | |
| 635 | } else { | |
| 636 | 256x | int_value = static_cast<uint32_t>(data[offset]) | |
| 637 | 256x | (static_cast<uint32_t>(data[offset + 1]) << 8); |
| 638 | 256x | if (bps < 16) { |
| 639 | ! | int_value &= ((1u << bps) - 1u); |
| 640 | } | |
| 641 | } | |
| 642 | 256x | raw_value = static_cast<double>(int_value); |
| 643 | 256x | if (processing && linearization_present && |
| 644 | ! | linearization_table.size() > 1) { |
| 645 | ! | if (int_value < linearization_table.size()) { |
| 646 | ! | raw_value = static_cast<double>(linearization_table[int_value]); |
| 647 | ! | linearization_applied = true; |
| 648 | ! | } else if (!linearization_warned) { |
| 649 | ! | AppendWarn(&warn_out, |
| 650 | ! | "Linearization table is smaller than sample range."); |
| 651 | ! | linearization_warned = true; |
| 652 | } | |
| 653 | } | |
| 654 | } else { | |
| 655 | ! | float value = 0.0f; |
| 656 | ! | std::memcpy(&value, data + offset, sizeof(float)); |
| 657 | ! | raw_value = static_cast<double>(value); |
| 658 | ! | if (processing && linearization_present && !linearization_warned) { |
| 659 | ! | AppendWarn(&warn_out, |
| 660 | ! | "Linearization table present but samples are float."); |
| 661 | ! | linearization_warned = true; |
| 662 | } | |
| 663 | } | |
| 664 | ||
| 665 | 256x | double out_value = raw_value; |
| 666 | 256x | if (processing) { |
| 667 | 256x | double denom = white_levels[c] - black_levels[c]; |
| 668 | 256x | if (denom <= 0.0) { |
| 669 | ! | out_value = 0.0; |
| 670 | } else { | |
| 671 | 256x | out_value = (raw_value - black_levels[c]) / denom; |
| 672 | } | |
| 673 | 256x | out_value = Clamp01(out_value); |
| 674 | } | |
| 675 | ||
| 676 | 256x | values[sample_idx] = out_value; |
| 677 | } | |
| 678 | } | |
| 679 | } | |
| 680 | ||
| 681 | 1x | if (linearization_present && !linearization_applied && processing && |
| 682 | ! | linearization_table.size() <= 1) { |
| 683 | ! | AppendWarn(&warn_out, |
| 684 | ! | "Linearization table present but not available for use."); |
| 685 | } | |
| 686 | ||
| 687 | 1x | if (processing && opcodes_present) { |
| 688 | ! | opcodes_applied = ApplyGainMaps(image.opcodelist2_gainmap, width, height, |
| 689 | spp, &values, &warn_out); | |
| 690 | ! | if (!opcodes_applied) { |
| 691 | ! | AppendWarn(&warn_out, "OpcodeList2 gain maps present but not applied."); |
| 692 | } | |
| 693 | 1x | } else if (opcodes_present && !processing) { |
| 694 | ! | AppendWarn(&warn_out, "OpcodeList2 gain maps present but skipped."); |
| 695 | } | |
| 696 | ||
| 697 | 1x | if (baseline_exposure_seen && baseline_exposure != 0.0) { |
| 698 | ! | AppendWarn(&warn_out, |
| 699 | ! | "BaselineExposure present; value not applied or undone."); |
| 700 | } | |
| 701 | ||
| 702 | 1x | if (image.has_active_area) { |
| 703 | int active_area_vals[4] = { | |
| 704 | ! | image.active_area[0], |
| 705 | ! | image.active_area[1], |
| 706 | ! | image.active_area[2], |
| 707 | ! | image.active_area[3] |
| 708 | }; | |
| 709 | ! | std::vector<double> cropped; |
| 710 | ! | int crop_w = width; |
| 711 | ! | int crop_h = height; |
| 712 | ! | if (ApplyActiveAreaCrop(values, width, height, spp, active_area_vals, |
| 713 | &cropped, &crop_w, &crop_h)) { | |
| 714 | ! | values.swap(cropped); |
| 715 | ! | width = crop_w; |
| 716 | ! | height = crop_h; |
| 717 | ! | active_area_applied = true; |
| 718 | } | |
| 719 | } | |
| 720 | ||
| 721 | 1x | bool iso_ok = !Rcpp::NumericVector::is_na(iso) && iso > 0.0; |
| 722 | 1x | bool exposure_ok = !Rcpp::NumericVector::is_na(exposure_time) && |
| 723 | ! | exposure_time > 0.0; |
| 724 | 1x | if (iso_ok && exposure_ok) { |
| 725 | ! | if (processing) { |
| 726 | ! | double scale = (100.0 / iso) * (1.0 / exposure_time); |
| 727 | ! | for (double& v : values) { |
| 728 | ! | v *= scale; |
| 729 | } | |
| 730 | ! | exposure_normalized_applied = true; |
| 731 | } else { | |
| 732 | ! | AppendWarn(&warn_out, |
| 733 | ! | "Exposure normalization skipped because normalize is FALSE."); |
| 734 | } | |
| 735 | } else { | |
| 736 | 1x | AppendWarn(&warn_out, |
| 737 | 3x | "Exposure normalization skipped due to missing ISO or ExposureTime."); |
| 738 | } | |
| 739 | ||
| 740 | 1x | std::vector<double> r_values = RowMajorToR(values, width, height, spp); |
| 741 | 1x | Rcpp::NumericVector pixels(r_values.begin(), r_values.end()); |
| 742 | 1x | if (spp == 1) { |
| 743 | 1x | Rcpp::IntegerVector dim = Rcpp::IntegerVector::create(height, width); |
| 744 | 1x | pixels.attr("dim") = dim; |
| 745 | } else { | |
| 746 | ! | Rcpp::IntegerVector dim = Rcpp::IntegerVector::create(height, width, spp); |
| 747 | ! | pixels.attr("dim") = dim; |
| 748 | } | |
| 749 | ||
| 750 | 1x | Rcpp::IntegerMatrix cfa_pattern(2, 2); |
| 751 | 1x | cfa_pattern(0, 0) = image.cfa_pattern[0][0]; |
| 752 | 1x | cfa_pattern(0, 1) = image.cfa_pattern[0][1]; |
| 753 | 1x | cfa_pattern(1, 0) = image.cfa_pattern[1][0]; |
| 754 | 1x | cfa_pattern(1, 1) = image.cfa_pattern[1][1]; |
| 755 | ||
| 756 | 1x | Rcpp::IntegerVector cfa_plane_color(4); |
| 757 | 5x | for (int i = 0; i < 4; ++i) { |
| 758 | 4x | cfa_plane_color[i] = static_cast<int>( |
| 759 | 4x | static_cast<unsigned char>(image.cfa_plane_color[i])); |
| 760 | } | |
| 761 | ||
| 762 | 1x | Rcpp::IntegerVector black_level(4); |
| 763 | 1x | Rcpp::IntegerVector white_level(4); |
| 764 | 5x | for (int i = 0; i < 4; ++i) { |
| 765 | 4x | black_level[i] = image.black_level[i]; |
| 766 | 4x | white_level[i] = image.white_level[i]; |
| 767 | } | |
| 768 | ||
| 769 | 1x | Rcpp::NumericVector as_shot_neutral(3, NA_REAL); |
| 770 | 4x | for (int i = 0; i < 3; ++i) { |
| 771 | 3x | if (image.has_as_shot_neutral) { |
| 772 | ! | as_shot_neutral[i] = image.as_shot_neutral[i]; |
| 773 | } | |
| 774 | } | |
| 775 | ||
| 776 | 1x | Rcpp::NumericVector analog_balance(3, NA_REAL); |
| 777 | 4x | for (int i = 0; i < 3; ++i) { |
| 778 | 3x | if (image.has_analog_balance) { |
| 779 | ! | analog_balance[i] = image.analog_balance[i]; |
| 780 | } | |
| 781 | } | |
| 782 | ||
| 783 | 1x | Rcpp::NumericVector color_matrix1(9); |
| 784 | 1x | Rcpp::NumericVector color_matrix2(9); |
| 785 | 1x | int idx = 0; |
| 786 | 4x | for (int r = 0; r < 3; ++r) { |
| 787 | 12x | for (int c = 0; c < 3; ++c) { |
| 788 | 9x | color_matrix1[idx] = image.color_matrix1[r][c]; |
| 789 | 9x | color_matrix2[idx] = image.color_matrix2[r][c]; |
| 790 | 9x | idx++; |
| 791 | } | |
| 792 | } | |
| 793 | ||
| 794 | 1x | Rcpp::IntegerVector active_area(4); |
| 795 | 5x | for (int i = 0; i < 4; ++i) { |
| 796 | 4x | active_area[i] = image.has_active_area ? image.active_area[i] : NA_INTEGER; |
| 797 | } | |
| 798 | ||
| 799 | Rcpp::List meta = Rcpp::List::create( | |
| 800 | 2x | Rcpp::Named("width") = width, |
| 801 | 2x | Rcpp::Named("height") = height, |
| 802 | 3x | Rcpp::Named("samples_per_pixel") = image.samples_per_pixel, |
| 803 | 3x | Rcpp::Named("bits_per_sample") = image.bits_per_sample, |
| 804 | 3x | Rcpp::Named("bits_per_sample_original") = image.bits_per_sample_original, |
| 805 | 3x | Rcpp::Named("sample_format") = static_cast<int>(image.sample_format), |
| 806 | 2x | Rcpp::Named("cfa_pattern") = cfa_pattern, |
| 807 | 2x | Rcpp::Named("cfa_plane_color") = cfa_plane_color, |
| 808 | 3x | Rcpp::Named("cfa_layout") = image.cfa_layout, |
| 809 | 2x | Rcpp::Named("black_level") = black_level, |
| 810 | 2x | Rcpp::Named("white_level") = white_level, |
| 811 | 2x | Rcpp::Named("as_shot_neutral") = as_shot_neutral, |
| 812 | 3x | Rcpp::Named("has_as_shot_neutral") = image.has_as_shot_neutral, |
| 813 | 2x | Rcpp::Named("analog_balance") = analog_balance, |
| 814 | 3x | Rcpp::Named("has_analog_balance") = image.has_analog_balance, |
| 815 | 2x | Rcpp::Named("color_matrix1") = color_matrix1, |
| 816 | 2x | Rcpp::Named("color_matrix2") = color_matrix2, |
| 817 | 3x | Rcpp::Named("orientation") = static_cast<int>(orientation), |
| 818 | 2x | Rcpp::Named("active_area") = active_area, |
| 819 | 3x | Rcpp::Named("has_active_area") = image.has_active_area, |
| 820 | 2x | Rcpp::Named("active_area_applied") = active_area_applied, |
| 821 | 2x | Rcpp::Named("linearization_present") = linearization_present, |
| 822 | 2x | Rcpp::Named("linearization_applied") = linearization_applied, |
| 823 | 2x | Rcpp::Named("opcodes_present") = opcodes_present, |
| 824 | 2x | Rcpp::Named("opcodes_applied") = opcodes_applied, |
| 825 | 2x | Rcpp::Named("baseline_exposure") = baseline_exposure, |
| 826 | 2x | Rcpp::Named("baseline_exposure_seen") = baseline_exposure_seen, |
| 827 | 2x | Rcpp::Named("baseline_exposure_undone") = baseline_exposure_undone, |
| 828 | 2x | Rcpp::Named("iso") = iso, |
| 829 | 2x | Rcpp::Named("exposure_time") = exposure_time, |
| 830 | 2x | Rcpp::Named("f_number") = f_number, |
| 831 | 3x | Rcpp::Named("exposure_normalized_applied") = exposure_normalized_applied |
| 832 | ); | |
| 833 | ||
| 834 | return Rcpp::List::create( | |
| 835 | 2x | Rcpp::Named("pixels") = pixels, |
| 836 | 2x | Rcpp::Named("meta") = meta, |
| 837 | 2x | Rcpp::Named("warn") = warn_out |
| 838 | ); | |
| 839 | } | |
| 840 | ||
| 841 | // [[Rcpp::export]] | |
| 842 | 1x | Rcpp::NumericVector dng_apply_active_area_cpp(Rcpp::NumericVector pixels, |
| 843 | Rcpp::IntegerVector active_area) { | |
| 844 | 1x | Rcpp::IntegerVector dims = pixels.attr("dim"); |
| 845 | 1x | if (dims.size() < 2) { |
| 846 | ! | Rcpp::stop("pixels must have dim."); |
| 847 | } | |
| 848 | 1x | int height = dims[0]; |
| 849 | 1x | int width = dims[1]; |
| 850 | 1x | int spp = (dims.size() >= 3) ? dims[2] : 1; |
| 851 | 1x | if (active_area.size() < 4) { |
| 852 | ! | Rcpp::stop("active_area must have 4 values."); |
| 853 | } | |
| 854 | ||
| 855 | 1x | int area[4] = {active_area[0], active_area[1], active_area[2], active_area[3]}; |
| 856 | 1x | std::vector<double> row_major = RToRowMajor(pixels, width, height, spp); |
| 857 | 1x | std::vector<double> cropped; |
| 858 | 1x | int crop_w = width; |
| 859 | 1x | int crop_h = height; |
| 860 | 1x | if (!ApplyActiveAreaCrop(row_major, width, height, spp, area, &cropped, |
| 861 | &crop_w, &crop_h)) { | |
| 862 | ! | return pixels; |
| 863 | } | |
| 864 | ||
| 865 | 1x | std::vector<double> out = RowMajorToR(cropped, crop_w, crop_h, spp); |
| 866 | 1x | Rcpp::NumericVector out_vec(out.begin(), out.end()); |
| 867 | 1x | if (spp == 1) { |
| 868 | 3x | out_vec.attr("dim") = Rcpp::IntegerVector::create(crop_h, crop_w); |
| 869 | } else { | |
| 870 | ! | out_vec.attr("dim") = Rcpp::IntegerVector::create(crop_h, crop_w, spp); |
| 871 | } | |
| 872 | 1x | return out_vec; |
| 873 | } | |
| 874 | ||
| 875 | // [[Rcpp::export]] | |
| 876 | 1x | Rcpp::NumericVector dng_exposure_normalize_cpp(Rcpp::NumericVector pixels, |
| 877 | double iso, | |
| 878 | double exposure_time) { | |
| 879 | 1x | if (iso <= 0.0 || exposure_time <= 0.0) { |
| 880 | ! | Rcpp::stop("iso and exposure_time must be positive."); |
| 881 | } | |
| 882 | 1x | Rcpp::IntegerVector dims = pixels.attr("dim"); |
| 883 | 1x | if (dims.size() < 2) { |
| 884 | ! | Rcpp::stop("pixels must have dim."); |
| 885 | } | |
| 886 | 1x | int height = dims[0]; |
| 887 | 1x | int width = dims[1]; |
| 888 | 1x | int spp = (dims.size() >= 3) ? dims[2] : 1; |
| 889 | 1x | double scale = (100.0 / iso) * (1.0 / exposure_time); |
| 890 | ||
| 891 | 1x | std::vector<double> row_major = RToRowMajor(pixels, width, height, spp); |
| 892 | 6x | for (double& v : row_major) { |
| 893 | 4x | v *= scale; |
| 894 | } | |
| 895 | 1x | std::vector<double> out = RowMajorToR(row_major, width, height, spp); |
| 896 | 1x | Rcpp::NumericVector out_vec(out.begin(), out.end()); |
| 897 | 1x | out_vec.attr("dim") = dims; |
| 898 | 1x | return out_vec; |
| 899 | } | |
| 900 | ||
| 901 | // [[Rcpp::export]] | |
| 902 | 1x | Rcpp::NumericVector dng_undo_baseline_exposure_cpp(Rcpp::NumericVector pixels, |
| 903 | double baseline_exposure) { | |
| 904 | 1x | Rcpp::IntegerVector dims = pixels.attr("dim"); |
| 905 | 1x | if (dims.size() < 2) { |
| 906 | ! | Rcpp::stop("pixels must have dim."); |
| 907 | } | |
| 908 | 1x | int height = dims[0]; |
| 909 | 1x | int width = dims[1]; |
| 910 | 1x | int spp = (dims.size() >= 3) ? dims[2] : 1; |
| 911 | 1x | double scale = std::pow(2.0, baseline_exposure); |
| 912 | 1x | if (scale == 0.0) { |
| 913 | ! | Rcpp::stop("baseline_exposure scale is invalid."); |
| 914 | } | |
| 915 | ||
| 916 | 1x | std::vector<double> row_major = RToRowMajor(pixels, width, height, spp); |
| 917 | 6x | for (double& v : row_major) { |
| 918 | 4x | v /= scale; |
| 919 | } | |
| 920 | 1x | std::vector<double> out = RowMajorToR(row_major, width, height, spp); |
| 921 | 1x | Rcpp::NumericVector out_vec(out.begin(), out.end()); |
| 922 | 1x | out_vec.attr("dim") = dims; |
| 923 | 1x | return out_vec; |
| 924 | } | |
| 925 | ||
| 926 | // [[Rcpp::export]] | |
| 927 | 1x | bool write_dng_cpp(const std::string& filename, |
| 928 | SEXP pixels, | |
| 929 | Rcpp::List meta, | |
| 930 | int bitdepth = 16, | |
| 931 | bool compress = true) { | |
| 932 | 1x | if (!Rf_isNumeric(pixels)) { |
| 933 | ! | Rcpp::stop("pixels must be numeric."); |
| 934 | } | |
| 935 | ||
| 936 | 1x | Rcpp::RObject pix_obj(pixels); |
| 937 | 1x | if (bitdepth < 1 || bitdepth > 16) { |
| 938 | ! | Rcpp::stop("bitdepth must be between 1 and 16."); |
| 939 | } | |
| 940 | ||
| 941 | 1x | Rcpp::NumericVector pix = Rcpp::as<Rcpp::NumericVector>(pix_obj); |
| 942 | 1x | Rcpp::IntegerVector dims = pix.attr("dim"); |
| 943 | 1x | if (dims.size() == 0) { |
| 944 | ! | Rcpp::stop("pixels must be a matrix or 3D array."); |
| 945 | } | |
| 946 | ||
| 947 | 1x | int height = dims[0]; |
| 948 | 1x | int width = dims[1]; |
| 949 | 1x | int spp = 1; |
| 950 | 1x | bool is_mosaic = false; |
| 951 | ||
| 952 | 1x | if (dims.size() == 2) { |
| 953 | 1x | spp = 1; |
| 954 | 1x | is_mosaic = true; |
| 955 | ! | } else if (dims.size() == 3 && dims[2] == 3) { |
| 956 | ! | spp = 3; |
| 957 | } else { | |
| 958 | ! | Rcpp::stop("pixels must have dim (h,w) or (h,w,3)."); |
| 959 | } | |
| 960 | ||
| 961 | 1x | std::size_t n_samples = static_cast<std::size_t>(width) * |
| 962 | 1x | static_cast<std::size_t>(height) * static_cast<std::size_t>(spp); |
| 963 | 1x | std::vector<uint16_t> buf(n_samples); |
| 964 | 1x | double max_val = std::pow(2.0, static_cast<double>(bitdepth)) - 1.0; |
| 965 | ||
| 966 | 17x | for (int y = 0; y < height; ++y) { |
| 967 | 272x | for (int x = 0; x < width; ++x) { |
| 968 | 512x | for (int c = 0; c < spp; ++c) { |
| 969 | 256x | std::size_t r_idx = static_cast<std::size_t>(y) + |
| 970 | 256x | static_cast<std::size_t>(height) * |
| 971 | 256x | (static_cast<std::size_t>(x) + static_cast<std::size_t>(width) * |
| 972 | 256x | static_cast<std::size_t>(c)); |
| 973 | ||
| 974 | 256x | double v = pix[r_idx]; |
| 975 | 256x | if (Rcpp::NumericVector::is_na(v)) { |
| 976 | ! | v = 0.0; |
| 977 | } | |
| 978 | 256x | v = Clamp01(v); |
| 979 | 256x | uint16_t q = static_cast<uint16_t>(std::lround(v * max_val)); |
| 980 | ||
| 981 | 256x | std::size_t sample_idx = (static_cast<std::size_t>(y) * |
| 982 | 256x | static_cast<std::size_t>(width) + static_cast<std::size_t>(x)) * |
| 983 | 256x | static_cast<std::size_t>(spp) + static_cast<std::size_t>(c); |
| 984 | 256x | buf[sample_idx] = q; |
| 985 | } | |
| 986 | } | |
| 987 | } | |
| 988 | ||
| 989 | 1x | tinydngwriter::DNGImage dng_image; |
| 990 | 1x | dng_image.SetBigEndian(false); |
| 991 | 1x | if (!dng_image.SetSubfileType(false, false, false)) { |
| 992 | ! | Rcpp::stop("Failed to set DNG SubfileType."); |
| 993 | } | |
| 994 | 1x | if (!dng_image.SetImageWidth(static_cast<unsigned int>(width)) || |
| 995 | 2x | !dng_image.SetImageLength(static_cast<unsigned int>(height)) || |
| 996 | 1x | !dng_image.SetRowsPerStrip(static_cast<unsigned int>(height))) { |
| 997 | ! | Rcpp::stop("Failed to set DNG image dimensions."); |
| 998 | } | |
| 999 | 1x | if (!dng_image.SetSamplesPerPixel(static_cast<unsigned short>(spp))) { |
| 1000 | ! | Rcpp::stop("Failed to set DNG samples per pixel."); |
| 1001 | } | |
| 1002 | ||
| 1003 | std::vector<unsigned short> bps(static_cast<std::size_t>(spp), | |
| 1004 | 1x | static_cast<unsigned short>(bitdepth)); |
| 1005 | 1x | if (!dng_image.SetBitsPerSample(static_cast<unsigned int>(spp), bps.data())) { |
| 1006 | ! | Rcpp::stop("Failed to set DNG bits per sample."); |
| 1007 | } | |
| 1008 | ||
| 1009 | 1x | if (!dng_image.SetPlanarConfig(tinydngwriter::PLANARCONFIG_CONTIG)) { |
| 1010 | ! | Rcpp::stop("Failed to set DNG planar configuration."); |
| 1011 | } | |
| 1012 | ||
| 1013 | 1x | if (is_mosaic) { |
| 1014 | 1x | if (!dng_image.SetPhotometric(tinydngwriter::PHOTOMETRIC_CFA)) { |
| 1015 | ! | Rcpp::stop("Failed to set DNG photometric interpretation."); |
| 1016 | } | |
| 1017 | 1x | if (!dng_image.SetCFARepeatPatternDim(2, 2)) { |
| 1018 | ! | Rcpp::stop("Failed to set CFA repeat pattern."); |
| 1019 | } | |
| 1020 | ||
| 1021 | 1x | unsigned char cfa_vals[4] = {0, 1, 1, 2}; |
| 1022 | 1x | if (HasListElement(meta, "cfa_pattern")) { |
| 1023 | 1x | Rcpp::IntegerMatrix cfa = Rcpp::as<Rcpp::IntegerMatrix>(meta["cfa_pattern"]); |
| 1024 | 1x | if (cfa.nrow() == 2 && cfa.ncol() == 2) { |
| 1025 | 1x | cfa_vals[0] = static_cast<unsigned char>(cfa(0, 0)); |
| 1026 | 1x | cfa_vals[1] = static_cast<unsigned char>(cfa(0, 1)); |
| 1027 | 1x | cfa_vals[2] = static_cast<unsigned char>(cfa(1, 0)); |
| 1028 | 1x | cfa_vals[3] = static_cast<unsigned char>(cfa(1, 1)); |
| 1029 | } | |
| 1030 | } | |
| 1031 | ||
| 1032 | 1x | if (!dng_image.SetCFAPattern(4, cfa_vals)) { |
| 1033 | ! | Rcpp::stop("Failed to set CFA pattern."); |
| 1034 | } | |
| 1035 | } else { | |
| 1036 | ! | if (!dng_image.SetPhotometric(tinydngwriter::PHOTOMETRIC_RGB)) { |
| 1037 | ! | Rcpp::stop("Failed to set DNG photometric interpretation."); |
| 1038 | } | |
| 1039 | } | |
| 1040 | ||
| 1041 | 1x | if (HasListElement(meta, "black_level")) { |
| 1042 | 1x | Rcpp::NumericVector black = GetNumericVector(meta, "black_level"); |
| 1043 | 1x | if (black.size() > 0) { |
| 1044 | 1x | std::vector<unsigned short> black_vals(static_cast<std::size_t>(black.size())); |
| 1045 | 5x | for (R_xlen_t i = 0; i < black.size(); ++i) { |
| 1046 | 4x | double v = black[i]; |
| 1047 | 4x | if (Rcpp::NumericVector::is_na(v)) v = 0.0; |
| 1048 | 4x | if (v < 0.0) v = 0.0; |
| 1049 | 4x | if (v > max_val) v = max_val; |
| 1050 | 4x | black_vals[static_cast<std::size_t>(i)] = static_cast<unsigned short>(v); |
| 1051 | } | |
| 1052 | 1x | if (black.size() == 4) { |
| 1053 | 1x | dng_image.SetBlackLevelRepeatDim(2, 2); |
| 1054 | } | |
| 1055 | 1x | dng_image.SetBlackLevel(static_cast<unsigned int>(black_vals.size()), |
| 1056 | 1x | black_vals.data()); |
| 1057 | } | |
| 1058 | } | |
| 1059 | ||
| 1060 | 1x | if (HasListElement(meta, "white_level")) { |
| 1061 | 1x | Rcpp::NumericVector white = GetNumericVector(meta, "white_level"); |
| 1062 | 1x | if (white.size() > 0) { |
| 1063 | 1x | std::vector<double> white_vals(static_cast<std::size_t>(white.size())); |
| 1064 | 5x | for (R_xlen_t i = 0; i < white.size(); ++i) { |
| 1065 | 4x | double v = white[i]; |
| 1066 | 4x | if (Rcpp::NumericVector::is_na(v)) v = max_val; |
| 1067 | 4x | if (v < 0.0) v = 0.0; |
| 1068 | 4x | if (v > max_val) v = max_val; |
| 1069 | 4x | white_vals[static_cast<std::size_t>(i)] = v; |
| 1070 | } | |
| 1071 | 1x | dng_image.SetWhiteLevelRational(static_cast<unsigned int>(white_vals.size()), |
| 1072 | 1x | white_vals.data()); |
| 1073 | } | |
| 1074 | } | |
| 1075 | ||
| 1076 | 1x | bool allow_as_shot = true; |
| 1077 | 1x | if (HasListElement(meta, "has_as_shot_neutral")) { |
| 1078 | Rcpp::LogicalVector has_as_shot = Rcpp::as<Rcpp::LogicalVector>( | |
| 1079 | ! | meta["has_as_shot_neutral"]); |
| 1080 | ! | allow_as_shot = has_as_shot.size() > 0 && has_as_shot[0] == TRUE; |
| 1081 | } | |
| 1082 | 1x | if (allow_as_shot && HasListElement(meta, "as_shot_neutral")) { |
| 1083 | ! | Rcpp::NumericVector as_shot = GetNumericVector(meta, "as_shot_neutral"); |
| 1084 | ! | if (!HasNaNumeric(as_shot, 3)) { |
| 1085 | ! | dng_image.SetAsShotNeutral(3, as_shot.begin()); |
| 1086 | } | |
| 1087 | } | |
| 1088 | ||
| 1089 | 1x | if (HasListElement(meta, "color_matrix1")) { |
| 1090 | ! | Rcpp::NumericVector cm1 = GetNumericVector(meta, "color_matrix1"); |
| 1091 | ! | if (!HasNaNumeric(cm1, 9)) { |
| 1092 | ! | dng_image.SetColorMatrix1(3, cm1.begin()); |
| 1093 | } | |
| 1094 | } | |
| 1095 | ||
| 1096 | 1x | if (HasListElement(meta, "color_matrix2")) { |
| 1097 | ! | Rcpp::NumericVector cm2 = GetNumericVector(meta, "color_matrix2"); |
| 1098 | ! | if (!HasNaNumeric(cm2, 9)) { |
| 1099 | ! | dng_image.SetColorMatrix2(3, cm2.begin()); |
| 1100 | } | |
| 1101 | } | |
| 1102 | ||
| 1103 | 1x | bool allow_analog_balance = true; |
| 1104 | 1x | if (HasListElement(meta, "has_analog_balance")) { |
| 1105 | Rcpp::LogicalVector has_analog = Rcpp::as<Rcpp::LogicalVector>( | |
| 1106 | ! | meta["has_analog_balance"]); |
| 1107 | ! | allow_analog_balance = has_analog.size() > 0 && has_analog[0] == TRUE; |
| 1108 | } | |
| 1109 | 1x | if (allow_analog_balance && HasListElement(meta, "analog_balance")) { |
| 1110 | ! | Rcpp::NumericVector ab = GetNumericVector(meta, "analog_balance"); |
| 1111 | ! | if (!HasNaNumeric(ab, 3)) { |
| 1112 | ! | dng_image.SetAnalogBalance(3, ab.begin()); |
| 1113 | } | |
| 1114 | } | |
| 1115 | ||
| 1116 | 1x | bool allow_active_area = true; |
| 1117 | 1x | if (HasListElement(meta, "has_active_area")) { |
| 1118 | Rcpp::LogicalVector has_active = Rcpp::as<Rcpp::LogicalVector>( | |
| 1119 | ! | meta["has_active_area"]); |
| 1120 | ! | allow_active_area = has_active.size() > 0 && has_active[0] == TRUE; |
| 1121 | } | |
| 1122 | 1x | if (allow_active_area && HasListElement(meta, "active_area")) { |
| 1123 | ! | Rcpp::IntegerVector area = GetIntegerVector(meta, "active_area"); |
| 1124 | ! | if (!HasNaInteger(area, 4)) { |
| 1125 | unsigned int values[4] = { | |
| 1126 | ! | static_cast<unsigned int>(area[0]), |
| 1127 | ! | static_cast<unsigned int>(area[1]), |
| 1128 | ! | static_cast<unsigned int>(area[2]), |
| 1129 | ! | static_cast<unsigned int>(area[3]) |
| 1130 | }; | |
| 1131 | ! | dng_image.SetActiveArea(values); |
| 1132 | } | |
| 1133 | } | |
| 1134 | ||
| 1135 | 1x | if (HasListElement(meta, "orientation")) { |
| 1136 | ! | Rcpp::IntegerVector orientation = GetIntegerVector(meta, "orientation"); |
| 1137 | ! | if (orientation.size() >= 1 && orientation[0] != NA_INTEGER) { |
| 1138 | ! | dng_image.SetOrientation(static_cast<unsigned short>(orientation[0])); |
| 1139 | } | |
| 1140 | } | |
| 1141 | ||
| 1142 | 1x | if (is_mosaic && compress) { |
| 1143 | 1x | if (!dng_image.SetCompression(tinydngwriter::COMPRESSION_NEW_JPEG)) { |
| 1144 | ! | Rcpp::stop("Failed to set DNG compression."); |
| 1145 | } | |
| 1146 | 1x | if (!dng_image.SetImageDataJpeg(buf.data(), |
| 1147 | static_cast<unsigned int>(width), | |
| 1148 | static_cast<unsigned int>(height), | |
| 1149 | static_cast<unsigned int>(bitdepth))) { | |
| 1150 | ! | Rcpp::stop("Failed to set DNG JPEG image data."); |
| 1151 | } | |
| 1152 | } else { | |
| 1153 | ! | if (!dng_image.SetCompression(tinydngwriter::COMPRESSION_NONE)) { |
| 1154 | ! | Rcpp::stop("Failed to set DNG compression."); |
| 1155 | } | |
| 1156 | ! | if (!dng_image.SetImageData(reinterpret_cast<unsigned char*>(buf.data()), |
| 1157 | ! | buf.size() * sizeof(uint16_t))) { |
| 1158 | ! | Rcpp::stop("Failed to set DNG image data."); |
| 1159 | } | |
| 1160 | } | |
| 1161 | ||
| 1162 | 1x | tinydngwriter::DNGWriter writer(false); |
| 1163 | 1x | writer.AddImage(&dng_image); |
| 1164 | 1x | std::string err; |
| 1165 | 1x | if (!writer.WriteToFile(filename.c_str(), &err)) { |
| 1166 | ! | Rcpp::stop(err.empty() ? "Failed to write DNG." : err); |
| 1167 | } | |
| 1168 | ||
| 1169 | 1x | return true; |
| 1170 | } |
| 1 | #include <vector> | |
| 2 | #include <memory> | |
| 3 | #include <string> | |
| 4 | #include "Rcpp.h" | |
| 5 | #include <filesystem> | |
| 6 | ||
| 7 | #define STB_IMAGE_IMPLEMENTATION | |
| 8 | #include <stbimageheaders/stb_image.h> | |
| 9 | ||
| 10 | namespace fs = std::filesystem; | |
| 11 | ||
| 12 | // [[Rcpp::export]] | |
| 13 | 7x | Rcpp::NumericVector load_image_stb(const std::string& filename, |
| 14 | int& width, | |
| 15 | int& height, | |
| 16 | int& channels, | |
| 17 | int desired_channels) { | |
| 18 | 7x | width = height = channels = 0; |
| 19 | ||
| 20 | 7x | const fs::path filepath(filename); |
| 21 | 7x | const std::string filepath_string = filepath.string(); |
| 22 | ||
| 23 | 7x | float* data = stbi_loadf(filepath_string.c_str(), &width, &height, &channels, |
| 24 | desired_channels); | |
| 25 | 7x | if (!data) { |
| 26 | throw std::runtime_error( | |
| 27 | ! | "Loading of '" + filename + "' (float) failed: " + |
| 28 | ! | std::string(stbi_failure_reason()) + |
| 29 | ! | " -- nx/ny/channels: " + std::to_string(width) + "/" + |
| 30 | ! | std::to_string(height) + "/" + std::to_string(channels)); |
| 31 | } | |
| 32 | ||
| 33 | 7x | if (desired_channels != 0) { |
| 34 | 7x | channels = desired_channels; |
| 35 | } | |
| 36 | ||
| 37 | 7x | if (width == 0 || height == 0 || channels == 0) { |
| 38 | ! | stbi_image_free(data); |
| 39 | ! | throw std::runtime_error("Could not find " + filename); |
| 40 | } | |
| 41 | ||
| 42 | // Enforce RGBA | |
| 43 | 7x | if (channels != 4) { |
| 44 | ! | stbi_image_free(data); |
| 45 | throw std::runtime_error( | |
| 46 | ! | "Expected 4 channels (RGBA) but got " + std::to_string(channels) + |
| 47 | ! | ". Call with desired_channels = 4."); |
| 48 | } | |
| 49 | ||
| 50 | // Allocate R array: dim = c(height, width, 4) (RGBA in the 3rd dimension) | |
| 51 | 7x | std::size_t n_pixels = static_cast<std::size_t>(width) * |
| 52 | 7x | static_cast<std::size_t>(height); |
| 53 | 7x | std::size_t n_vals = n_pixels * 4; |
| 54 | ||
| 55 | 7x | Rcpp::NumericVector arr_return(n_vals); |
| 56 | 7x | Rcpp::IntegerVector dim(3); |
| 57 | 7x | dim[0] = height; // rows (y) |
| 58 | 7x | dim[1] = width; // cols (x) |
| 59 | 7x | dim[2] = 4; // RGBA |
| 60 | 7x | arr_return.attr("dim") = dim; |
| 61 | ||
| 62 | // Reorder from STB layout (y, x, c; row-major) to R layout (y, x, c; column-major) | |
| 63 | 119x | for (int y = 0; y < height; ++y) { |
| 64 | 1904x | for (int x = 0; x < width; ++x) { |
| 65 | 8960x | for (int c = 0; c < 4; ++c) { |
| 66 | 7168x | std::size_t stb_idx = |
| 67 | 7168x | (static_cast<std::size_t>(y) * width + x) * 4 + c; |
| 68 | ||
| 69 | // R index: y + height * (x + width * c) | |
| 70 | 7168x | std::size_t r_idx = |
| 71 | 7168x | static_cast<std::size_t>(y) + |
| 72 | 7168x | static_cast<std::size_t>(height) * |
| 73 | 7168x | (x + static_cast<std::size_t>(width) * c); |
| 74 | ||
| 75 | 7168x | arr_return[r_idx] = static_cast<double>(data[stb_idx]); |
| 76 | } | |
| 77 | } | |
| 78 | } | |
| 79 | ||
| 80 | 7x | stbi_image_free(data); |
| 81 | 7x | return arr_return; |
| 82 | } |
| 1 | #define STB_IMAGE_RESIZE_IMPLEMENTATION | |
| 2 | ||
| 3 | #include <RcppArmadillo.h> | |
| 4 | #include <RProgress.h> | |
| 5 | #include <stbimageheaders/stb_image_resize2.h> | |
| 6 | // [[Rcpp::depends(RcppArmadillo)]] | |
| 7 | using namespace Rcpp; | |
| 8 | ||
| 9 | // [[Rcpp::export]] | |
| 10 | ! | arma::mat subsample(arma::mat& circle, int size) { |
| 11 | ! | int binsize = circle.n_cols/size; |
| 12 | ! | arma::mat subsampled(size,size,arma::fill::zeros); |
| 13 | ! | if(size == 1) { |
| 14 | ! | subsampled(0,0) = 1; |
| 15 | ! | return(subsampled); |
| 16 | } | |
| 17 | ! | arma::mat temp; |
| 18 | ! | for(int i = 0; i < size; i++) { |
| 19 | ! | for(int j = 0; j < size; j++) { |
| 20 | ! | if(i != size - 1 && j != size - 1) { |
| 21 | ! | temp = circle.submat(binsize*i,binsize*j,binsize*(i+1),binsize*(j+1)); |
| 22 | ! | subsampled(i,j) = accu(temp)/(temp.n_elem); |
| 23 | ! | } else if (i == size - 1 && j != size - 1) { |
| 24 | ! | temp = circle.submat(binsize*i,binsize*j,circle.n_rows-1,binsize*(j+1)); |
| 25 | ! | subsampled(i,j) = accu(temp)/(temp.n_elem); |
| 26 | ! | } else if (j == size - 1 && i != size - 1) { |
| 27 | ! | temp = circle.submat(binsize*i,binsize*j,binsize*(i+1),circle.n_cols-1); |
| 28 | ! | subsampled(i,j) = accu(temp)/(temp.n_elem); |
| 29 | ! | } else if (i == size - 1 && j == size - 1) { |
| 30 | ! | temp = circle.submat(binsize*i,binsize*j,circle.n_rows-1,circle.n_cols-1); |
| 31 | ! | subsampled(i,j) = accu(temp)/(temp.n_elem); |
| 32 | } | |
| 33 | } | |
| 34 | } | |
| 35 | ! | return(subsampled); |
| 36 | } | |
| 37 | ||
| 38 | ! | arma::mat subsample_interpolate(arma::mat& circle, float mag) { |
| 39 | //Create two vectors ranging from 1 to ncol/nrow | |
| 40 | ! | arma::vec X = arma::regspace(1, circle.n_cols); |
| 41 | ! | arma::vec Y = arma::regspace(1, circle.n_rows); |
| 42 | //Create two vectors ranging from 1 to the ncol/nrow, with step mag | |
| 43 | //e.g. (1 + 0*mag, 1 + mag, 1+2*mag, ... , 1 + floor(end-1)/mag, so that | |
| 44 | // start + floor(end-1) * mag < ncol/nrow | |
| 45 | ||
| 46 | //These are our new, interpolated values | |
| 47 | ! | arma::vec XI = arma::regspace(X.min(), mag, X.max()); |
| 48 | ! | arma::vec YI = arma::regspace(Y.min(), mag, Y.max()); |
| 49 | ||
| 50 | //If X1.n_elem is even, remove one element to make it odd | |
| 51 | ! | if(XI.n_elem % 2 == 0) { |
| 52 | ! | XI.set_size(XI.n_elem-1); |
| 53 | } | |
| 54 | //If Y1.n_elem is even, remove one element to make it odd | |
| 55 | ||
| 56 | ! | if(YI.n_elem % 2 == 0) { |
| 57 | ! | YI.set_size(YI.n_elem-1); |
| 58 | } | |
| 59 | ! | arma::mat ZI; |
| 60 | //Interpolate the `circle` values given on the XY grid on the new grid ZI specified | |
| 61 | //by XI and YI | |
| 62 | ! | arma::interp2(X, Y, circle, XI, YI, ZI); |
| 63 | ! | return(ZI); |
| 64 | } | |
| 65 | ||
| 66 | // [[Rcpp::export]] | |
| 67 | 95x | arma::mat rayinterp2(arma::mat& image, arma::vec& XI, arma::vec& YI) { |
| 68 | 95x | arma::vec X = arma::regspace(1, image.n_cols); |
| 69 | 95x | arma::vec Y = arma::regspace(1, image.n_rows); |
| 70 | 95x | arma::mat ZI; |
| 71 | 95x | arma::interp2(X, Y, image, XI, YI, ZI); |
| 72 | 95x | return(ZI); |
| 73 | } | |
| 74 | ||
| 75 | ||
| 76 | // [[Rcpp::export]] | |
| 77 | ! | arma::mat resize_image(arma::mat& image, float mag) { |
| 78 | ! | arma::vec X = arma::regspace(1, image.n_cols); |
| 79 | ! | arma::vec Y = arma::regspace(1, image.n_rows); |
| 80 | ! | arma::vec XI = arma::regspace(X.min(), 1.0/mag, X.max()); |
| 81 | ! | arma::vec YI = arma::regspace(Y.min(), 1.0/mag, Y.max()); |
| 82 | ! | arma::mat ZI; |
| 83 | ! | arma::interp2(X, Y, image, XI, YI, ZI); |
| 84 | ! | return(ZI); |
| 85 | } | |
| 86 | ||
| 87 | // [[Rcpp::export]] | |
| 88 | ! | arma::mat resize_image_xy(arma::mat& image, arma::vec XI, arma::vec YI) { |
| 89 | ! | arma::vec X = arma::regspace(1, image.n_cols); |
| 90 | ! | arma::vec Y = arma::regspace(1, image.n_rows); |
| 91 | ! | arma::mat ZI; |
| 92 | ! | arma::interp2(X, Y, image, XI, YI, ZI); |
| 93 | ! | return(ZI); |
| 94 | } | |
| 95 | ||
| 96 | // [[Rcpp::export]] | |
| 97 | 8x | NumericMatrix resize_matrix_stb(NumericMatrix image, int width, int height, int method) { |
| 98 | 8x | float* resized_image = new float[width * height]; |
| 99 | 8x | float* original_image = new float[image.ncol() * image.nrow()]; |
| 100 | ||
| 101 | 816x | for(int i = 0; i < image.nrow(); i++ ) { |
| 102 | 160824x | for(int j = 0; j < image.ncol(); j++) { |
| 103 | 160016x | original_image[i + image.nrow() * j] = image(i,j); |
| 104 | } | |
| 105 | } | |
| 106 | stbir_filter interp_type; | |
| 107 | 8x | switch(method) { |
| 108 | ! | case 0: |
| 109 | ! | interp_type = STBIR_FILTER_DEFAULT; |
| 110 | ! | break; |
| 111 | ! | case 1: |
| 112 | ! | interp_type = STBIR_FILTER_BOX; |
| 113 | ! | break; |
| 114 | ! | case 2: |
| 115 | ! | interp_type = STBIR_FILTER_TRIANGLE; |
| 116 | ! | break; |
| 117 | 8x | case 3: |
| 118 | 8x | interp_type = STBIR_FILTER_CUBICBSPLINE; |
| 119 | 8x | break; |
| 120 | ! | case 4: |
| 121 | ! | interp_type = STBIR_FILTER_CATMULLROM; |
| 122 | ! | break; |
| 123 | ! | case 5: |
| 124 | ! | interp_type = STBIR_FILTER_MITCHELL; |
| 125 | ! | break; |
| 126 | ! | default: |
| 127 | ! | interp_type = STBIR_FILTER_MITCHELL; |
| 128 | } | |
| 129 | ||
| 130 | 8x | void* resized = stbir_resize( |
| 131 | original_image, image.nrow(), image.ncol(), 0, | |
| 132 | resized_image, width, height, 0, | |
| 133 | STBIR_1CHANNEL, STBIR_TYPE_FLOAT, | |
| 134 | STBIR_EDGE_WRAP, interp_type); | |
| 135 | 8x | if (resized == nullptr) { |
| 136 | ! | delete[] resized_image; |
| 137 | ! | delete[] original_image; |
| 138 | ! | stop("stb image resize failed."); |
| 139 | } | |
| 140 | 8x | NumericMatrix resized_mat(width,height); |
| 141 | 280x | for(int i = 0; i < width; i++ ) { |
| 142 | 16736x | for(int j = 0; j < height; j++) { |
| 143 | 16464x | resized_mat(i,j) = resized_image[i + width * j]; |
| 144 | } | |
| 145 | } | |
| 146 | 8x | delete[] resized_image; |
| 147 | 8x | delete[] original_image; |
| 148 | ||
| 149 | 8x | return(resized_mat); |
| 150 | } | |
| 151 | ||
| 152 | ! | float evaluate_disk(float x) { |
| 153 | ! | return((cos(x*1.685979) * -22.356787 + sin(x*1.685979) * 85.912460) * exp(-4.892608 *x) + |
| 154 | ! | (cos(x*4.998496) * 35.918936 + sin(x*4.998496) * -28.875618) * exp(-4.711870 *x) + |
| 155 | ! | (cos(x*8.244168) * -13.212253 + sin(x*8.244168) * -1.578428) * exp(-4.052795 *x) + |
| 156 | ! | (cos(x*11.900859) * 0.507991 + sin(x*11.900859) * 1.816328) * exp(-2.929212* x) + |
| 157 | ! | (cos(x*16.116382) * 0.138051 + sin(x*16.116382) * -0.010000) * exp(-1.512961 *x)); |
| 158 | } | |
| 159 | ||
| 160 | // [[Rcpp::export]] | |
| 161 | ! | arma::mat generate_disk(float radius, int dim, bool offsetx, bool offsety) { |
| 162 | ! | arma::mat testmat(dim,dim); |
| 163 | ! | arma::vec x = arma::linspace(-1,1,dim) * radius; |
| 164 | ! | arma::vec y = arma::linspace(-1,1,dim) * radius; |
| 165 | ! | if(offsetx) { |
| 166 | ! | x -= radius/dim + radius/dim/8; |
| 167 | } | |
| 168 | ! | if(offsety) { |
| 169 | ! | y -= radius/dim + radius/dim/8; |
| 170 | } | |
| 171 | ! | for(arma::uword i = 0; i < testmat.n_rows; i++) { |
| 172 | ! | for(arma::uword j = 0; j < testmat.n_cols; j++) { |
| 173 | ! | testmat(i,j) = fabs(evaluate_disk(pow(x[i],2.0) + pow(y[j],2.0))); |
| 174 | } | |
| 175 | } | |
| 176 | ! | return(testmat); |
| 177 | } | |
| 178 | ||
| 179 | // [[Rcpp::export]] | |
| 180 | ! | arma::mat gen_ellipse(const double intensity, double width, double height) { |
| 181 | ! | arma::mat ellipse(width,height); |
| 182 | ! | for (int i = 0; i < width; ++i) { |
| 183 | ! | for (int j = 0; j < height; ++j) { |
| 184 | ! | ellipse(i,j) = pow(((double)i - width/2 + 0.5), 2.0) * pow(height/2,2.0) + |
| 185 | ! | pow(((double)j - height/2 + 0.5),2.0) * pow(width/2,2.0) > pow(width * height, 2.0)/16 ? intensity : 0.0; |
| 186 | } | |
| 187 | } | |
| 188 | ! | return(ellipse); |
| 189 | } | |
| 190 | ||
| 191 | // [[Rcpp::export]] | |
| 192 | ! | arma::mat subsample_rect(arma::mat& rect, int binsx, int binsy) { |
| 193 | ! | int binsizex = rect.n_rows/binsx; |
| 194 | ! | int binsizey = rect.n_cols/binsy; |
| 195 | ! | arma::mat subsampled(binsx,binsy,arma::fill::zeros); |
| 196 | ! | arma::mat temp; |
| 197 | ! | for(int i = 0; i < binsx; i++) { |
| 198 | ! | for(int j = 0; j < binsy; j++) { |
| 199 | ! | if(i != binsx - 1 && j != binsy - 1) { |
| 200 | ! | temp = rect.submat(binsizex*i,binsizey*j,binsizex*(i+1),binsizey*(j+1)); |
| 201 | ! | subsampled(i,j) = accu(temp)/(temp.n_elem); |
| 202 | ! | } else if (i == binsx - 1 && j != binsy - 1) { |
| 203 | ! | temp = rect.submat(binsizex*i,binsizey*j,rect.n_rows-1,binsizey*(j+1)); |
| 204 | ! | subsampled(i,j) = accu(temp)/(temp.n_elem); |
| 205 | ! | } else if (j == binsy - 1 && i != binsx - 1) { |
| 206 | ! | temp = rect.submat(binsizex*i,binsizey*j,binsizex*(i+1),rect.n_cols-1); |
| 207 | ! | subsampled(i,j) = accu(temp)/(temp.n_elem); |
| 208 | ! | } else if (i == binsx - 1 && j == binsy - 1) { |
| 209 | ! | temp = rect.submat(binsizex*i,binsizey*j,rect.n_rows-1,rect.n_cols-1); |
| 210 | ! | subsampled(i,j) = accu(temp)/(temp.n_elem); |
| 211 | } | |
| 212 | } | |
| 213 | } | |
| 214 | ! | return(subsampled); |
| 215 | } | |
| 216 | ||
| 217 | // [[Rcpp::export]] | |
| 218 | ! | arma::mat gen_circle_psf(const double radius) { |
| 219 | ! | int size = ceil(radius * 2); |
| 220 | ! | if(size < 6) { |
| 221 | ! | size = 7; |
| 222 | } | |
| 223 | ! | if((size % 2) == 0) { |
| 224 | ! | size++; |
| 225 | } | |
| 226 | ! | arma::mat kernel(size,size); |
| 227 | ! | if(radius == 0) { |
| 228 | ! | arma::mat zero(1,1,arma::fill::ones); |
| 229 | ! | return(zero); |
| 230 | } | |
| 231 | ! | double mean = (size-1)/2; |
| 232 | ! | for (int i = 0; i < size; ++i) { |
| 233 | ! | for (int j = 0; j < size; ++j) { |
| 234 | ! | kernel(i,j) = pow(((double)i - mean),2.0) + pow(((double)j - mean),2.0) < pow(radius,2.0) ? 1.0 : 0.0; |
| 235 | } | |
| 236 | } | |
| 237 | ! | return(kernel); |
| 238 | } | |
| 239 | ||
| 240 | // [[Rcpp::export]] | |
| 241 | ! | bool is_inside(double sizehex, double positionx, double positiony, double sinval, double cosval) { |
| 242 | ! | double num1 = fabs(cosval* (positionx - sizehex) - sinval* (positiony - sizehex)); |
| 243 | ! | double num2 = fabs(sinval* (positionx - sizehex) + cosval* (positiony - sizehex)); |
| 244 | ! | double minval = sizehex - num1 < sizehex / 2 ? sizehex - num1 : sizehex / 2; |
| 245 | ! | return(num2 < sqrt(3.0) * minval); |
| 246 | } | |
| 247 | ||
| 248 | // [[Rcpp::export]] | |
| 249 | ! | arma::mat gen_hex_psf(const double radius, const double rotation) { |
| 250 | ! | int size = ceil(radius * 2); |
| 251 | ! | if(size < 6) { |
| 252 | ! | size = 7; |
| 253 | } | |
| 254 | ! | if((size % 2) == 0) { |
| 255 | ! | size++; |
| 256 | } | |
| 257 | ! | arma::mat kernel(size,size); |
| 258 | ! | if(radius == 0) { |
| 259 | ! | arma::mat zero(1,1,arma::fill::zeros); |
| 260 | ! | return(zero); |
| 261 | } | |
| 262 | ! | const double sinval = sin(rotation); |
| 263 | ! | const double cosval = cos(rotation); |
| 264 | ! | double mean = (size-1)/2; |
| 265 | ! | for (int i = 0; i < size; ++i) { |
| 266 | ! | for (int j = 0; j < size; ++j) { |
| 267 | ! | kernel(i,j) = is_inside(mean, i, j, sinval, cosval) ? 1.0 : 0.0; |
| 268 | } | |
| 269 | } | |
| 270 | ! | return(kernel); |
| 271 | } | |
| 272 | ||
| 273 | // [[Rcpp::export]] | |
| 274 | ! | arma::mat psf(const arma::mat& image, const IntegerMatrix blurmatrix, |
| 275 | const arma::mat& depthmap, double depth, const arma::mat custombokeh, | |
| 276 | int type, double bokehintensity, double bokehlimit, | |
| 277 | double rotation, bool progbar, int channel) { | |
| 278 | ! | int maxsteps = max(blurmatrix); |
| 279 | ! | int rows = image.n_rows; |
| 280 | ! | int cols = image.n_cols; |
| 281 | ! | arma::mat tempkernel; |
| 282 | ! | std::vector<arma::mat> kernels; |
| 283 | ! | arma::mat mask; |
| 284 | ! | if(type == 0) { |
| 285 | ! | mask = generate_disk(1.18, 501, false, false); |
| 286 | ! | } else if (type == 1) { |
| 287 | ! | mask = gen_hex_psf(500, rotation); |
| 288 | ! | } else if (type == 2) { |
| 289 | ! | mask = custombokeh; |
| 290 | } | |
| 291 | ! | int counter = 0; |
| 292 | ! | int max_dim = mask.n_cols > mask.n_rows ? mask.n_cols : mask.n_rows; |
| 293 | ! | for(int i = 0; i < maxsteps+1; i++) { |
| 294 | ! | tempkernel = subsample_interpolate(mask, (float)max_dim/(float)(i+1)); |
| 295 | ! | tempkernel = tempkernel/accu(tempkernel); |
| 296 | ! | kernels.push_back(tempkernel); |
| 297 | ! | counter++; |
| 298 | } | |
| 299 | ! | int halfwidth = (kernels[counter-1].n_cols-1)/2; |
| 300 | ! | arma::mat temp; |
| 301 | ! | arma::mat temp2; |
| 302 | ! | arma::mat depthmask; |
| 303 | ! | arma::mat blurmask; |
| 304 | ! | arma::mat result(image.n_rows, image.n_cols, arma::fill::zeros); |
| 305 | ! | arma::mat normalize(result.n_rows, result.n_cols, arma::fill::zeros); |
| 306 | ! | std::string pbtext; |
| 307 | ! | if(channel == 1) { |
| 308 | ! | pbtext = "Rendering Bokeh 1/3 [:bar] ETA: :eta"; |
| 309 | ! | } else if(channel == 2) { |
| 310 | ! | pbtext = "Rendering Bokeh 2/3 [:bar] ETA: :eta"; |
| 311 | ! | } else if(channel == 3) { |
| 312 | ! | pbtext = "Rendering Bokeh 3/3 [:bar] ETA: :eta"; |
| 313 | } | |
| 314 | ! | RProgress::RProgress pb(pbtext); |
| 315 | ! | if(progbar) { |
| 316 | ! | pb.set_total(rows*cols); |
| 317 | } | |
| 318 | ||
| 319 | int begini, beginj, endi, endj, temphalfi, temphalfj; | |
| 320 | int beginslicei, endslicei, beginslicej, endslicej; | |
| 321 | ! | for (int i = halfwidth; i < rows-halfwidth; ++i) { |
| 322 | ||
| 323 | ! | Rcpp::checkUserInterrupt(); |
| 324 | ! | for (int j = halfwidth; j < cols-halfwidth; ++j) { |
| 325 | ! | if(progbar) { |
| 326 | ! | pb.tick(); |
| 327 | } | |
| 328 | ! | temp = kernels[blurmatrix(i,j)]/pow(depthmap(i,j),2); |
| 329 | ! | if(temp.n_cols == 1) { |
| 330 | ! | normalize(i,j) += 1/pow(depthmap(i,j),2); |
| 331 | ! | result(i,j) += image(i,j)/pow(depthmap(i,j),2); |
| 332 | ! | continue; |
| 333 | } | |
| 334 | ! | begini = i - (temp.n_rows-1)/2; |
| 335 | ! | beginj = j - (temp.n_cols-1)/2; |
| 336 | ! | endi = i + (temp.n_rows-1)/2; |
| 337 | ! | endj = j + (temp.n_cols-1)/2; |
| 338 | ! | if(image(i,j) > bokehlimit) { |
| 339 | ! | temp = temp * bokehintensity; |
| 340 | } | |
| 341 | ||
| 342 | ! | result.submat(begini, beginj, endi, endj) += image(i,j) * temp; |
| 343 | ! | normalize.submat(begini, beginj, endi, endj) += temp; |
| 344 | } | |
| 345 | } | |
| 346 | ||
| 347 | ! | for (int i = 0; i < halfwidth; ++i) { |
| 348 | ! | Rcpp::checkUserInterrupt(); |
| 349 | ! | for (int j = 0; j < cols; ++j) { |
| 350 | ! | if(progbar) { |
| 351 | ! | pb.tick(); |
| 352 | } | |
| 353 | ! | temp = kernels[blurmatrix(i,j)]/pow(depthmap(i,j),2); |
| 354 | ! | if(temp.n_cols == 1) { |
| 355 | ! | normalize(i,j) += 1/pow(depthmap(i,j),2); |
| 356 | ! | result(i,j) += image(i,j)/pow(depthmap(i,j),2); |
| 357 | ! | continue; |
| 358 | } | |
| 359 | ! | temphalfi = (temp.n_rows-1)/2; |
| 360 | ! | temphalfj = (temp.n_cols-1)/2; |
| 361 | ! | beginslicei = 0; |
| 362 | ! | endslicei = temp.n_rows-1; |
| 363 | ! | beginslicej = 0; |
| 364 | ! | endslicej = temp.n_cols-1; |
| 365 | ! | endi = i + temphalfi; |
| 366 | ! | endj = j + temphalfj; |
| 367 | ! | begini = i - temphalfi; |
| 368 | ! | beginj = j - temphalfj; |
| 369 | ! | if(i - temphalfi < 0) { |
| 370 | ! | beginslicei = temphalfi - i; |
| 371 | ! | begini = 0; |
| 372 | } | |
| 373 | ! | if(i + temphalfi > rows - 1) { |
| 374 | ! | endslicei = endslicei - (i + temphalfi - rows + 1); |
| 375 | ! | endi = rows - 1; |
| 376 | } | |
| 377 | ! | if(j - temphalfj < 0) { |
| 378 | ! | beginslicej = temphalfj - j; |
| 379 | ! | beginj = 0; |
| 380 | } | |
| 381 | ! | if(j + temphalfj > cols - 1) { |
| 382 | ! | endslicej = endslicej - (j + temphalfj - cols + 1); |
| 383 | ! | endj = cols - 1; |
| 384 | } | |
| 385 | ! | if(image(i,j) > bokehlimit) { |
| 386 | ! | temp = temp * bokehintensity; |
| 387 | } | |
| 388 | ! | temp2 = temp.submat(beginslicei,beginslicej,endslicei,endslicej); |
| 389 | ! | result.submat(begini, beginj, endi, endj) += image(i,j) * temp2; |
| 390 | ! | normalize.submat(begini, beginj, endi, endj) += temp2; |
| 391 | } | |
| 392 | } | |
| 393 | ! | for (int i = halfwidth; i < rows-halfwidth; ++i) { |
| 394 | ! | Rcpp::checkUserInterrupt(); |
| 395 | ! | for (int j = 0; j < halfwidth; ++j) { |
| 396 | ! | if(progbar) { |
| 397 | ! | pb.tick(); |
| 398 | } | |
| 399 | ! | temp = kernels[blurmatrix(i,j)]/pow(depthmap(i,j),2); |
| 400 | ! | if(temp.n_cols == 1) { |
| 401 | ! | normalize(i,j) += 1/pow(depthmap(i,j),2); |
| 402 | ! | result(i,j) += image(i,j)/pow(depthmap(i,j),2); |
| 403 | ! | continue; |
| 404 | } | |
| 405 | ! | temphalfi = (temp.n_rows-1)/2; |
| 406 | ! | temphalfj = (temp.n_cols-1)/2; |
| 407 | ! | beginslicei = 0; |
| 408 | ! | endslicei = temp.n_rows-1; |
| 409 | ! | beginslicej = 0; |
| 410 | ! | endslicej = temp.n_cols-1; |
| 411 | ! | endi = i + temphalfi; |
| 412 | ! | endj = j + temphalfj; |
| 413 | ! | begini = i - temphalfi; |
| 414 | ! | beginj = j - temphalfj; |
| 415 | ! | if(i - temphalfi < 0) { |
| 416 | ! | beginslicei = temphalfi - i; |
| 417 | ! | begini = 0; |
| 418 | } | |
| 419 | ! | if(i + temphalfi > rows - 1) { |
| 420 | ! | endslicei = endslicei - (i + temphalfi - rows + 1); |
| 421 | ! | endi = rows - 1; |
| 422 | } | |
| 423 | ! | if(j - temphalfj < 0) { |
| 424 | ! | beginslicej = temphalfj - j; |
| 425 | ! | beginj = 0; |
| 426 | } | |
| 427 | ! | if(j + temphalfj > cols - 1) { |
| 428 | ! | endslicej = endslicej - (j + temphalfj - cols + 1); |
| 429 | ! | endj = cols - 1; |
| 430 | } | |
| 431 | ! | if(image(i,j) > bokehlimit) { |
| 432 | ! | temp = temp * bokehintensity; |
| 433 | } | |
| 434 | ! | temp2 = temp.submat(beginslicei,beginslicej,endslicei,endslicej); |
| 435 | ! | result.submat(begini, beginj, endi, endj) += image(i,j) * temp2; |
| 436 | ! | normalize.submat(begini, beginj, endi, endj) += temp2; |
| 437 | } | |
| 438 | } | |
| 439 | ! | for (int i = halfwidth; i < rows-halfwidth; ++i) { |
| 440 | ! | Rcpp::checkUserInterrupt(); |
| 441 | ! | for (int j = cols-halfwidth; j < cols; ++j) { |
| 442 | ! | if(progbar) { |
| 443 | ! | pb.tick(); |
| 444 | } | |
| 445 | ! | temp = kernels[blurmatrix(i,j)]/pow(depthmap(i,j),2); |
| 446 | ! | if(temp.n_cols == 1) { |
| 447 | ! | normalize(i,j) += 1/pow(depthmap(i,j),2); |
| 448 | ! | result(i,j) += image(i,j)/pow(depthmap(i,j),2); |
| 449 | ! | continue; |
| 450 | } | |
| 451 | ! | temphalfi = (temp.n_rows-1)/2; |
| 452 | ! | temphalfj = (temp.n_cols-1)/2; |
| 453 | ! | beginslicei = 0; |
| 454 | ! | endslicei = temp.n_rows-1; |
| 455 | ! | beginslicej = 0; |
| 456 | ! | endslicej = temp.n_cols-1; |
| 457 | ! | endi = i + temphalfi; |
| 458 | ! | endj = j + temphalfj; |
| 459 | ! | begini = i - temphalfi; |
| 460 | ! | beginj = j - temphalfj; |
| 461 | ! | if(i - temphalfi < 0) { |
| 462 | ! | beginslicei = temphalfi - i; |
| 463 | ! | begini = 0; |
| 464 | } | |
| 465 | ! | if(i + temphalfi > rows - 1) { |
| 466 | ! | endslicei = endslicei - (i + temphalfi - rows + 1); |
| 467 | ! | endi = rows - 1; |
| 468 | } | |
| 469 | ! | if(j - temphalfj < 0) { |
| 470 | ! | beginslicej = temphalfj - j; |
| 471 | ! | beginj = 0; |
| 472 | } | |
| 473 | ! | if(j + temphalfj > cols - 1) { |
| 474 | ! | endslicej = endslicej - (j + temphalfj - cols + 1); |
| 475 | ! | endj = cols - 1; |
| 476 | } | |
| 477 | ! | if(image(i,j) > bokehlimit) { |
| 478 | ! | temp = temp * bokehintensity; |
| 479 | } | |
| 480 | ! | temp2 = temp.submat(beginslicei,beginslicej,endslicei,endslicej); |
| 481 | ! | result.submat(begini, beginj, endi, endj) += image(i,j) * temp2; |
| 482 | ! | normalize.submat(begini, beginj, endi, endj) += temp2; |
| 483 | } | |
| 484 | } | |
| 485 | ! | for (int i = rows-halfwidth; i < rows; ++i) { |
| 486 | ! | Rcpp::checkUserInterrupt(); |
| 487 | ! | for (int j = 0; j < cols; ++j) { |
| 488 | ! | if(progbar) { |
| 489 | ! | pb.tick(); |
| 490 | } | |
| 491 | ! | temp = kernels[blurmatrix(i,j)]/pow(depthmap(i,j),2); |
| 492 | ! | if(temp.n_cols == 1) { |
| 493 | ! | normalize(i,j) += 1/pow(depthmap(i,j),2); |
| 494 | ! | result(i,j) += image(i,j)/pow(depthmap(i,j),2); |
| 495 | ! | continue; |
| 496 | } | |
| 497 | ! | temphalfi = (temp.n_rows-1)/2; |
| 498 | ! | temphalfj = (temp.n_cols-1)/2; |
| 499 | ! | beginslicei = 0; |
| 500 | ! | endslicei = temp.n_rows-1; |
| 501 | ! | beginslicej = 0; |
| 502 | ! | endslicej = temp.n_cols-1; |
| 503 | ! | endi = i + temphalfi; |
| 504 | ! | endj = j + temphalfj; |
| 505 | ! | begini = i - temphalfi; |
| 506 | ! | beginj = j - temphalfj; |
| 507 | ! | if(i - temphalfi < 0) { |
| 508 | ! | beginslicei = temphalfi - i; |
| 509 | ! | begini = 0; |
| 510 | } | |
| 511 | ! | if(i + temphalfi > rows - 1) { |
| 512 | ! | endslicei = endslicei - (i + temphalfi - rows + 1); |
| 513 | ! | endi = rows - 1; |
| 514 | } | |
| 515 | ! | if(j - temphalfj < 0) { |
| 516 | ! | beginslicej = temphalfj - j; |
| 517 | ! | beginj = 0; |
| 518 | } | |
| 519 | ! | if(j + temphalfj > cols - 1) { |
| 520 | ! | endslicej = endslicej - (j + temphalfj - cols + 1); |
| 521 | ! | endj = cols - 1; |
| 522 | } | |
| 523 | ! | if(image(i,j) > bokehlimit) { |
| 524 | ! | temp = temp * bokehintensity; |
| 525 | } | |
| 526 | ! | temp2 = temp.submat(beginslicei,beginslicej,endslicei,endslicej); |
| 527 | ! | result.submat(begini, beginj, endi, endj) += image(i,j) * temp2; |
| 528 | ! | normalize.submat(begini, beginj, endi, endj) += temp2; |
| 529 | } | |
| 530 | } | |
| 531 | ! | return(result/normalize); |
| 532 | } | |
| 533 | ||
| 534 | // [[Rcpp::export]] | |
| 535 | ! | arma::mat convolution_cpp(const arma::mat& image, const arma::mat kernel, |
| 536 | bool progbar, int channel, arma::mat& bloom_matrix) { | |
| 537 | ! | int rows = image.n_rows; |
| 538 | ! | int cols = image.n_cols; |
| 539 | ! | arma::mat mask; |
| 540 | //kernel needs to have odd number of cols | |
| 541 | ! | int halfwidth = (kernel.n_cols-1)/2; |
| 542 | ! | arma::mat temp; |
| 543 | ! | arma::mat temp2; |
| 544 | ! | arma::mat result(image.n_rows, image.n_cols, arma::fill::zeros); |
| 545 | ! | arma::mat normalize(result.n_rows, result.n_cols, arma::fill::zeros); |
| 546 | ! | std::string pbtext; |
| 547 | ! | if(channel == 1) { |
| 548 | ! | pbtext = "Rendering Bokeh 1/3 [:bar] ETA: :eta"; |
| 549 | ! | } else if(channel == 2) { |
| 550 | ! | pbtext = "Rendering Bokeh 2/3 [:bar] ETA: :eta"; |
| 551 | ! | } else if(channel == 3) { |
| 552 | ! | pbtext = "Rendering Bokeh 3/3 [:bar] ETA: :eta"; |
| 553 | } | |
| 554 | ! | RProgress::RProgress pb(pbtext); |
| 555 | ! | if(progbar) { |
| 556 | ! | pb.set_total(rows*cols); |
| 557 | } | |
| 558 | ! | bool norm = false; |
| 559 | ! | if(arma::accu(kernel) != 0) { |
| 560 | ! | norm = true; |
| 561 | } | |
| 562 | ||
| 563 | int begini, beginj, endi, endj, temphalfi, temphalfj; | |
| 564 | int beginslicei, endslicei, beginslicej, endslicej; | |
| 565 | ! | temphalfi = (kernel.n_rows-1)/2; |
| 566 | ! | temphalfj = (kernel.n_cols-1)/2; |
| 567 | ||
| 568 | ! | for (int i = halfwidth; i < rows-halfwidth; ++i) { |
| 569 | ! | Rcpp::checkUserInterrupt(); |
| 570 | ! | for (int j = halfwidth; j < cols-halfwidth; ++j) { |
| 571 | ! | if(bloom_matrix(i,j)) { |
| 572 | ! | if(progbar) { |
| 573 | ! | pb.tick(); |
| 574 | } | |
| 575 | ! | if(kernel.n_cols == 1) { |
| 576 | ! | normalize(i,j) += 1; |
| 577 | ! | result(i,j) += image(i,j); |
| 578 | ! | continue; |
| 579 | } | |
| 580 | ! | begini = i - (kernel.n_rows-1)/2; |
| 581 | ! | beginj = j - (kernel.n_cols-1)/2; |
| 582 | ! | endi = i + (kernel.n_rows-1)/2; |
| 583 | ! | endj = j + (kernel.n_cols-1)/2; |
| 584 | ! | result.submat(begini, beginj, endi, endj) += image(i,j) * kernel; |
| 585 | ! | normalize.submat(begini, beginj, endi, endj) += kernel; |
| 586 | } else { | |
| 587 | ! | result(i,j) += image(i,j); |
| 588 | ! | normalize(i,j) += 1; |
| 589 | } | |
| 590 | } | |
| 591 | } | |
| 592 | ||
| 593 | ! | for (int i = 0; i < halfwidth; ++i) { |
| 594 | ! | Rcpp::checkUserInterrupt(); |
| 595 | ! | for (int j = 0; j < cols; ++j) { |
| 596 | ! | if(bloom_matrix(i,j)) { |
| 597 | ! | if(progbar) { |
| 598 | ! | pb.tick(); |
| 599 | } | |
| 600 | ! | if(kernel.n_cols == 1) { |
| 601 | ! | normalize(i,j) += 1; |
| 602 | ! | result(i,j) += image(i,j); |
| 603 | ! | continue; |
| 604 | } | |
| 605 | ! | beginslicei = 0; |
| 606 | ! | endslicei = kernel.n_rows-1; |
| 607 | ! | beginslicej = 0; |
| 608 | ! | endslicej = kernel.n_cols-1; |
| 609 | ! | endi = i + temphalfi; |
| 610 | ! | endj = j + temphalfj; |
| 611 | ! | begini = i - temphalfi; |
| 612 | ! | beginj = j - temphalfj; |
| 613 | ! | if(i - temphalfi < 0) { |
| 614 | ! | beginslicei = temphalfi - i; |
| 615 | ! | begini = 0; |
| 616 | } | |
| 617 | ! | if(i + temphalfi > rows - 1) { |
| 618 | ! | endslicei = endslicei - (i + temphalfi - rows + 1); |
| 619 | ! | endi = rows - 1; |
| 620 | } | |
| 621 | ! | if(j - temphalfj < 0) { |
| 622 | ! | beginslicej = temphalfj - j; |
| 623 | ! | beginj = 0; |
| 624 | } | |
| 625 | ! | if(j + temphalfj > cols - 1) { |
| 626 | ! | endslicej = endslicej - (j + temphalfj - cols + 1); |
| 627 | ! | endj = cols - 1; |
| 628 | } | |
| 629 | ! | temp2 = kernel.submat(beginslicei,beginslicej,endslicei,endslicej); |
| 630 | ! | result.submat(begini, beginj, endi, endj) += image(i,j) * temp2; |
| 631 | ! | normalize.submat(begini, beginj, endi, endj) += temp2; |
| 632 | } else { | |
| 633 | ! | result(i,j) += image(i,j); |
| 634 | ! | normalize(i,j) += 1; |
| 635 | } | |
| 636 | } | |
| 637 | } | |
| 638 | ! | for (int i = halfwidth; i < rows-halfwidth; ++i) { |
| 639 | ! | Rcpp::checkUserInterrupt(); |
| 640 | ! | for (int j = 0; j < halfwidth; ++j) { |
| 641 | ! | if(bloom_matrix(i,j)) { |
| 642 | ! | if(progbar) { |
| 643 | ! | pb.tick(); |
| 644 | } | |
| 645 | ! | if(kernel.n_cols == 1) { |
| 646 | ! | normalize(i,j) += 1; |
| 647 | ! | result(i,j) += image(i,j); |
| 648 | ! | continue; |
| 649 | } | |
| 650 | ! | beginslicei = 0; |
| 651 | ! | endslicei = kernel.n_rows-1; |
| 652 | ! | beginslicej = 0; |
| 653 | ! | endslicej = kernel.n_cols-1; |
| 654 | ! | endi = i + temphalfi; |
| 655 | ! | endj = j + temphalfj; |
| 656 | ! | begini = i - temphalfi; |
| 657 | ! | beginj = j - temphalfj; |
| 658 | ! | if(i - temphalfi < 0) { |
| 659 | ! | beginslicei = temphalfi - i; |
| 660 | ! | begini = 0; |
| 661 | } | |
| 662 | ! | if(i + temphalfi > rows - 1) { |
| 663 | ! | endslicei = endslicei - (i + temphalfi - rows + 1); |
| 664 | ! | endi = rows - 1; |
| 665 | } | |
| 666 | ! | if(j - temphalfj < 0) { |
| 667 | ! | beginslicej = temphalfj - j; |
| 668 | ! | beginj = 0; |
| 669 | } | |
| 670 | ! | if(j + temphalfj > cols - 1) { |
| 671 | ! | endslicej = endslicej - (j + temphalfj - cols + 1); |
| 672 | ! | endj = cols - 1; |
| 673 | } | |
| 674 | ! | temp2 = kernel.submat(beginslicei,beginslicej,endslicei,endslicej); |
| 675 | ! | result.submat(begini, beginj, endi, endj) += image(i,j) * temp2; |
| 676 | ! | normalize.submat(begini, beginj, endi, endj) += temp2; |
| 677 | } else { | |
| 678 | ! | result(i,j) += image(i,j); |
| 679 | ! | normalize(i,j) += 1; |
| 680 | } | |
| 681 | } | |
| 682 | } | |
| 683 | ! | for (int i = halfwidth; i < rows-halfwidth; ++i) { |
| 684 | ! | Rcpp::checkUserInterrupt(); |
| 685 | ! | for (int j = cols-halfwidth; j < cols; ++j) { |
| 686 | ! | if(bloom_matrix(i,j)) { |
| 687 | ! | if(progbar) { |
| 688 | ! | pb.tick(); |
| 689 | } | |
| 690 | ! | if(kernel.n_cols == 1) { |
| 691 | ! | normalize(i,j) += 1; |
| 692 | ! | result(i,j) += image(i,j); |
| 693 | ! | continue; |
| 694 | } | |
| 695 | ! | beginslicei = 0; |
| 696 | ! | endslicei = kernel.n_rows-1; |
| 697 | ! | beginslicej = 0; |
| 698 | ! | endslicej = kernel.n_cols-1; |
| 699 | ! | endi = i + temphalfi; |
| 700 | ! | endj = j + temphalfj; |
| 701 | ! | begini = i - temphalfi; |
| 702 | ! | beginj = j - temphalfj; |
| 703 | ! | if(i - temphalfi < 0) { |
| 704 | ! | beginslicei = temphalfi - i; |
| 705 | ! | begini = 0; |
| 706 | } | |
| 707 | ! | if(i + temphalfi > rows - 1) { |
| 708 | ! | endslicei = endslicei - (i + temphalfi - rows + 1); |
| 709 | ! | endi = rows - 1; |
| 710 | } | |
| 711 | ! | if(j - temphalfj < 0) { |
| 712 | ! | beginslicej = temphalfj - j; |
| 713 | ! | beginj = 0; |
| 714 | } | |
| 715 | ! | if(j + temphalfj > cols - 1) { |
| 716 | ! | endslicej = endslicej - (j + temphalfj - cols + 1); |
| 717 | ! | endj = cols - 1; |
| 718 | } | |
| 719 | ! | temp2 = kernel.submat(beginslicei,beginslicej,endslicei,endslicej); |
| 720 | ! | result.submat(begini, beginj, endi, endj) += image(i,j) * temp2; |
| 721 | ! | normalize.submat(begini, beginj, endi, endj) += temp2; |
| 722 | } else { | |
| 723 | ! | result(i,j) += image(i,j); |
| 724 | ! | normalize(i,j) += 1; |
| 725 | } | |
| 726 | } | |
| 727 | } | |
| 728 | ! | for (int i = rows-halfwidth; i < rows; ++i) { |
| 729 | ! | Rcpp::checkUserInterrupt(); |
| 730 | ! | for (int j = 0; j < cols; ++j) { |
| 731 | ! | if(bloom_matrix(i,j)) { |
| 732 | ! | if(progbar) { |
| 733 | ! | pb.tick(); |
| 734 | } | |
| 735 | ! | if(kernel.n_cols == 1) { |
| 736 | ! | normalize(i,j) += 1; |
| 737 | ! | result(i,j) += image(i,j); |
| 738 | ! | continue; |
| 739 | } | |
| 740 | ! | beginslicei = 0; |
| 741 | ! | endslicei = kernel.n_rows-1; |
| 742 | ! | beginslicej = 0; |
| 743 | ! | endslicej = kernel.n_cols-1; |
| 744 | ! | endi = i + temphalfi; |
| 745 | ! | endj = j + temphalfj; |
| 746 | ! | begini = i - temphalfi; |
| 747 | ! | beginj = j - temphalfj; |
| 748 | ! | if(i - temphalfi < 0) { |
| 749 | ! | beginslicei = temphalfi - i; |
| 750 | ! | begini = 0; |
| 751 | } | |
| 752 | ! | if(i + temphalfi > rows - 1) { |
| 753 | ! | endslicei = endslicei - (i + temphalfi - rows + 1); |
| 754 | ! | endi = rows - 1; |
| 755 | } | |
| 756 | ! | if(j - temphalfj < 0) { |
| 757 | ! | beginslicej = temphalfj - j; |
| 758 | ! | beginj = 0; |
| 759 | } | |
| 760 | ! | if(j + temphalfj > cols - 1) { |
| 761 | ! | endslicej = endslicej - (j + temphalfj - cols + 1); |
| 762 | ! | endj = cols - 1; |
| 763 | } | |
| 764 | ! | temp2 = kernel.submat(beginslicei,beginslicej,endslicei,endslicej); |
| 765 | ! | result.submat(begini, beginj, endi, endj) += image(i,j) * temp2; |
| 766 | ! | normalize.submat(begini, beginj, endi, endj) += temp2; |
| 767 | } else { | |
| 768 | ! | result(i,j) += image(i,j); |
| 769 | ! | normalize(i,j) += 1; |
| 770 | } | |
| 771 | } | |
| 772 | } | |
| 773 | ! | if(norm) { |
| 774 | ! | return(result/normalize); |
| 775 | } else { | |
| 776 | ! | return(result); |
| 777 | } | |
| 778 | } |