rtiffimager

How do I convert this tif file to jpeg without losing information in R


I have the following 32-bit 180 dpi tif image: https://drive.google.com/file/d/1C6Ink5cZAVnvwNfVceQgMycOwhh6Q-M8/view?usp=drive_link

I want to do an analysis using R's imager package, which requires conversion to a different format. I am reading the image into R using the following code:

img <- readTIFF("image1.tif")

which gives me the warning message "TIFFReadDirectory: Unknown field with tag 33821 (0x841d) encountered" and a matrix with an range of 5-314.1667

if I then use writeJPEG(img, "image1.jpeg"), I get a matrix in with a min of 0 and a max of 1, which as an image is totally washed out and has lost most of the shading information. If I use writeTIFF(img, "image2.tiff"), I get the error "The input contains values outside the [0, 1] range - storage of such values is undefined", and an image that looks very different from the original tif. writePNG has the same problem.

How do I get R to preserve the data in my tif file during conversion to a format that imager can handle?


Solution

  • Why to convert it to jpeg? Which is a/ lossy compression format, b/ supports only 8-bit per channel? What's the reason behind? You can use imager::as.cimg() directly:

    img <- tiff::readTIFF("/home/sapi/Downloads/image1.tif", info = TRUE) |>
      imager::as.cimg()
    #> Warning in tiff::readTIFF("/home/sapi/Downloads/image1.tif", info = TRUE):
    #> TIFFReadDirectory: Unknown field with tag 33821 (0x841d) encountered
    
    img
    #> Image. Width: 480 pix Height: 720 pix Depth: 1 Colour channels: 1
    
    plot(img)
    

    And to prove that it's a proper class and contains proper values:

    class(img)
    #> [1] "cimg"         "imager_array" "numeric"
    
    img[1,c(1:20)]
    #>  [1]  64.0000  64.0000   5.0000 294.5333 288.7333 281.3333 291.6333 305.4333
    #>  [9] 303.8000 291.5000 277.3667 280.6333 309.0000 360.3333 400.7667 431.4000
    #> [17] 421.4667 400.4667 396.7667 360.1000
    

    Created on 2024-02-29 with reprex v2.1.0