opencv advanced 02 - draw a variety of geometric figures on the image

OpenCV provides convenient drawing functions, which can be used to draw straight lines, rectangles, circles, ellipses and other geometric figures, and can also add text descriptions at specified positions in the image.

OpenCV provides the function cv2.line() for drawing straight lines, cv2.rectangle() for drawing rectangles, cv2.circle() for drawing circles, cv2.ellipse() for drawing ellipses, and cv2.polylines for drawing polygons (), the function cv2.putText() that adds text to the image and other drawing functions.

These drawing functions have some common parameters, which are mainly used to set the source image, color, line attributes, etc. A brief introduction to these common parameters is given below.

  • img : The carrier image on which graphics are drawn (container carrier for drawing, also known as canvas, artboard).
  • color : The color to draw the shape. Colors are usually represented using the BGR model, for example, (0, 255, 0) for green. For grayscale images, only grayscale values ​​can be passed in. Note that the order of the color channels is BGR, not RGB.
  • thickness : The thickness of the line. The default value is 1, if it is set to -1, it means filling the graphics (that is, the drawn graphics are solid).
  • lineType : the type of line, the default is 8 connection types. The value and description of the lineType parameter are shown in Table 19-1.

insert image description here

  • shift: data precision. This parameter is used to control the accuracy of the value (such as the coordinates of the center of the circle, etc.), and generally does not need to be set.

draw straight line

OpenCV provides the function cv2.line() to draw straight lines (line segments). The syntax of this function is:

img = cv2.line( img, pt1, pt2, color[, thickness[, lineType ]])

In the formula:

  • The meanings of the parameters img, color, thickness, and lineType are as shown in the previous description.
  • pt1 represents the first point (start point) of the line segment.
  • pt2 represents the second point (end point) of the line segment.

Example: Use the cv2.line() function to draw three line segments within an image with a black background.

import numpy as np
import cv2
n = 300  # 图像尺寸

# 创建一个空白的彩色图像,尺寸为(n+1) x (n+1)3通道(RGB)
img = np.zeros((n+1, n+1, 3), np.uint8)

# 在图像上绘制蓝色直线,起点为(0,0),终点为(n,n),线宽为3
img = cv2.line(img, (0, 0), (n, n), (255, 0, 0), 3)

# 在图像上绘制绿色直线,起点为(0,100),终点为(n,100),线宽为1
img = cv2.line(img, (0, 100), (n, 100), (0, 255, 0), 1)

# 在图像上绘制红色直线,起点为(100,0),终点为(100,n),线宽为6
img = cv2.line(img, (100, 0), (100, n), (0, 0, 255), 6)

winname = 'line-demo'  # 窗口名称

# 创建一个窗口并设置窗口名字
cv2.namedWindow(winname)

# 在窗口中显示图像
cv2.imshow(winname, img)

# 等待键盘按键,0表示无限等待
cv2.waitKey(0)
cv2.destroyAllWindows()

operation result:

insert image description here

draw rectangle

OpenCV provides 函数 cv2.rectangle()methods for drawing rectangles. The syntax of this function is:

img = cv2.rectangle( img, pt1, pt2, color[, thickness[, lineType]] )

In the formula:

  • The meanings of the parameters img, color, thickness, and lineType are as shown in the previous description.
  • pt1 is the rectangle vertex.
  • pt2 is the vertex opposite to pt1 in the rectangle.

Use the function cv2.rectangle() to draw a solid rectangle and a hollow rectangle inside a white background image.

code show as below:

import numpy as np
import cv2

n = 300  # 图像尺寸

# 创建一个白色背景的彩色图像,尺寸为n x n,3通道(RGB)
img = np.ones((n, n, 3), np.uint8) * 255

# 在图像上绘制填充的红色矩形,左上角坐标为(50, 50),右下角坐标为(n-100, n-50),颜色为红色,厚度为-1表示填充, 0表示不填充
img = cv2.rectangle(img, (50, 50), (n-100, n-50), (0, 0, 255), -1)

winname = 'rect-shixin'  # 窗口名称

# 创建一个窗口并设置窗口名字
cv2.namedWindow(winname)

# 在窗口中显示图像
cv2.imshow(winname, img)

# 等待键盘按键,0表示无限等待
cv2.waitKey(0)

# 关闭所有打开的窗口
cv2.destroyAllWindows()

insert image description here
Willimg = cv2.rectangle(img, (50, 50), (n-100, n-50), (0, 0, 255), -1)

If -1 is changed to 0, a non-solid rectangular frame can be drawn, and the effect is as follows.

insert image description here

draw circle

OpenCV provides a 函数 cv2.circle()tool for drawing circles. The syntax of this function is:

img = cv2.circle( img, center, radius, color[, thickness[, lineType]] )

In the formula:

  • The meanings of the parameters img, color, thickness, and lineType are as shown in the previous description.

  • center is the center of the circle.

  • radius is the radius

Use the function cv2.circle() to draw a set of concentric circles within a white background image.

code show as below:

