找出圖像輪廓
contours, hierarchy = cv.findContours(thresh, 3, 2)
畫出圖像輪廓
cnt = contours[1]
cv.drawContours(img_color1, [cnt], 0, (0, 0, 255), 2)
計算輪廓面積
area = cv.contourArea(cnt) #cnt:輪廓
print(area)
計算輪廓周長
perimeter = cv.arcLength(cnt, True) #參數2:表示輪廓是否封閉
print(perimeter)
圖像矩
M = cv.moments(cnt)
print(M)
print(M['m00']) # 輪廓面積
cx, cy = M['m10'] / M['m00'], M['m01'] / M['m00'] # 輪廓質心
print(cx, cy)
圖像外接矩形
x, y, w, h = cv.boundingRect(cnt) # 外接矩形
cv.rectangle(img_color1, (x, y), (x + w, y + h), (0, 255, 0), 2)
最小外接矩形
rect = cv.minAreaRect(cnt) # 最小外接矩形
box = np.int0(cv.boxPoints(rect)) # 矩形的四個角點並取整
cv.drawContours(img_color1, [box], 0, (255, 0, 0), 2)
最小外接圓
(x, y), radius = cv.minEnclosingCircle(cnt)
(x, y, radius) = map(int, (x, y, radius)) # 這也是取整的一種方式噢
cv.circle(img_color2, (x, y), radius, (0, 0, 255), 2)
擬合橢圓
ellipse = cv.fitEllipse(cnt)
cv.ellipse(img_color2, ellipse, (0, 255, 0), 2)
實驗:計算下圖中數字1的面積、輪廓周長,繪制數字1的外接矩形、最小外接矩形、最小外接圓、擬合橢圓
import cv2 as cv
import numpy as np
# 載入手寫數字圖片
img = cv.imread('handwriting.jpg', 0)
# 將圖像二值化
_, thresh = cv.threshold(img, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)
contours, hierarchy = cv.findContours(thresh, 3, 2)
# 創建出兩幅彩色圖用於繪制
img_color1 = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
img_color2 = np.copy(img_color1)
# 創建一幅彩色圖像用作結果對比
img_color = np.copy(img_color1)
# 計算數字1的輪廓特征
cnt = contours[1]
cv.drawContours(img_color1, [cnt], 0, (0, 0, 255), 2)
# 1.輪廓面積
area = cv.contourArea(cnt) # 6289.5
print(area)
# 2.輪廓周長
perimeter = cv.arcLength(cnt, True) # 527.4041
print(perimeter)
# 3.圖像矩
M = cv.moments(cnt)
print(M)
print(M['m00']) # 輪廓面積
cx, cy = M['m10'] / M['m00'], M['m01'] / M['m00'] # 輪廓質心
print(cx, cy)
# 4.圖像外接矩形和最小外接矩形
x, y, w, h = cv.boundingRect(cnt) # 外接矩形
cv.rectangle(img_color1, (x, y), (x + w, y + h), (0, 255, 0), 2)
rect = cv.minAreaRect(cnt) # 最小外接矩形
box = np.int0(cv.boxPoints(rect)) # 矩形的四個角點並取整
cv.drawContours(img_color1, [box], 0, (255, 0, 0), 2)
# 5.最小外接圓
(x, y), radius = cv.minEnclosingCircle(cnt)
(x, y, radius) = map(int, (x, y, radius)) # 這也是取整的一種方式噢
cv.circle(img_color2, (x, y), radius, (0, 0, 255), 2)
# 6.擬合橢圓
ellipse = cv.fitEllipse(cnt)
cv.ellipse(img_color2, ellipse, (0, 255, 0), 2)
result = np.hstack((img_color,img_color1,img_color2))
cv.imshow('result',result)
cv.waitKey(0)
cv.destroyAllWindows()
實驗結果