Converting 16 Bit JPEG2000 greyscale image to 8 bit JPG causes loss of image quality
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 pixelvalue is 4 and themin pixelvalue 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 pixelvalue is 239 and themin pixelvalue 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 sharpcompletes 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
sharpas reported bynpm 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?
- Download the attached file
input.jp2 - 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
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");

Is there a possibility of us putting in manual normalization values to the function in future? It would really help
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");
@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.

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()
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 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?
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.