OpenCV图像轮廓(1)查找和绘制轮廓

本文参照OpenCV官网文档来写,中英文对照,略作修改。

For better accuracy, use binary images. So before finding contours, apply threshold or canny edge detection.

为了查找轮廓更加精确,请使用二值图像。所以在查找轮廓之前,先用threshold一类的阈值函数或者canny一类的边缘检测函数得到二值图像。

In OpenCV, finding contours is like finding white object from black background. So remember, object to be found should be white and background should be black.

在OpenCV中查找轮廓就像黑色背景中查找白色物体。所以,你所要处理的图片中,背景应该是黑色的,前景物体应该是白色的。

如果不是这样,就需要先处理成这样,例如取阈值时使用INVERSE参数。

Use cv2.findContours to find coutours. There are three arguments in cv2.findContours() function, first one is source image, second is contour retrieval mode, third is contour approximation method.

使用cv2.findContours来查找轮廓,这个函数有3个参数。第1个是原始图像,第2个是轮廓提取模式,第3个是轮廓近似方法。

And it outputs the contours and hierarchy. contours is a Python list of all the contours in the image. Each individual contour is a Numpy array of (x,y) coordinates of boundary points of the object.

这个函数输出轮廓contours和层次hierarchy。轮廓是一个由图像中的所有轮廓组成的Python列表。每一个轮廓是一个Numpy数组,数组中的元素是轮廓的(x,y)坐标。

To draw the contours, cv.drawContours function is used. Its first argument is source image, second argument is the contours which should be passed as a Python list, third argument is index of contours (useful when drawing individual contour. To draw all contours, pass -1) and remaining arguments are color, thickness etc.

使用cv2.drawContours来绘制轮廓。该函数第1个参数是原始图像;第2个参数是轮廓(以Python列表方式传入);第3个参数是要绘制的轮廓在列表中的索引,如果要绘制某个特定轮廓,这个参数很有用,如果要绘制全部轮廓,这个参数就设为-1;后面其他的参数就是类似颜色、细条粗细等。

下面通过一个实际例子来看一下。

def contour00():
    img = cv2.imread('../images/lena.jpg', cv2.IMREAD_GRAYSCALE)
    ret, thresh = cv2.threshold(img, 160, 255, cv2.THRESH_BINARY)
    contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    img1 = img.copy()
    cv2.drawContours(img1, contours, -1, (0,255,0), 3)
    plot_images(1,2,[img,img1], gray=True)

运行效果如下
OpenCV图像轮廓(1)查找和绘制轮廓_第1张图片

你可能感兴趣的:(计算机视觉,OpenCV,python,图像识别,计算机视觉,opencv)