feat(classify): 添加图片明暗分类功能

- 修改 ImageDir 函数增加 darkScore 和 lightScore 参数
- 实现 BrightnessName 函数计算明暗等级
- 定义暗色和亮色阈值等级数组
- 在 organize.go 中集成图片明暗分析逻辑
- 使用 ITU-R BT.601 公式计算像素亮度
- 为大图实现自动采样加速分析
- 更新 README.md 文档说明明暗分类算法
- 在目录结构中体现明暗等级命名规则
This commit is contained in:
2025-03-29 21:11:14 +08:00
parent 4da4b738e6
commit 99b9460bcd
5 changed files with 149 additions and 25 deletions
+67
View File
@@ -0,0 +1,67 @@
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)
}