19

I'm trying using opencv python codes for my mini project that is Basic paint application.

I want to write a text on my image in run-time application. Not before running the code or hard coded text. How can I do that?

I need help for that, Thanks.

Shriniwas
  • 664
  • 3
  • 11
  • 25

1 Answers1

39

Here is how its done in OpenCV

You can add text to your image using cv2.putText() function For example: cv2.putText(img,'OpenCV',(10,500), font, 4, (255, 255, 255), 2, cv2.LINE_AA)

Check THIS LINK for more details

Here is an example:

import cv2
im = cv2.imread(path + 'pillar.png', 1)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(im, 'Christmas', (10,450), font, 3, (0, 255, 0), 2, cv2.LINE_AA)
cv2.imwrite(path + 'pillar_text.jpg', im)

enter image description here

UPDATE

I used the chr() function to enter the values of the keys being entered. For every character typed the image would be updated in a while loop. Here is a sample code:

import cv2
path = "C:/Users//Desktop/ocean.jpg"

img = cv2.imread(path)

font = cv2.FONT_HERSHEY_SIMPLEX

i = 10
while(1):
    cv2.imshow('img',img)

    k = cv2.waitKey(33)
    if k==27:    # Esc key to stop
        break
    elif k==-1:  # normally -1 returned,so don't print it
        continue
    else:
        print (k) # else print its value
       cv2.putText(img, chr(k), (i, 50), font, 1, (0, 255, 0), 1, cv2.LINE_AA)
        i+=15

cv2.waitKey(0)
cv2.destroyAllWindows()

Instructions:

  1. Press any key to enter its value
  2. Press Esc key to end the program
Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
  • Thanks for replying.... I did that before what you have shown up there...That is okay..But my point is how can I write or type text on already opened Image.? Like Say..The program for importing and displaying image, and after executing your program at run-time when your image is popup on screen, that time we have to write text on that image.. I hope you will understand what I am saying.!!! Thanks – Shriniwas May 07 '18 at 04:36
  • like we use "Insert text into the picture" tool from Paint. "A" looking symbol in Paint. – Shriniwas May 07 '18 at 04:53
  • @Niranjankulkarni have a look at the update and see if it suits your requirement – Jeru Luke May 07 '18 at 08:14
  • 1
    Thanks ...that works for me. I will make changes accordingly. Appreciated. – Shriniwas May 07 '18 at 09:05
  • @JeruLuke i have an error when i tried this code : SystemError: returned NULL without setting an error – weights Feb 11 '20 at 13:03
  • @sayedashraf Check whether the coordinates (x and y) are within the image – Jeru Luke Feb 11 '20 at 13:11