process_image.go 4.36 KB
Newer Older
Michael Yang's avatar
Michael Yang committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package llama4

import (
	"cmp"
	"image"
	"math"
	"slices"
	"sort"

	"golang.org/x/image/draw"

	"github.com/ollama/ollama/fs"
	"github.com/ollama/ollama/model/imageproc"
)

type ImageProcessor struct {
	imageSize, patchSize, numChannels, maxUpscalingSize int
}

func newImageProcessor(c fs.Config) ImageProcessor {
	return ImageProcessor{
		imageSize:        int(c.Uint("vision.image_size")),
		patchSize:        int(c.Uint("vision.patch_size")),
		numChannels:      int(c.Uint("vision.num_channels", 3)),
		maxUpscalingSize: int(c.Uint("vision.max_upscaling_size", 448)),
	}
}

func factors(n int) []int {
	var result []int
	seen := make(map[int]bool)

	for i := 1; i <= n/2; i++ {
		if n%i == 0 && !seen[i] {
			result = append(result, i)
			seen[i] = true
		}
	}

	result = append(result, n)
	sort.Ints(result)

	return result
}

func (p ImageProcessor) supportedResolutions() []image.Point {
	var resolutions []image.Point

	aspectMap := make(map[float64][]image.Point)
	for i := p.patchSize; i >= 1; i-- {
		for _, f := range factors(i) {
			x := f
			y := i / f
			k := float64(y) / float64(x)
			aspectMap[k] = append(aspectMap[k], image.Point{x, y})
		}
	}

	for _, v := range aspectMap {
		for _, i := range v {
			resolutions = append(resolutions, image.Point{i.X * p.imageSize, i.Y * p.imageSize})
		}
	}

	return resolutions
}

func (p ImageProcessor) bestResolution(img image.Point, possibleResolutions []image.Point, resizeToMaxCanvas bool) image.Point {
	w, h := img.X, img.Y

	scales := make([]float64, len(possibleResolutions))

	for i, res := range possibleResolutions {
		scaleW := float64(res.X) / float64(w)
		scaleH := float64(res.Y) / float64(h)
76
		scale := min(scaleW, scaleH)
Michael Yang's avatar
Michael Yang committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126

		scales[i] = scale
	}

	minAboveOne := func(scales []float64) (float64, bool) {
		min := math.MaxFloat64
		found := false

		for _, s := range scales {
			if s >= 1.0 && s < min {
				min = s
				found = true
			}
		}

		return min, found
	}

	bestScale, ok := minAboveOne(scales)
	if resizeToMaxCanvas || !ok {
		bestScale = slices.Max(scales)
	}

	var bestOptions []image.Point
	for i, scale := range scales {
		if math.Abs(scale-bestScale) < 1e-6 {
			bestOptions = append(bestOptions, possibleResolutions[i])
		}
	}

	var chosenResolution image.Point
	if len(bestOptions) > 1 {
		chosenResolution = slices.MinFunc(bestOptions, func(a, b image.Point) int {
			return cmp.Compare(a.X*a.Y, b.X*b.Y)
		})
	} else {
		chosenResolution = bestOptions[0]
	}

	return chosenResolution
}

func (p ImageProcessor) maxResolution(imageRes, targetRes image.Point) image.Point {
	scaleW := float64(targetRes.X) / float64(imageRes.X)
	scaleH := float64(targetRes.Y) / float64(imageRes.Y)

	var newRes image.Point
	if scaleW < scaleH {
		newRes = image.Point{
			targetRes.X,
127
			int(min(math.Floor(float64(imageRes.Y)*scaleW), float64(targetRes.Y))),
Michael Yang's avatar
Michael Yang committed
128
129
130
		}
	} else {
		newRes = image.Point{
131
			int(min(math.Floor(float64(imageRes.X)*scaleH), float64(targetRes.X))),
Michael Yang's avatar
Michael Yang committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
			targetRes.Y,
		}
	}

	return newRes
}

func (p ImageProcessor) pad(src image.Image, outputSize image.Point) image.Image {
	dst := image.NewRGBA(image.Rect(0, 0, outputSize.X, outputSize.Y))
	draw.Draw(dst, src.Bounds(), src, image.Point{}, draw.Over)
	return dst
}

func (p ImageProcessor) ProcessImage(img image.Image) (pixelsLocal, pixelsGlobal []float32, targetSize image.Point, _ error) {
	img = imageproc.Composite(img)

	targetSize = p.bestResolution(img.Bounds().Max, p.supportedResolutions(), false)
	targetSizeWithoutDistortion := targetSize
	if p.maxUpscalingSize > 0 {
		targetSizeWithoutDistortion = p.maxResolution(img.Bounds().Max, targetSize)
		targetSizeWithoutDistortion.X = min(max(img.Bounds().Max.X, p.maxUpscalingSize), targetSize.X)
		targetSizeWithoutDistortion.Y = min(max(img.Bounds().Max.Y, p.maxUpscalingSize), targetSize.Y)
	}

	newSizeWithoutDistortion := p.maxResolution(img.Bounds().Max, targetSizeWithoutDistortion)

	padded := p.pad(imageproc.Resize(img, newSizeWithoutDistortion, imageproc.ResizeBilinear), targetSize)
	pixelsLocal = imageproc.Normalize(padded, imageproc.ImageNetStandardMean, imageproc.ImageNetStandardSTD, true, true)

	if targetSize.X/p.imageSize*targetSize.Y/p.imageSize > 1 {
		padded := imageproc.Resize(img, image.Point{p.imageSize, p.imageSize}, imageproc.ResizeBilinear)
		pixelsGlobal = imageproc.Normalize(padded, imageproc.ImageNetStandardMean, imageproc.ImageNetStandardSTD, true, true)
	}

	return pixelsLocal, pixelsGlobal, targetSize, nil
}