goimagehash/transforms/pixels.go

39 lines
1.1 KiB
Go
Raw Normal View History

2017-07-28 10:18:24 -07:00
// Copyright 2017 The goimagehash Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package transforms
import (
"image"
2024-04-05 16:29:03 -07:00
"image/color"
2017-07-28 10:18:24 -07:00
)
2024-04-05 16:29:03 -07:00
func toGray(r, g, b uint8) uint8 {
// 19595 + 38470 + 7471 equals 65536.
return uint8((19595*uint32(r) + 38470*uint32(g) + 7471*uint32(b) + 1<<15) >> 16)
2017-07-28 10:18:24 -07:00
}
2024-04-05 16:29:03 -07:00
// Rgb2Gray function converts RGB to a gray scale array.
func Rgb2Gray(colorImg image.Image) []uint8 {
colorImg.Bounds().Dx()
bounds := colorImg.Bounds()
2024-04-05 16:29:03 -07:00
w, h := bounds.Dx(), bounds.Dy()
pixels := make([]uint8, h*w)
for i := range pixels {
x, y := i%w, i/w
var R, G, B uint32
switch v := colorImg.At(x, y).(type) {
case color.NRGBA: // pillow discards alpha during conversion and provides no way to pre-multiply it
R, G, B = uint32(v.R)<<8, uint32(v.G)<<8, uint32(v.B)<<8
default:
R, G, B, _ = colorImg.At(x, y).RGBA()
}
2024-04-05 16:29:03 -07:00
// Pillow only operates on 8bit data, operating on higher bit data produces rounding differences
pixels[i] = toGray(uint8(R>>8), uint8(G>>8), uint8(B>>8))
}
2024-04-05 16:29:03 -07:00
return pixels
}