Draw text cv2 python

Python OpenCV: How to draw text on an image

In this tutorial we will learn how to draw text on an image, using Python and OpenCV.

The code we will analyze was tested on Windows 8.1, with version 4.1.2 of OpenCV. The Python version used was 3.7.2.

How to draw text on the image

We will start by importing the cv2 module, which will expose to us the function we need to draw text on an image.

After that, we will load an image from the file system with a call to the imread function. As input, we pass the path to the image we want to use. When testing the code, don’t forget to adapt the code to point to an image in your machine.

img = cv2.imread('C:/Users/N/Desktop/monument.png')

Now, to draw text on the image, we will make use of the putText function. It receives the following parameters:

  • Image that will be used to write the text. We will pass the image we have just read;
  • Text to be drawn in the image, as a string. We will pass a testing string;
  • A tuple containing the pixel coordinates (x and y) of the bottom left corner where to draw the text. We will draw it at the top left corner of the image by using the coordinates x = 0 and y = 30.
  • The font, from the cv2 module. The list of possible values can be found here. In this example, we will be using FONT_HERSHEY_SIMPLEX;
  • The scale of the text. We will pass the value 1.0 to keep the font base size;
  • A tuple containing the BGR values for the color of the text. We will set our text to black, which means setting B=0, G=0 and R=0;
  • The thickness of the lines of the text. We will set it to 4. This is an optional parameter that, when not specified, defaults to 1.

Note that the putText function changes the image we pass as input. So, if we need to preserve the original image for some reason, we can simply copy it and write the text on the copy. This post explains how to copy an image.

cv2.putText(img, "My text", (0, 30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 4)

Now that we have drawn the text on the image, we will display it in a window. This is done simply by calling the imshow function, passing as first input the name of the window and as second our image.

Читайте также:  Трости на альт саксофон vandoren java

To finalize, we will wait for the user input to destroy the window and end our program.

cv2.waitKey(0) cv2.destroyAllWindows()

The complete code can be seen below.

import cv2 img = cv2.imread('C:/Users/N/Desktop/monument.png') cv2.putText(img, "My text", (0, 30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 4) cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows()

To test the previous script, you simply need to run it in a tool of your choice. I’ll be using PyCharm, a Python IDE.

Upon running the code, you should obtain a result similar to the one shown in figure 1. As we can check, we obtain an image with the text written in the top left corner, as expected.

Output of the OpenCV program, showing the image with the text drawn.

A more complex example

Since we already covered the basics, we will now analyze a more complex example where we will add a slider to the image to control the thickness of the text. The procedure to add a slider to a window was already covered here.

Like before, we will start by importing the cv2 module. Then, we will read an image from the file system and display it in a window. We will keep the window name in a variable since we will need it to create the slider.

Note that we are not going to write any text right away. This means that, when we run the program, it won’t show any text until we move the slider for the first time.

import cv2 img = cv2.imread('C:/Users/N/Desktop/monument.png') windowName = 'image' cv2.imshow(windowName, img)

Then we will add the slider to our image by calling the createTrackbar function. As input we pass the following values:

  • The name of the slider. We will call it “Thickness”;
  • The name of the window where to add the slider. We will pass the variable that holds the name of the window we created before;
  • The initial value to set the slider. We will set it to the beginning of the scale, which corresponds to zero;
  • The maximum value of the slider scale. We will use a value of 10;
  • The callback function that will be executed when the slider value changes. We will call this function on_change_thickness and analyze its implementation below.
cv2.createTrackbar('Thickness', windowName, 0, 10, on_change_thickness)

After this, we will wait for the user input. When it happens, we will destroy the window and finish the execution of our code.

cv2.waitKey(0) cv2.destroyAllWindows()

To finish, we will analyze the implementation of the on_change_thickness callback function. Note that it will receive as input the current value of the slider.

def on_change_thickness(val): # implementation

Like already commented on the previous section, the putText function alters the image. So, if we write with different thicknesses in the same place, we will get overlapped text. To avoid this, we will make a copy of the original image and write the text with the new thickness on this copy.

imageCopy = img.copy() cv2.putText(imageCopy, "My text", (0, 100), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0), val)

Then, we will display the image in the same window we have already created.

cv2.imshow(windowName, imageCopy)

The whole callback function can be seen below.

def on_change_thickness(val): imageCopy = img.copy() cv2.putText(imageCopy, "My text", (0, 100), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0), val) cv2.imshow(windowName, imageCopy)

The final Python script can be seen in the snippet below.

import cv2 def on_change_thickness(val): imageCopy = img.copy() cv2.putText(imageCopy, "My text", (0, 100), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0), val) cv2.imshow(windowName, imageCopy) img = cv2.imread('C:/Users/N/Desktop/monument.png') windowName = 'image' cv2.imshow(windowName, img) cv2.createTrackbar('Thickness', windowName, 0, 10, on_change_thickness) cv2.waitKey(0) cv2.destroyAllWindows()

Like before, simply run the code and check the result. You should get an output like the one shown in figure 2.

Читайте также:  Css все div одной высоты

Suggested OpenCV readings

Источник

Python OpenCV | cv2.putText() method

OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.putText() method is used to draw a text string on any image.

Syntax: cv2.putText(image, text, org, font, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]])

