# coding=utf-8 from scipy.spatial import distance as dist from imutils import perspective from imutils import contours import numpy as np import argparse import imutils import cv2 import time # 定義一個中點函數,後面會用到 def midpoint(ptA, ptB): return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5) # 讀取輸入圖片 image = cv2.imread("test3.jpg") # 建立一個黑色背景的圖片 bg_img = np.zeros((image.shape[0], image.shape[1] // 2, 3), np.uint8) # 設定正方形的邊長 length = int(2 / 2.54 * image.shape[1] / 2) # 畫出正方形 cv2.rectangle(bg_img, (bg_img.shape[1] // 2 - length // 2, bg_img.shape[0] // 2 - length // 2), (bg_img.shape[1] // 2 + length // 2, bg_img.shape[0] // 2 + length // 2), (255, 255, 255), 2) # 將原始圖片與正方形圖案合併在一起 image = np.concatenate((bg_img, image), axis=1) cv2.imshow('Result', image) cv2.waitKey(0) # 輸入圖片灰度化 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 = imutils.grab_contours(cnts) # 對輪廓按照從左到右進行排序處理 (cnts, _) = contours.sort_contours(cnts) # 初始化 'pixels per metric' pixelsPerMetric = None # 循環遍歷每一個輪廓 for c in cnts: # 如果當前輪廓的面積太少,認為可能是噪聲,直接忽略掉 if cv2.contourArea(c) < 100: continue # 根據物體輪廓計算出外切矩形框 orig = image.copy() box = cv2.minAreaRect(c) box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box) box = np.array(box, dtype="int") # 按照top-left, top-right, bottom-right, bottom-left的順序對輪廓點進行排序,並繪製外切的BB,用綠色的線來表示 box = perspective.order_points(box) cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 2) # 繪製BB的4個頂點,用紅色的小圓圈來表示 for (x, y) in box: cv2.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1) # 分別計算top-left 和top-right的中心點和bottom-left 和bottom-right的中心點坐標 (tl, tr, br, bl) = box (tltrX, tltrY) = midpoint(tl, tr) (blbrX, blbrY) = midpoint(bl, br) # 分別計算top-left和top-right的中心點和top-righ和bottom-right的中心點坐標 (tlblX, tlblY) = midpoint(tl, bl) (trbrX, trbrY) = midpoint(tr, br) # 繪製BB的4條邊的中心點,用藍色的小圓圈來表示 cv2.circle(orig, (int(tltrX), int(tltrY)), 5, (255, 0, 0), -1) cv2.circle(orig, (int(blbrX), int(blbrY)), 5, (255, 0, 0), -1) cv2.circle(orig, (int(tlblX), int(tlblY)), 5, (255, 0, 0), -1) cv2.circle(orig, (int(trbrX), int(trbrY)), 5, (255, 0, 0), -1) # 在中心點之間繪製直線,用紫紅色的線來表示 cv2.line(orig, (int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)), (255, 0, 255), 2) cv2.line(orig, (int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)), (255, 0, 255), 2) # 計算兩個中心點之間的歐氏距離,即圖片距離 dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY)) dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY)) # 初始化測量指標值,參考物體在圖片中的寬度已經通過歐氏距離計算得到,參考物體的實際大小已知 if pixelsPerMetric is None: pixelsPerMetric = dB / (1.968503 *2.54) #大約5公分=1.968503英吋 # 計算目標的實際大小(寬和高),用英尺來表示 dimA = dA / pixelsPerMetric dimB = dB / pixelsPerMetric # 在圖片中繪製結果 cv2.putText(orig, "{:.1f}cm".format(dimB), (int(tltrX - 15), int(tltrY - 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 2) cv2.putText(orig, "{:.1f}cm".format(dimA), (int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 2) print('長:',"{:.1f}cm".format(dimB)) print('寬:',"{:.1f}cm".format(dimA)) now_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time())) save_pic_name = now_time + '_' + '.jpg' cv2.imwrite(save_pic_name, orig) path = 'size_output.txt' with open(path, 'a') as f: f.write('長:'+"{:.1f}cm".format(dimB)+' 寬:'+"{:.1f}cm".format(dimA) + '\n') # 顯示結果 #cv2.namedWindow('Image', 0) cv2.namedWindow("Image", cv2.WINDOW_NORMAL) cv2.resizeWindow("Image", 800, 600) cv2.imshow("Image", orig) cv2.waitKey(0)