以矩形框起辨識的物體,並依序標上記號。
★範例所使用的圖檔下載位置
★程式範例執行
from imutils import contours
import numpy as np
import argparse
import imutils
import cv2
def order_points_old(pts):
#設定物體輪廓之四個點位置,左上右上右下左下(順時針)
rect = np.zeros((4, 2), dtype="float32")
s = pts.sum(axis=1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
return rect
ap = argparse.ArgumentParser()
args = vars(ap.parse_args())
image = cv2.imread("03.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)
edged = cv2.Canny(gray, 50, 100)
edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
#以順時針順序排列(刪除即相反)
(cnts, _) = contours.sort_contours(cnts)
for (i, c) in enumerate(cnts):
if cv2.contourArea(c) < 100:
continue
box = cv2.minAreaRect(c)
box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)
box = np.array(box, dtype="int")
cv2.drawContours(image, [box], -1, (0, 255, 200), 2)
rect = order_points_old(box)
cv2.putText(image, "Object #{}".format(i + 1),
(int(rect[0][0] - 15), int(rect[0][1] - 15)),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,255, 200), 1)
cv2.imshow("Image", image)
cv2.waitKey(0)
★範例執行結果
★細部程式介紹
【numpy.sum】
◎使用格式:
◎範例程式:
【numpy.diff】
◎使用格式:
◎範例程式:
Comments
comments powered by Disqus