1

I want to add a text on an given co-ordinates of an image using the gocv library (also the text should expand from the co-ordinates; not from left to right).

Using the below command I was able to achieve both requirements. How can I load a custom .ttf font file and do the same thing ?

import (
    "fmt"
    "image"
    "image/color"
    "os"

    "github.com/gofiber/fiber/v2"
    "gocv.io/x/gocv"
)

func GeneralRoutes(gen fiber.Router) {
    gen.Get("/image", func(c *fiber.Ctx) error {
        imageFile := "path/input.png"
        outputFile := "path/output.jpg"

        img := gocv.IMRead(imageFile, gocv.IMReadColor)
        if img.Empty() {
            fmt.Printf("Error opening image: %s\n", imageFile)
            os.Exit(1)
        }

        // Create a font type and scale
        font := gocv.FontHersheyPlain
        scale := 5.5
        thickness := 5

        // Define the text to be added, position, font type and color
        text := "Hello World"

        textSize := gocv.GetTextSize(text, font, scale, thickness)

        textPos := img.Point{X: 1170 - textSize.X/2, Y: 663 - textSize.Y/2}

        gocv.PutText(&img, text, textPos, font, scale, color.RGBA{0, 0, 0, 0}, thickness)

        // Save the output image
        gocv.IMWrite(outputFile, img)

        return c.SendFile(outputFile)
    })
}
  • 1
    if gocv is OpenCV, and you want arbitrary font support, you need the "freetype" module from the contrib repo. – Christoph Rackwitz Jan 11 '23 at 14:44
  • Does this answer your question? [AttributeError: module 'cv2.cv2' has no attribute 'freetype' in OpenCV](https://stackoverflow.com/questions/55961893/attributeerror-module-cv2-cv2-has-no-attribute-freetype-in-opencv) – Christoph Rackwitz Jan 11 '23 at 14:44
  • It should also be possible if you have OpenCV built with Qt HighGUI backend: https://docs.opencv.org/4.7.0/dc/d46/group__highgui__qt.html#ga4e2751b94f709c848f0658d78007e449 – Dan Mašek Jan 11 '23 at 15:00
  • @ChristophRackwitz The freetype module is not implemented on gocv yet – dasunNimantha Jan 11 '23 at 15:19

0 Answers0