使用OpenCV的函数polylines()绘制多条相连的线段和多边形;使用函数fillPoly()绘制带填充效果的多边形

函数polylines()可用来根据点集绘制多条相连的线段,也可用来绘制多边形。

函数polylines()有两种原型,这里只向大家介绍比较常用的那种原型。

函数polylines()的C++原型如下:

void cv::polylines(InputOutputArray img,
                   const Point *const * pts,
                   const int * npts,
                   int ncontours,
                   bool isClosed,
                   const Scalar & color,
                   int thickness = 1,
                   int lineType = LINE_8,
                   int shift = 0 )

函数polylines()的Python原型如下:

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

函数polylines()的参数意义如下:
img—绘制的多条相连线段或多边形所在的图像。
pts—存放点集坐标的二维数组,它是一个指针的指针,要注意的是在Python-OpenCV中,其中每一个坐标的数据类型为int32,而不能为常用的uint8。
npts—代表有几组点集。
ncontours—代表有内个轮廓。
isClosed—是否把绘制的多条线段首尾相连,显示,如果要绘制多边形,则这个参数值该置为true。
color—线条的颜色,用三通道表示。
thickness—线条的粗细,这里不能取负值。
lineType—线条的类型,默认值为LINE_8。
shift—坐标值的小数位数。

函数fillPoly()用于在图像上绘制带填充效果的多边形。

函数fillPoly(也)有两种原型,这里也只向大家介绍比较常用的那种原型。

C++原型如下:

void cv::fillPoly(InputOutputArray img,
                  const Point ** pts,
                  const int * npts,
                  int ncontours,
                  const Scalar & color,
                  int lineType = LINE_8,
                  int shift = 0,
                  Point offset = Point() )

Python原型如下:

img=cv.fillPoly(img, pts, color[, lineType[, shift[, offset]]])

参数意义如下:
img—绘制的多边形所在的图像。
pts—存放多边形顶点坐标的二维数组,它是一个指针的指针,要注意的是在Python-OpenCV中,其中每一个坐标的数据类型为int32,而不能为常用的uint8。
npts—代表有几组点集。
ncontours—代表有内个轮廓。
color—线条的颜色,用三通道表示。
lineType—线条的类型,默认值为LINE_8。
shift—坐标值的小数位数。
offset—所有多边形顶点坐标的偏移量。

这两个函数的Python示例代码如下:

# -*- coding: utf-8 -*-
# 出处:昊虹AI笔记网(hhai.cc)
# 用心记录计算机视觉和AI技术

# 博主微信/QQ 2487872782
# QQ群 271891601
# 欢迎技术交流与咨询

# OpenCV的版本为4.4.0

import numpy as np
import cv2 as cv

if __name__ == '__main__':
    img1 = np.zeros((200, 400, 3), dtype='uint8')
    img2 = np.zeros((200, 400, 3), dtype='uint8')
    img3 = np.zeros((200, 400, 3), dtype='uint8')

    pts = np.array([[150, 33], [263, 40], [330, 100], [321, 180], [118, 90]], dtype='int32')

    # 使用函数polylines()绘制多边形
    cv.polylines(img1, [pts], True, (255, 0, 0))

    # 使用函数polylines()绘制多条线段
    cv.polylines(img2, [pts], False, (255, 0, 0))

    # 使用函数fillPoly()绘制带填充效果的多边形
    cv.fillPoly(img3, [pts], (255, 0, 0))

    cv.imshow('img1', img1)
    cv.imshow('img2', img2)
    cv.imshow('img3', img3)
    cv.waitKey(0)
    cv.destroyAllWindows()

运行结果如下:
在这里插入图片描述
这两个函数在C++环境下的示例代码要复杂些,因为牵涉到指针的指针。
如果需要C++示例代码,
请访问本博文的原文获取,
本博文原文链接如下:

https://www.hhai.cc/thread-176-1-1.html

这两个函数的C++代码运行结果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wenhao_ir/article/details/128401094