I need to pre-process an image to convert it to a high contrast dark-on-light background that is ideal to feed to OCR tools.
The pre-processing, which for starters I did in Gimp, simply involves running its Color->Invert
operation, which gives me a result that works very well when fed into OCR tools.
This question though is how to replicate the same operation via OpenCV.
The following is the OpenCV code (via the Go wrapper for OpenCV) that I have managed so far:
func preprocessImage(inputImage gocv.Mat) {
white := gocv.NewMatWithSizeFromScalar(
gocv.Scalar{255.0, 255.0, 255.0, 255.0},
inputImage.Rows(), inputImage.Cols(),
inputImage.Type()
)
targetMat := gocv.NewMat()
gocv.Subtract(white, inputImage, &targetMat)
pngCompressionOptions := []int{gocv.IMWritePngCompression, 0}
gocv.IMWrite("result.png", targetMat, pngCompressionOptions)
}
However, this does not seem to match the results I obtain from Gimp.
As a sample, here's the original image:
Here's the result of applying Color->Invert
via Gimp:
Here's the result I get via the OpenCV code shown above:
As is evident, there seems to quite some difference between the two results.
Gimp's documentation on what exactly Color->Invert does is a bit cryptic, at least to me. It mentions that "hues are replaced by their complementary colors" but am unclear as to how to replicate that.
Just to be clear, I am not expecting working Golang code in the answers. I am just looking for some hints as to what OpenCV functions I should string together (in any language, I can port that to Go) in order to replicate Gimp's Color-Invert
operation.
I am unfamiliar with Go
, but it looks like your image got converted to greyscale on opening.
Check your flags/parameters where you loaded it and that you have at least three, rather than one single channel.