- 修改 ImageDir 函数增加 darkScore 和 lightScore 参数 - 实现 BrightnessName 函数计算明暗等级 - 定义暗色和亮色阈值等级数组 - 在 organize.go 中集成图片明暗分析逻辑 - 使用 ITU-R BT.601 公式计算像素亮度 - 为大图实现自动采样加速分析 - 更新 README.md 文档说明明暗分类算法 - 在目录结构中体现明暗等级命名规则
68 lines
1.6 KiB
Go
68 lines
1.6 KiB
Go
package probe
|
|
|
|
import (
|
|
"image"
|
|
"math"
|
|
"os"
|
|
|
|
_ "image/gif"
|
|
_ "image/jpeg"
|
|
_ "image/png"
|
|
|
|
_ "golang.org/x/image/bmp"
|
|
_ "golang.org/x/image/tiff"
|
|
_ "golang.org/x/image/webp"
|
|
)
|
|
|
|
// AnalyzeBrightness 打开并解码图片,分析明暗程度。
|
|
// darkScore: 暗色像素(亮度 < 80)占比;lightScore: 亮色像素(亮度 > 175)占比。
|
|
func AnalyzeBrightness(filePath string) (darkScore float64, lightScore float64, err error) {
|
|
f, err := os.Open(filePath)
|
|
if err != nil {
|
|
return 0, 0, err
|
|
}
|
|
defer f.Close()
|
|
img, _, err := image.Decode(f)
|
|
if err != nil {
|
|
return 0, 0, err
|
|
}
|
|
dark, light := analyzeBrightness(img)
|
|
return dark, light, nil
|
|
}
|
|
|
|
// analyzeBrightness 统计暗色/亮色像素占比(ITU-R BT.601 亮度公式),大图自动采样加速
|
|
func analyzeBrightness(img image.Image) (darkScore float64, lightScore float64) {
|
|
bounds := img.Bounds()
|
|
totalPixels := bounds.Dx() * bounds.Dy()
|
|
if totalPixels == 0 {
|
|
return 0, 0
|
|
}
|
|
|
|
darkCount, lightCount, sampleCount := 0, 0, 0
|
|
sampleStep := 1
|
|
if totalPixels > 1_000_000 {
|
|
sampleStep = int(math.Sqrt(float64(totalPixels) / 100_000))
|
|
}
|
|
|
|
for y := bounds.Min.Y; y < bounds.Max.Y; y += sampleStep {
|
|
for x := bounds.Min.X; x < bounds.Max.X; x += sampleStep {
|
|
r, g, b, _ := img.At(x, y).RGBA()
|
|
r8 := uint8(r >> 8)
|
|
g8 := uint8(g >> 8)
|
|
b8 := uint8(b >> 8)
|
|
brightness := 0.299*float64(r8) + 0.587*float64(g8) + 0.114*float64(b8)
|
|
if brightness < 80 {
|
|
darkCount++
|
|
} else if brightness > 175 {
|
|
lightCount++
|
|
}
|
|
sampleCount++
|
|
}
|
|
}
|
|
|
|
if sampleCount == 0 {
|
|
return 0, 0
|
|
}
|
|
return float64(darkCount) / float64(sampleCount), float64(lightCount) / float64(sampleCount)
|
|
}
|