# coding: utf-8
# !/usr/bin/python
"""
@File : OpenCV中的轮廓.py
@Author : jiaming
@Modify Time: 2020/2/4 12:02
@Contact :
@Version : 1.0
@Desciption : OpenCV 中的轮廓
理解什么是轮廓,学习找轮廓,绘制轮廓
cv2.findContours(), cv2.drawContours()
图像、轮廓、轮廓的层析结构=cv2.findContours(输入图像、轮廓检索模式、轮廓近似方法)
cv2.drawContours(原始图像、轮廓(列表)、索引(-1: 绘制所有轮廓))
"""
import os
import sys
import numpy as np
import cv2
import pprint
from matplotlib import pyplot as plt
rawPath = os.path.abspath(__file__)
currentFile = os.path.basename(sys.argv[0])
dataPath = rawPath[:rawPath.find(currentFile)] + r'static\\'
"""
轮廓可以简单认为成将连续的点连在一起的曲线,具有相同的颜色或者灰度,轮廓在形状分析和物体的检测和识别
中很有用。
为了更加准确,要使用二值化图像。在寻找轮廓之前,要进行阈值化处理或者 Canny 边界检测。
查找轮廓的函数会修改原始图像。如果你在找到轮廓之后还想使用原始图像,你应该将原始图像存储到其他变量中。
在 opencv 中,查找轮廓就像在黑色背景中找白色物体。
"""
im = cv2.imread(dataPath + 'j.png')
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 200, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('img1', thresh)
contours, hierarchy = cv2.findContours(
thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 以上设置是较为通用的用法,后面会讲到一些具体的设置参数
# 这一步会把thresh变为轮廓图,即与img相同;然而不断试验并没发现thresh发生任何变化
# cv2.CHAIN_APPROX_SIMPLE 将轮廓上的冗余点去掉,压缩轮廓
# cv2.CHAIN_APPROX_NONE 所有边界点都会被存储
# BGR
cv2.drawContours(im, contours, -1, (0, 0, 255), 1)
# 这一步会把轮廓线画在im中
cv2.imshow('img', im)
cv2.waitKey(0)
print(len(contours)) # 4 个轮廓