disintegration / imaging

Imaging is a simple image processing package for Go
MIT License
5.28k stars 440 forks source link

Scaling is not gamma-aware #80

Closed ypomortsev closed 6 years ago

ypomortsev commented 6 years ago

Thanks for your hard work on this library! Please consider making the scaling gamma-aware. For example, scaling this image down 50%:

gamma_dalai_lama_gray

produces:

out

but should look like:

gamma_dalai_lama_gray_good

This is the code I used to generate the scaled versions.

See Eric Brasseur's Gamma error in picture scaling for more details.

disintegration commented 6 years ago

You are right, the implemented image processing functions do not convert images to/from a linear color space. It was a deliberate decision (at least for v1 of the package). Here are some considerations:

If you really need a more accurate image scaling, consider using the other package I wrote - github.com/disintegration/gift. Here's the example:

package main

import (
    "image"
    _ "image/jpeg"
    "image/png"
    "log"
    "os"

    "github.com/disintegration/gift"
)

func main() {
    src, err := loadImage("gamma_dalai_lama_gray.jpg")
    if err != nil {
        log.Fatal(err)
    }

    w, h := src.Bounds().Dx()/2, src.Bounds().Dy()/2

    g := gift.New(
        gift.ColorspaceSRGBToLinear(),
        gift.Resize(w, h, gift.LanczosResampling),
        gift.ColorspaceLinearToSRGB(),
    )
    dst := image.NewRGBA(g.Bounds(src.Bounds()))
    g.Draw(dst, src)

    err = saveImage("out.png", dst)
    if err != nil {
        log.Fatal(err)
    }
}

func loadImage(filename string) (image.Image, error) {
    file, err := os.Open(filename)
    if err != nil {
        return nil, err
    }
    defer file.Close()
    img, _, err := image.Decode(file)
    if err != nil {
        return nil, err
    }
    return img, nil
}

func saveImage(filename string, img image.Image) error {
    file, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer file.Close()
    if err := png.Encode(file, img); err != nil {
        return err
    }
    return nil
}

gamma_dalai_lama_gray out

ypomortsev commented 6 years ago

Very cool, thanks for the thorough answer. I'll check out gift.