sharp icon indicating copy to clipboard operation
sharp copied to clipboard

Converting 16 Bit JPEG2000 greyscale image to 8 bit JPG causes loss of image quality

Open LachlanNewman opened this issue 3 years ago • 6 comments

Possible bug

When trying to convert a 16-bit greyscale JPEG2000 image to an 8-bit JPG image there is a loss in the quality of the output. (see attached actual_output.jpg

Other Useful Information

  • When printing the stats of the image when it is first read, the max pixel value is 4 and the min pixel value is 0. this doesn't make any sense because when you open the image in a JPG2000-compatible platform (see https://nroduit.github.io/en/) it shows a much larger range of shades of grey.
  • also after normalizing the image the max pixel value is 239 and the min pixel value is 15. Shouldn't it stretch the luminance range so it's between 0 and 255?

Is this a possible bug in a feature of sharp, unrelated to installation?

  • [x] Running npm install sharp completes without error.
  • [x] Running node -e "require('sharp')" completes without error.

Are you using the latest version of sharp?

  • [x] I am using the latest version of sharp as reported by npm view sharp dist-tags.latest.

What is the output of running npx envinfo --binaries --system --npmPackages=sharp --npmGlobalPackages=sharp?

  System:
    OS: macOS 12.3.1
    CPU: (10) arm64 Apple M1 Pro
    Memory: 65.33 MB / 32.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.14.0 - ~/.nvm/versions/node/v16.14.0/bin/node
    Yarn: 1.22.17 - ~/.nvm/versions/node/v16.14.0/bin/yarn
    npm: 8.3.1 - ~/.nvm/versions/node/v16.14.0/bin/npm
  npmPackages:
    sharp: ^0.31.3 => 0.31.3 

What are the steps to reproduce?

  1. Download the attached file input.jp2
  2. run the sample script below in Node.

What is the expected behaviour?

should convert the image to 8 bits. negate the image and normalize the pixels from 0 to 255 and produce an image similar to the attachment expected_output.jpg

Please provide a minimal, standalone code sample, without other dependencies, that demonstrates this problem

import sharp from 'sharp'
import fs from 'fs'

async function convertToJpeg() {
      const imageBytes = fs.readFileSync(`path/to/input.jp2`);

      const output = await sharp(imageBytes)
      .gamma()
      .grayscale()
      .negate({alpha: true})
      .normalise()
      .toFormat('jpg')
      .toBuffer()

      fs.writeFileSync(`output/output.jpg`,output)
}

convertToJpeg()

Please provide sample image(s) that help explain this problem

images.zip

LachlanNewman avatar Feb 28 '23 01:02 LachlanNewman

This appears to be unrelated to JPG2000, as converting the input to a 16-bit greyscale PNG produces a similar result.

The input image is very dark, with little variance in pixel values. Image normalisation is histogram-based and throws away the lowest and highest ~2% of bins, and this is where I think data is being discarded.

Increasing the brightness via .modulate({ brightness }) should help. You may need to split the work into a couple of pipelines to ensure the operation ordering is exactly what you need.

https://sharp.pixelplumbing.com/api-operation#modulate

sharp("16-bit-grey.png")
  .resize(360)
  .modulate({ brightness: 8 })
  .normalise()
  .toFile("normalised.png");

normalised.png

lovell avatar Feb 28 '23 15:02 lovell

Is there a possibility of us putting in manual normalization values to the function in future? It would really help

jonseppanen avatar Mar 01 '23 00:03 jonseppanen

This appears to be unrelated to JPG2000, as converting the input to a 16-bit greyscale PNG produces a similar result.

The input image is very dark, with little variance in pixel values. Image normalisation is histogram-based and throws away the lowest and highest ~2% of bins, and this is where I think data is being discarded.

Increasing the brightness via .modulate({ brightness }) should help. You may need to split the work into a couple of pipelines to ensure the operation ordering is exactly what you need.

https://sharp.pixelplumbing.com/api-operation#modulate

sharp("16-bit-grey.png")
  .resize(360)
  .modulate({ brightness: 8 })
  .normalise()
  .toFile("normalised.png");

normalised.png

@lovell thanks so much for your help. the output looks great however I still need to run the negate function because the current output is the negative of the x-ray. however when I run negate after applying modulate and normalize i get a completely white png. (see attached)

updated code

import sharp from 'sharp'
import fs from 'fs'

async function convertToJpeg() {
      const imageBytes = fs.readFileSync(`path/to/input.jp2`);

      const output = await sharp(imageBytes)
      .resize(360)
      .modulate({ brightness: 8 })
      .normalise()
      .negate({alpha: true})
      .toFile("normalised.png");
}


convertToJpeg()

note: I've tried to write the output as a png and I still get the same white image.

normalised

Update

For some reason when I create a new sharp instance after calling modulate and normalize and then call negate it works.

async function convertToJpeg() {
      const imageBytes = fs.readFileSync(`path/to/input.jp2`);

      const output = await sharp(imageBytes)
      .resize(360)
      .modulate({ brightness: 8 })
      .normalise()
     
      await sharp(await output.toBuffer()).negate().toFile('normalise_negate.png')
}


convertToJpeg()

LachlanNewman avatar Mar 01 '23 01:03 LachlanNewman

when I create a new sharp instance...

Yes, this is what I was referring to when I said you "may need to split the work into a couple of pipelines".

lovell avatar Mar 03 '23 11:03 lovell

@lovell was there a way you determined the value of brightness required based on the image where all the pixels lied within the lower 1 % of the spectrum or was that just trial and error?

LachlanNewman avatar Mar 08 '23 10:03 LachlanNewman

I probably got lucky, but it should be possible to calculate a suitable value based on the min and max values from stats().

In the 16-bit sample image you provided, the max pixel value in the image is only 1023 so there's plenty of headroom to increase brightness given the ushort range is 0-65535.

lovell avatar Mar 09 '23 15:03 lovell