Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write text on image using opencv python in run-time application [duplicate]

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.

like image 862
trojanatwar Avatar asked May 05 '18 12:05

trojanatwar


People also ask

How do I show text in OpenCV?

Algorithm. Step 1: Import cv2 Step 2: Define the parameters for the puttext( ) function. Step 3: Pass the parameters in to the puttext() function. Step 4: Display the image.

How do I duplicate an image in OpenCV?

One way it can be done is through the copy() function of the numpy module. Wtih the copy() function and passing into it the image you want to copy, a copy will be made. This is shown in the code below. We use the OpenCV module to read in an image.


1 Answers

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
like image 176
Jeru Luke Avatar answered Oct 21 '22 08:10

Jeru Luke