How to Convert an Image of Text into a Binarized (Light & Dark) View using Go

Cloudmersive
2 min readNov 25, 2022

The Cloudmersive Optical Character Recognition (OCR) endpoint offers a variety of direct image-to-text conversion services for your personal & professional projects. While many essential OCR preprocessing features are built into these API services, you can also access & utilize those same preprocessing features through independent API calls for your own applications as well.

Binarization (converting images to light and dark view) is one such critical step in OCR preprocessing, and using the complementary code examples below, you can call our independent Binarization preprocessing API with ease. This API will perform an adaptive binarization algorithm on your input image, converting it to light & dark view, ensuring it is well-prepared for future OCR operations.

To call this API for free, you’ll first need to get a free-tier Cloudmersive API key by registering a free account on our website (this will provide a limit of 800 API calls per month). After that, simply copy & paste the complementary code examples provided below into your file and include your file path in the appropriate field (labeled in the code comments). That’s all there is to it!

package main

import (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)

func main() {

url := "https://api.cloudmersive.com/ocr/preprocessing/image/binarize"
method := "POST"

payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, errFile1 := os.Open("/path/to/file")
defer file.Close()
part1,
errFile1 := writer.CreateFormFile("imageFile",filepath.Base("/path/to/file"))
_, errFile1 = io.Copy(part1, file)
if errFile1 != nil {
fmt.Println(errFile1)
return
}
err := writer.Close()
if err != nil {
fmt.Println(err)
return
}


client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)

if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "multipart/form-data")
req.Header.Add("Apikey", "YOUR-API-KEY-HERE")

req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()

body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.