func NewImageAPI(trainingDir string) *ImageAPI { // Creates a drawing channel and scores map drawingChan := make(chan classifier.Drawing) scores := make(map[string]float64) // Do the 'training' go classifier.ReadDrawings(trainingDir, drawingChan) for drawing := range drawingChan { score := classifier.TrainFromDrawings(drawing) scores[drawing.Classification] = score } return &ImageAPI{ Scores: scores, } }
func (api *ImageAPI) classifyHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Content-Type", "application/json") imageEncoded := r.FormValue("image") reader := base64.NewDecoder( base64.StdEncoding, strings.NewReader(imageEncoded)) image, err := jpeg.Decode(reader) if err != nil { http.Error(w, err.Error(), 500) return } result := classifier.TrainFromDrawings( classifier.Drawing{Image: image}) closestClassification := "" closestDistance := math.Inf(0) // Loop through and find the best classification for classification, score := range api.Scores { if distance := math.Abs(result - score); distance < closestDistance { closestClassification = classification closestDistance = distance } } jsonBytes, err := json.Marshal(struct { Classification string `json:",omitempty"` Distance float64 `json:",omitempty"` }{closestClassification, closestDistance}) if err != nil { log.Println(err) http.Error(w, err.Error(), 500) return } fmt.Fprintf(w, string(jsonBytes)) }