Python-OpenCV中的圖像輪廓檢測



  主要記錄Python-OpenCV中的cv2.findContours()方法;官方文檔


cv2.findContours()

  在二值圖像中尋找圖像的輪廓;與cv2.drawubgContours()配合使用;

# 方法中使用的算法來源
Satoshi Suzuki and others. Topological structural analysis of digitized binary images by border following. Computer Vision, Graphics, and Image Processing, 30(1):32–46, 1985.
def findContours(image, mode, method, contours=None, hierarchy=None, offset=None):
"""
檢測二值圖像的輪廓信息
Argument:
	image: 待檢測圖像
	mode: 輪廓檢索模式
	method: 輪廓近似方法
	contours: 檢測到的輪廓;每個輪廓都存儲為點矢量
	hierarchy: 
	offset: 輪廓點移動的偏移量
"""

示例:檢測下圖中的輪廓

#!/usr/bin/env python
#-*- coding:utf-8 -*-
# @Time    : 19-4-20 下午6:29
# @Author  : chen

import cv2
import matplotlib.pyplot as plt

image = cv2.imread("input_01.png")
image_BGR = image.copy()

# 將圖像轉換成灰度圖像,並執行圖像高斯模糊,以及轉化成二值圖像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5,5), 0)
image_binary = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]

# 從二值圖像中提取輪廓
# contours中包含檢測到的所有輪廓,以及每個輪廓的坐標點
contours = cv2.findContours(image_binary.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]

# 遍歷檢測到的所有輪廓,並將檢測到的坐標點畫在圖像上
# c的類型numpy.ndarray,維度(num, 1, 2), num表示有多少個坐標點
for c in contours:
    cv2.drawContours(image, [c], -1, (255, 0, 0), 2)

image_contours = image

# display BGR image
plt.subplot(1, 3, 1)
plt.imshow(image_BGR)
plt.axis('off')
plt.title('image_BGR')

# display binary image
plt.subplot(1, 3, 2)
plt.imshow(image_binary, cmap='gray')
plt.axis('off')
plt.title('image_binary')

# display contours
plt.subplot(1, 3, 3)
plt.imshow(image_contours)
plt.axis('off')
plt.title('{} contours'.format(len(contours)))

plt.show()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM