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

📅  最后修改于: 2021-04-27 19:24:22             🧑  作者: 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