Parameters:
image: It is the image on which text is to be drawn.
text: Text string to be drawn.
org: It is the coordinates of the bottom-left corner of the text string in the image. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).
font: It denotes the font type. Some of font types are FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, , etc.
fontScale: Font scale factor that is multiplied by the font-specific base size.
color: It is the color of text string to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color.
thickness: It is the thickness of the line in px.
lineType: This is an optional parameter.It gives the type of the line to be used.
bottomLeftOrigin: This is an optional parameter. When it is true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner.

Return Value: It returns an image.

Image used for all the below examples:

Источник

OpenCV на python: наложение текста и графики

На предыдущем уроке мы научились получать поток кадров с веб-камеры и применять к ним различные преобразования. Сегодня рассмотрим еще несколько полезных функций, которые помогут нам выводить в кадр важную информацию.

1. Вывод текста поверх картинки в OpenCV

Для наложения текста на кадр воспользуемся функцией:

putText( кадр, текст, координаты, тип шрифта, масштаб шрифта, цвет [, толщина пера [, тип линии [, центр координат]]])
  • кадр — изображение, на которое мы накладываем текст;
  • текст — понятное дело, текст, который мы собираемся вывести в кадр;
  • координаты — кортеж из двух координат нижнего левого угла текста, например (5,10);
  • тип шрифта — одна из констант, указанных ниже;
  • масштаб шрифта — у шрифта есть некий стандартный размер, который довольно таки большой. Этот параметр позволяет уменьшать или увеличивать шрифт относительно стандартного. Например, для увеличения в два раза — пишем 2, для уменьшения в 2 раза — 0.5;
  • цвет — кортеж из трех чисел от 0 до 255, которые задают цвет в модели RGB. Нужно помнить, что в этом кортеже, цвета идут задом на перед: BGR. Синий цвет — (255,0,0);
  • толщина пера — необязательный параметр;
  • тип линии — необязательный параметр, одно из трех значений: LINE_8 пунктир мелкий, LINE_4 — пунктир крупный, LINE_AA — сглаженная линия;
  • центр координат — необязательный параметр. По-умолчанию координаты текста отсчитываются от верхнего левого угла. Если этот параметр равен True, то будут от нижнего левого угол.
  • FONT_HERSHEY_SIMPLEX
  • FONT_HERSHEY_PLAIN
  • FONT_HERSHEY_DUPLEX
  • FONT_HERSHEY_COMPLEX
  • FONT_HERSHEY_TRIPLEX
  • FONT_HERSHEY_COMPLEX_SMALL
  • FONT_HERSHEY_SCRIPT_SIMPLEX
  • FONT_HERSHEY_SCRIPT_COMPLEX
Читайте также:  If var is false javascript

Напишем программу, которая выведет в кадр текст «Hello world!» с координатами 20,20, желтым цветом.

import cv2 import video if __name__ == '__main__': cv2.namedWindow( "result" ) cap = video.create_capture(0) color_yellow = (0,255,255) while True: flag, img = cap.read() try: cv2.putText(img, "Hello world!", (20,20), cv2.FONT_HERSHEY_SIMPLEX, 1, color_yellow, 2) cv2.imshow('result', img) except: cap.release() raise ch = cv2.waitKey(5) if ch == 27: break cap.release() cv2.destroyAllWindows()

2. Вывод отрезка, окружности и прямоугольника в OpenCV

Перейдем к геометрическим фигурам. Для вывода отрезка используем функцию:

line( кадр, координаты начала, координаты конца, цвет [, толщина пера [, тип линии [, сдвиг]]])

помимо известных уже аргументов есть и один новый:

  • сдвиг — необязательный параметр. Отвечает за смещение координат по формуле x = x*2^-сдвиг. Применяется для создания сглаженных линий.

Следующая функции рисует окружность:

circle( кадр, координаты центра, радиус, цвет [, толщина пера [, тип линии [, сдвиг]]])

Тут всё просто, так что переходим к прямоугольнику:

rectangle( кадр, координаты 1, координаты 2, цвет [, толщина пера [, тип линии [, сдвиг]]])
  • координаты 1 — координаты верхнего левого угла;
  • координаты 2 — координаты нижнего правого угла.

Теперь вставим в нашу программу все три функции.

import cv2 import video if __name__ == '__main__': cv2.namedWindow( "result" ) cap = video.create_capture(0) color_red = (0,0,255) color_yellow = (0,255,255) color_purple = (255,0,255) while True: flag, img = cap.read() try: # рисуем окружность cv2.circle(img, (190, 70), 10, color_red, -1) # рисуем прямоугольник cv2.rectangle(img, (180,140), (370,180), color_red, thickness=2, lineType=8, shift=0) # рисуем пять отрезков for i in range(5): cv2.line(img, (180,85+i*5), (370,85+i*5), color_purple, thickness=2, lineType=8, shift=0) # выводим текст cv2.putText(img, "Hello world!", (185,170), cv2.FONT_HERSHEY_SIMPLEX, 1, color_yellow, 2) cv2.imshow('result', img) except: cap.release() raise ch = cv2.waitKey(5) if ch == 27: break cap.release() cv2.destroyAllWindows()

Запускаем программу. Должно получиться что-то подобное:

OpenCV на python. Наложение текста и графики

На следующем уроке будем изучать работу с цветовыми фильтрами — основу для многих функций детектирования.

OpenCV на python: наложение текста и графики : 4 комментария

Ошибка
Traceback (most recent call last):
File «C:\Users\emose\OneDrive\Рабочий стол\sdfasd — копия — копия.py», line 1, in
import cv2
ModuleNotFoundError: No module named ‘cv2’

Источник

Оцените статью