Contours.md 2.8 KB
Newer Older
youcans_'s avatar
youcans_ 已提交
1 2 3 4 5 6 7 8 9 10 11
# 寻找图像的轮廓

轮廓是由连续的点组成的曲线。轮廓与边缘很相似,但轮廓是连续的,边缘不一定都连续。

轮廓反映了物体的基本外形,常用于形状分析和物体的检测和识别。

OpenCV 提供函数 **cv.findContours()** 对二值图像寻找轮廓,函数 **cv2.drawContours()** 绘制轮廓。

**函数说明:**

```
youcans_'s avatar
youcans_ 已提交
12
cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]]	) → contours, hierarchy
youcans_'s avatar
youcans_ 已提交
13 14 15 16 17 18 19
```

我们从康熙御笔书法中提取轮廓,据说这是一种经典的书画复制技法。下图从上到下分别是:
* 康熙御笔原图
* 康熙御笔碑帖图
* 康熙御笔轮廓图

F
feilong 已提交
20 21
![](https://gitcode.net/csdn/skill_tree_git_md_linux/-/raw/master/data/1.OpenCV初阶/2.二值图像处理/5.轮廓/ContuorsOutput.jpg)
<br/>
youcans_'s avatar
youcans_ 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

下面对康熙御笔寻找轮廓实现代码正确的是?

##  答案

```
import cv2 as cv

if __name__ == '__main__':
    img = cv.imread("Contours.jpg", flags=1)
    imgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

    ret, thresh = cv.threshold(imgGray, 127, 255, cv.THRESH_BINARY_INV)
    image, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
    contourPic = cv.drawContours(img, contours, -1, (0, 0, 255), 2)

    cv.imshow("ContourPicture", contourPic)
    cv.waitKey(0)
```

##  选项

###  使用了灰度图而不是二值图来查找轮廓

```
import cv2 as cv

if __name__ == '__main__':
    img = cv.imread("Contours.jpg", flags=1)
    imgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

    ret, thresh = cv.threshold(imgGray, 127, 255, cv.THRESH_BINARY_INV)
    image, contours, hierarchy = cv.findContours(imgGray, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
    contourPic = cv.drawContours(img, contours, -1, (0, 0, 255), 2)

    cv.imshow("ContourPicture", contourPic)
    cv.waitKey(0)
```

###  阈值处理时的阈值设置过大

```
import cv2 as cv

if __name__ == '__main__':
    img = cv.imread("Contours.jpg", flags=1)
    imgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

    ret, thresh = cv.threshold(imgGray, 205, 255, cv.THRESH_BINARY_INV)
    image, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
    contourPic = cv.drawContours(img, contours, -1, (0, 0, 255), 2)

    cv.imshow("ContourPicture", contourPic)
    cv.waitKey(0)
```

###  函数 findContours 缺少输出参数 image

```
import cv2 as cv

if __name__ == '__main__':
    img = cv.imread("Contours.jpg", flags=1)
    imgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

    ret, thresh = cv.threshold(imgGray, 127, 255, cv.THRESH_BINARY_INV)
    contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
    contourPic = cv.drawContours(img, contours, -1, (0, 0, 255), 2)

    cv.imshow("ContourPicture", contourPic)
    cv.waitKey(0)
```