輪郭の外接矩形の中心を求めたいのですが続きが分かりません
各輪郭の外接矩形の重心を求めるにはどうすれば良いでしょうか。
輪郭を抽出し外接矩形を求めるところまでは自力でできています。
python
1import cv2 2import numpy as np 3import time 4 5i = 0 # カウント変数 6# 動画ファイルのキャプチャ 7cap = cv2.VideoCapture("zverev1.mp4") 8 9# 最初のフレームを背景画像に設定 10ret, bg = cap.read() 11 12# グレースケール変換 13bg = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY) 14 15while(cap.isOpened()): 16 # フレームの取得 17 ret, frame = cap.read() 18 19 # グレースケール変換 20 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 21 # 差分の絶対値を計算 22 mask = cv2.absdiff(gray, bg) 23 24 # 差分画像を二値化してマスク画像を算出 25 th, im_th = cv2.threshold(mask, 30, 255, cv2.THRESH_BINARY) 26 27 contours, hierarchy = cv2.findContours(im_th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE ) 28 29 for i, contour in enumerate(contours): 30 cv2.drawContours(gray, contours, i, (255, 0, 0), 2) 31 x,y,w,h = cv2.boundingRect(contour) 32 cv2.rectangle(gray,(x,y),(x+w-1,y+h-1),(0,255,0),2) 33 34 35 # フレームとマスク画像を表示 36 cv2.imshow("Mask", im_th) 37 cv2.imshow("Flame", gray) 38 cv2.imshow("Background", bg) 39 40 41 42 # 待機(0.03sec) 43 time.sleep(0.03) 44 i += 1 # カウントを1増やす 45 46 # 背景画像の更新(一定間隔) 47 if(i > 30): 48 ret, bg = cap.read() 49 bg = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY) 50 i = 0 # カウント変数の初期化 51 52 # qキーが押されたら途中終了 53 if cv2.waitKey(1) & 0xFF == ord('q'): 54 break 55 56cap.release() 57cv2.destroyAllWindows() 58```