-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
218 lines (174 loc) · 4.73 KB
/
main.go
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
76
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
127
128
129
130
131
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package main
import (
"bufio"
"container/heap"
"errors"
"fmt"
"image"
"image/color"
_ "image/jpeg"
_ "image/png"
"net/http"
"os"
"runtime"
"sync"
"github.com/jeffvswanson/colorchallenge/exporttocsv"
log "github.com/jeffvswanson/colorchallenge/errorlogging"
)
type imageInfo struct {
p *http.Response
URL string
}
type colorNode struct {
Color color.Color
Occurrences int
}
// A colorHeap is a max-heap of the colors found from an image.
type colorHeap []colorNode
func (c colorHeap) Len() int { return len(c) }
func (c colorHeap) Less(i, j int) bool { return c[i].Occurrences < c[j].Occurrences }
func (c colorHeap) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c *colorHeap) Push(x interface{}) {
// Push and Pop use pointer receivers because they modify the
// slices's length not just its contents.
*c = append(*c, x.(colorNode))
}
func (c *colorHeap) Pop() interface{} {
old := *c
n := len(old)
x := old[n-1]
*c = old[0 : n-1]
return x
}
var logfile, csvfile *os.File
func init() {
logfile = log.FormatLog()
csvfile = exporttocsv.CreateCSV("ColorChallengeOutput")
headerRecord := []string{"URL", "top_color1", "top_color2", "top_color3"}
exporttocsv.Export(csvfile, headerRecord)
}
func main() {
defer logfile.Close()
defer csvfile.Close()
inputFilename := "input_test.txt"
// Setup
log.Write("Info", "Beginning setup", nil)
// Grab the URLs to parse
status := extractURLs(inputFilename, csvfile)
log.Write("Info", status, nil)
}
// extractURLs pulls the URLs from the given file for image processing.
func extractURLs(inFilename string, csv *os.File) string {
f, err := os.Open(inFilename)
if err != nil {
log.Write("Fatal", "URL extraction failed during setup.", err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
var wgCPU sync.WaitGroup
var wgIO sync.WaitGroup
urlChan := make(chan string)
images := make(chan imageInfo)
// Spawn workers to prevent saturating bandwidth.
workersIO := 10
for i := 0; i < workersIO; i++ {
wgIO.Add(1)
go func() {
for url := range urlChan {
extractImageData(url, images)
}
wgIO.Done()
}()
}
// While constrained to 1 processor, maybe we'll get lucky.
workersCPU := runtime.GOMAXPROCS(-1)
// Spawn workers to prevent running out of memory.
for i := 0; i < workersCPU; i++ {
wgCPU.Add(1)
go func() {
for image := range images {
output := countColors(image)
if output != nil {
exporttocsv.Export(csv, output)
}
}
wgCPU.Done()
}()
}
for scanner.Scan() {
urlChan <- scanner.Text()
}
if err != nil {
log.Write("Fatal", "Error scanning: ", err)
}
close(urlChan)
wgIO.Wait()
close(images)
wgCPU.Wait()
return "Process complete."
}
// extractImageData extracts the image from a given URL.
func extractImageData(url string, images chan<- imageInfo) {
resp, err := http.Get(url)
if err != nil {
log.Write("Warning", "http.Get failure - ", err)
return
}
if resp.StatusCode != http.StatusOK {
log.Write("Warning", fmt.Sprintf("%s http status not ok", url), errors.New(resp.Status))
return
}
img := imageInfo{
resp,
url,
}
images <- img
}
// countColors finds pixel color mapping of an image in RGB format.
func countColors(i imageInfo) []string {
// Extract the image information.
defer i.p.Body.Close()
img, _, err := image.Decode(i.p.Body)
if err != nil {
log.Write("Warning", fmt.Sprintf("%s image decode error", i.URL), err)
return nil
}
timesAppeared := make(map[color.Color]int)
for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
// img returns in YCbCr format will convert to RGB 8-bit on top 3 color return
yCbCr := img.At(x, y).(color.Color)
timesAppeared[yCbCr.(color.Color)]++
}
}
// Sort colors in descending order.
output := heapify(timesAppeared)
// Get the output string into url,color,color,color format.
output[0] = i.URL
return output
}
// heapify turns the color set into a max-heap data structure
func heapify(timesAppeared map[color.Color]int) []string {
c := make(colorHeap, 0, len(timesAppeared))
for color, appeared := range timesAppeared {
// Multiply by -1 since standard heap is a min-heap, this makes
// it a max-heap.
c = append(c, colorNode{color, appeared * -1})
}
h := &c
heap.Init(h)
return extractTopColors(h)
}
// extractTopColors pulls out the top 3 top colors in the image and
// returns them in hexadecimal format.
func extractTopColors(h *colorHeap) []string {
topColors := make([]string, 4)
for i := 1; i < 4; i++ {
c := heap.Pop(h).(colorNode)
// Convert the YCbCr format to RGB
rgb := color.NRGBAModel.Convert(c.Color).(color.NRGBA)
hexColor := fmt.Sprintf("#%.2X%.2X%.2X", rgb.R, rgb.G, rgb.B)
topColors[i] = hexColor
}
return topColors
}