1. 程式人生 > >OpenCV——邊界框、最小矩形區域和最小閉圓的輪廓

OpenCV——邊界框、最小矩形區域和最小閉圓的輪廓

對下面這張影象,檢測其邊界框、最小矩形區域以及最小閉圓的輪廓。

  • hammer.jpg

在這裡插入圖片描述

  • 使用cv2.pyrDown()函式縮小圖片。

  • 使用cv2.threshold()函式進行二值化處理。

  • 使用cv2.findContours()函式檢測輪廓。

  • 使用cv2.boundingRect()函式獲得邊界框。

  • 使用cv2.rectangle()函式繪製邊界框。

  • 使用cv2.minAreaRect()函式獲得最小矩形區域。

  • 使用cv2.drawContours()函式繪製最小矩形區域。

  • 使用cv2.minEnclosingCircle()函式獲得最小閉圓。

  • 使用cv2.circle()函式繪製最小閉圓。

  • 原始碼

import cv2
import numpy as np

img = cv2.pyrDown(cv2.imread("hammer.jpg", cv2.IMREAD_UNCHANGED))

ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY), 127, 255, cv2.THRESH_BINARY)
image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
    # find bounding box coordinates
    x, y, w, h = cv2.boundingRect(c)
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

    # find minimum area
    rect = cv2.minAreaRect(c)
    # calculate coordinates of the minimum area rectangle
    box = cv2.boxPoints(rect)
    # normalize coordinates to integers
    box = np.int0(box)
    # draw contours
    cv2.drawContours(img, [box], 0, (0, 0, 255), 3)

    # calculate center and radius of minimum enclosing circle
    (x, y), radius = cv2.minEnclosingCircle(c)
    # cast to integers
    center = (int(x), int(y))
    radius = int(radius)
    # draw the circle
    img = cv2.circle(img, center, radius, (0, 255, 0), 2)

cv2.drawContours(img, contours, -1, (255, 0, 0), 2)
cv2.imshow("contours", img)

cv2.waitKey()
cv2.destroyAllWindows()

  • contours

在這裡插入圖片描述