import numpy as np
import cv2
d = 400
img = np.ones((d,d,3),dtype="uint8")*255
(centerX,centerY) = (round(img.shape[1] / 2),round(img.shape[0] / 2))
# 将图像的中心作为圆心,实际值为 d/2
red = (0,0,255) # 设置白色变量
for r in range(5,round(d/2),12):
 cv2.circle(img,(centerX,centerY),r,red,3)
 # circle(载体图像,圆心,半径,颜色)
cv2.imshow("Demo19.3",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

running result:

insert image description here

draw an ellipse

OpenCV provides the function cv2.ellipse() to draw ellipses. The syntax format of this function is:
img=cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color[,
thickness[, lineType]])
where:

  • The meanings of the parameters img, color, thickness, and lineType are as shown in the previous description.
  • center is the coordinates of the center of the ellipse.
  • axes is the length of the axes.
  • angle is the angle of deflection.
  • startAngle is the angle of the starting angle of the arc.
  • endAngle is the angle of the end angle of the arc.

Use the function cv2.ellipse() to randomly draw a set of hollow ellipses within a white background image.

import numpy as np
import cv2
d = 400
img = np.ones((d,d,3),dtype="uint8")*255
# 生成白色背景
center=(round(d/2),round(d/2))
# 注意数值类型,不可以使用语句 center=(d/2,d/2)
size=(100,200)
# 轴的长度
for i in range(0,10):
 angle = np.random.randint(0,361)
 # 偏移角度
 color = np.random.randint(0,high = 256,size = (3,)).tolist()
 # 生成随机颜色,3[0,256)的随机数
 thickness = np.random.randint(1,9)
 cv2.ellipse(img, center, size, angle, 0, 360, color,thickness)
cv2.imshow("demo-tuoyuan",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

running result:
insert image description here

draw polygon

OpenCV provides the function cv2.polylines() to draw polygons. The syntax of this function is:

img = cv2.polylines( img, pts, isClosed, color[, thickness[,
lineType[, shift]]])

In the formula:

  • The meanings of the parameters img, color, thickness, lineType and shift are as shown in the previous description.
  • pts are the vertices of the polygon.
  • isClosed is a closed flag, used to indicate whether the polygon is closed. If the value is True, connect the last point to the first point to make the polygon closed; otherwise, just connect the points in turn to form a curve.

When using the function cv2.polylines() to draw a polygon, you need to give the coordinates of each vertex. The coordinates of these points construct an array whose size is equal to "the number of vertices 1 2", and the data type of this array must be numpy.int32.

Use the function cv2.polylines() to draw a polygon inside a white background image.

import numpy as np
import cv2
d = 400  # 图像尺寸

# 创建一个白色背景的彩色图像,尺寸为d x d,3通道(RGB)
img = np.ones((d, d, 3), dtype="uint8") * 255

# 生成多边形的各个顶点坐标
pts = np.array([[200, 50], [300, 200], [200, 350], [100, 200]], np.int32)

# 重新整形顶点数组,将其变为顶点数 x 1 x 2 的形状
pts = pts.reshape((-1, 1, 2))

# 使用 cv2.polylines() 函数绘制多边形
# 第一个参数为图像,第二个参数为顶点数组,第三个参数为True表示封闭多边形,颜色为绿色,线宽为8
cv2.polylines(img, [pts], True, (0, 255, 0), 8)
cv2.imshow("duobianxing",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

insert image description here

The third parameter isClosed in the function cv2.polylines() is a closed flag. When this value is set to False, each
vertex is only connected with a line segment, and the polygon is not closed. The code at this point is:

cv2.polylines(img,[pts],False,(0,255,0),8)

The effect is as follows:

insert image description here

draw text on graphics

OpenCV provides the function cv2.putText() to draw text on graphics. The syntax of this function is:

img=cv2.putText(img, text, org, fontFace, fontScale, color[,
thickness[, lineType[, bottomLeftOrigin]]])

In the formula:

  • The meanings of the parameters img, color, thickness, lineType and shift are as shown in the previous description.
  • text is the font to draw.
  • org is the location to draw the font, starting from the lower left corner of the text.
  • fontFace indicates the font type, and its parameter types and meanings are shown in Table 19-2.
  • fontScale represents the font size.
  • bottomLeftOrigin is used to control the orientation of the text. The default value is False, when set to True, the text is mirrored vertically.

insert image description here

Use the function cv2.putText() to draw text inside a white background image.

code show as below:

import numpy as np
import cv2

d = 400  # 图像尺寸

# 创建一个白色背景的彩色图像,尺寸为d x d,3通道(RGB)
img = np.ones((d, d, 3), dtype="uint8") * 255

# 定义字体
font = cv2.FONT_HERSHEY_SIMPLEX


# 在图像上绘制红色的 "OpenCV" 文本,位置同样为(0, 200),字体大小为3,线宽为5
cv2.putText(img, 'OpenCV', (0, 200), font, 3, (0, 0, 255), 5)

# 创建一个窗口并显示图像
cv2.imshow("weizi", img)

cv2.waitKey(0)
cv2.destroyAllWindows()


This program uses the function cv2.putText() to draw the text "OpenCV" in the image img .

insert image description here

Guess you like

Origin blog.csdn.net/hai411741962/article/details/132293031