Sharp: Calculate and expose a sharpness value in stats

Created on 9 Jun 2020  路  4Comments  路  Source: lovell/sharp

Big fan of your work on sharp and thanks for doing what you do and working on it! I've been using it a lot along side Gatsby and Electron projects.

What are you trying to achieve?
Have a sharpness value in the stats object, in order to make assumptions about blurry images.

Have you searched for similar feature requests?
I have. Found nothing.

What would you expect the API to look like?

const stats = await sharp(image)
      .stats()
      .then(stats => stats)
console.log('Sharpness: ', stats.sharpness)

What alternatives have you considered?
Calculating myself (or using OpenCV) by converting a single channel to grayscale and calculating a Laplacian. (There are some resources online on how to do this, here's one for context)

Is there a sample image that helps explain?
Here is some image from Unsplash:

sergei-akulich-ZNkvxIPPVeE-unsplash
Photo by Sergei Akulich on Unsplash

And here is the same image blurred a bit manually in GIMP:
sergei-akulich-ZNkvxIPPVeE-unsplash-blurred

Basically I think it would be a great feature for sharp to have, since it already has low level access to raw image data. I'm not completely sure how hard it would be to implement, so figured I'd open a ticket to see how you feel about it, as well any potential users of the feature.

enhancement ready-to-ship

Most helpful comment

Great, glad it worked, I went ahead and added it to the stats() response via commit 8f5495a - this will be in v0.25.4.

All 4 comments

Hi, the following function should provide what you're looking for:

const sharpness = (input) =>
  sharp(input)
    .greyscale()
    .convolve({
      width: 3,
      height: 3,
      kernel: [0, 1, 0, 1, -4, 1, 0, 1, 0],
    })
    .raw()
    .toBuffer({ resolveWithObject: true })
    .then(({ data, info }) => sharp(data, { raw: info }).stats())
    .then(({ channels }) => channels[0].stdev);

I see a value of ~18 for the original image and ~1.5 for the blurred image.

@lovell Thanks a lot for this. It works pretty reliably and is about ~ 2x more performant than the OpenCV for NodeJs counterpart.

Great, glad it worked, I went ahead and added it to the stats() response via commit 8f5495a - this will be in v0.25.4.

v0.25.4 now available, thank you for suggesting this improvement.

Was this page helpful?
0 / 5 - 0 ratings