简体   繁体   中英

Display Image in R

I have a 2D matrix of pixel coordinates ($n \times 2$ matrix) and a 3 dimensional ($n \times 3$ matrix) of RGB pixel values. Does anyone know of a function in R that would be able to generate the image (similar to imshow() in Python for example)?

I have googled and looked on this platform but I haven't found anything similar - I apologize if I've missed something obvious. Thanks for any help you can provide!

The imager package can help with this!

1. Prepare data for a demonstration

require( tidyr )
require( imager )

# example data from `imager` package
dat <- boats
# plot( boats )

# tall
dat_original <- as.data.frame( dat )
head( dat_original )
#  x y cc  value
#1 1 1  1 0.3882
#2 2 1  1 0.3859
#3 3 1  1 0.3849
#4 4 1  1 0.3852
#5 5 1  1 0.3860
#6 6 1  1 0.3856

dat_wide <- pivot_wider( dat_original, names_from = 'cc', values_from = 'value' )
head( dat_wide )
# A tibble: 6 × 5
#      x     y   `1`   `2`   `3`
#  <int> <int> <dbl> <dbl> <dbl>
#1     1     1 0.388 0.388 0.388
#2     2     1 0.386 0.386 0.386
#3     3     1 0.385 0.385 0.385
#4     4     1 0.385 0.385 0.385
#5     5     1 0.386 0.386 0.386
#6     6     1 0.386 0.386 0.386

2. Demonstrate

( You will need to shape your data from M2d, M3d to five columns wide so it looks like this ):

For example, you might use:

YOUR_DATA <- data.frame(
    x = M2d$x
  , y = M2d$y
  , R = M3d$red
  , G = M3d$green
  , B = M3d$blue
)
head( YOUR_DATA )
# A tibble: 6 × 5
#      x     y   R     G     B
#  <int> <int> <dbl> <dbl> <dbl>
#1     1     1 0.388 0.388 0.388
#2     2     1 0.386 0.386 0.386
#3     3     1 0.385 0.385 0.385
#4     4     1 0.385 0.385 0.385
#5     5     1 0.386 0.386 0.386
#6     6     1 0.386 0.386 0.386

Then make your data tall

dat_tall <- pivot_longer(
    YOUR_DATA
  , cols= c( 'R','G','B' )
  , names_to = 'cc'
  , values_to = 'value'
)
head(dat_tall)
## A tibble: 6 × 4
#      x     y cc    value
#  <int> <int> <chr> <dbl>
#1     1     1 1     0.388
#2     1     1 2     0.388
#3     1     1 3     0.388
#4     2     1 1     0.386
#5     2     1 2     0.386
#6     2     1 3     0.386

And fix column 'cc' (it must be an integer, not a character)

dat_tall$cc %<>% as.integer
## A tibble: 6 × 4
#      x     y    cc value
#  <int> <int> <int> <dbl>
#1     1     1     1 0.388
#2     1     1     2 0.388
#3     1     1     3 0.388
#4     2     1     1 0.386
#5     2     1     2 0.386
#6     2     1     3 0.386

Finally, make an image

image_data <- dat_tall
as.cimg( image_data ) %>% plot

成像仪包中的帆船图像

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM