如何使用 Python 在 OpenCV 中在图像上绘制折线?
要在图像上绘制折线,我们使用方法 cv2.polylines()。我们可以在图像上绘制开放或闭合的折线。绘制开放折线时,第一个点和最后一个点不相连。
语法
cv2.polylines() 的语法如下 −
cv2.polylines(src, [pts], isClosed, color, thick)
参数
src − 这是要在其上绘制折线的输入图像。
pts − 点数组列表。
isClosed − 设置 isClosed=True 以绘制封闭折线,对于开放折线,设置 isClosed=False。
color − 这是颜色线。
厚度− 线的粗细。默认厚度设置为厚度=1。
步骤
您可以使用以下步骤在图像上绘制折线−
导入所需的库。在以下所有 Python 示例中,所需的 Python 库为 OpenCV 和 NumPy。确保您已经安装了它们。
import cv2 import numpy as np
使用 cv2.imread() 方法读取输入图像。
img = cv2.imread('nature_waterfall.jpg')
定义一个 2D 点数组并重新整形。
points = np.array([[155,320],[250,420],[345,50]]) pts = points.reshape(-1,1,2) # 现在形状为 [3,1,2]
在图像上绘制折线,传递参数的所需值 - isClosed、color、 thick。要绘制闭合折线,请传递isClosed=True;要绘制开放折线,请设置isClosed=False。
cv2.polylines(img, [pts1], isClosed=True, color=(255,0,0), thicken = 2)
显示绘制折线的图像。
cv2.imshow("Polylines", img_poly) cv2.waitKey(0) cv2.destroyAllWindows()
我们将在以下示例中使用此图像作为输入文件。
示例 1
在下面的 Python 程序中,我们在输入图像上绘制了一条蓝色闭合折线。
# import required libraries import cv2 import numpy as np # load the input image img = cv2.imread('nature_waterfall.jpg') # define an array of three points on image to draw the polylines # shape of point array [3,2] points = np.array([[155,320],[250,420],[345,50]]) # reshape the point array to make it 3D pts = points.reshape(-1,1,2) # now shape [3,1,2] # draw polylines on the image, passing desired values of the arguments img_poly = cv2.polylines(img, [pts], isClosed=True, color=(255,0,0), thickness = 2) # display the image with drawn polylines cv2.imshow("Polylines", img_poly) cv2.waitKey(0) cv2.destroyAllWindows()
输出
执行上述程序时,将生成以下输出窗口。
请注意,图像上绘制的折线是封闭的。我们可以绘制一条不封闭的折线。在这种情况下,第一个点和最后一个点没有连接。请查看第二个示例,了解图像上绘制的两种类型的线。
示例 2
在下面的 Python 程序中,我们在输入图像上绘制三条折线。第一条和第三条折线是封闭的,而第二条折线不是封闭的。
import cv2 import numpy as np # read the input image img = cv2.imread('nature_waterfall.jpg') # define the array of points points1 = np.array([[455,200],[155,420],[145,350]]) points2 = np.array([[200,120],[200,320],[405,350], [600,30]]) points3 = np.array([[100,20],[320,20],[45,350], [100,150]]) # reshape the points pts1 = points1.reshape(-1,1,2) pts2 = points2.reshape(-1,1,2) pts3 = points3.reshape(-1,1,2) # draw the polylines cv2.polylines(img, [pts1], isClosed=True, color=(255,0,0), thickness = 2) cv2.polylines(img, [pts2], isClosed=False, color=(0,255,0), thickness = 2) cv2.polylines(img, [pts3], isClosed=True, color=(0,0,255), thickness = 2) # display the image with drawn polylines cv2.imshow("Polylines", img) cv2.waitKey(0) cv2.destroyAllWindows()
输出
执行上述程序时,将生成以下输出窗口。
请注意,绿色折线是开放的,而红色和蓝色折线是封闭的。