📜  使用 OpenCV 在图像上绘制几何形状

📅  最后修改于: 2021-10-23 08:45:38             🧑  作者: Mango

OpenCV 提供了许多绘图函数来绘制几何形状和在图像上写入文本。让我们看看一些绘图函数并使用 OpenCV 在图像上绘制几何形状。

一些绘图功能是:

为了演示上述函数的使用,我们需要一个大小为 400 X 400 的图像,填充纯色(在本例中为黑色)。为了做到这一点,我们可以利用numpy.zeroes函数来创建所需的图像。

# Python3 program to draw solid-colored
# image using numpy.zeroes() function
import numpy as np
import cv2
  
# Creating a black image with 3 channels
# RGB and unsigned int datatype
img = np.zeros((400, 400, 3), dtype = "uint8")
cv2.imshow('dark', img)
  
# Allows us to see image
# untill closed forcefully
cv2.waitKey(0)
cv2.destroyAllWindows()

输出 :
现在,让我们在这张纯黑色图像上绘制一些几何形状。

画一条线 :

# Python3 program to draw line
# shape on solid image
import numpy as np
import cv2
  
# Creating a black image with 3 channels
# RGB and unsigned int datatype
img = np.zeros((400, 400, 3), dtype = "uint8")
  
# Creating line
cv2.line(img, (20, 160), (100, 160), (0, 0, 255), 10)
  
cv2.imshow('dark', img)
  
# Allows us to see image
# untill closed forcefully
cv2.waitKey(0)
cv2.destroyAllWindows()

输出 :

画一个矩形:

# Python3 program to draw rectangle
# shape on solid image
import numpy as np
import cv2
  
# Creating a black image with 3
# channels RGB and unsigned int datatype
img = np.zeros((400, 400, 3), dtype = "uint8")
  
# Creating rectangle
cv2.rectangle(img, (30, 30), (300, 200), (0, 255, 0), 5)
  
cv2.imshow('dark', img)
  
# Allows us to see image
# untill closed forcefully
cv2.waitKey(0)
cv2.destroyAllWindows()

输出 :

画一个圆圈:

# Python3 program to draw circle
# shape on solid image
import numpy as np
import cv2
  
# Creating a black image with 3
# channels RGB and unsigned int datatype
img = np.zeros((400, 400, 3), dtype = "uint8")
  
# Creating circle
cv2.circle(img, (200, 200), 80, (255, 0, 0), 3)
  
cv2.imshow('dark', img)
  
# Allows us to see image
# untill closed forcefully
cv2.waitKey(0)
cv2.destroyAllWindows()

输出 :

书写文字:

# Python3 program to write 
# text on solid image
import numpy as np
import cv2
  
# Creating a black image with 3
# channels RGB and unsigned int datatype
img = np.zeros((400, 400, 3), dtype = "uint8")
  
# writing text
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'GeeksForGeeks', (50, 50),
            font, 0.8, (0, 255, 0), 2, cv2.LINE_AA)
  
cv2.imshow('dark', img)
  
# Allows us to see image
# untill closed forcefully
cv2.waitKey(0)
cv2.destroyAllWindows()

输出 :


在图像上绘制形状的应用:

  • 绘制几何形状可以帮助我们突出图像的特定部分。
  • 线条等几何形状可以帮助我们指出或识别图像中的特定区域。
  • 在图像的某些区域上书写文本可以为该区域添加描述。

参考 :
https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html