大学生の初心者です。カメラから移動体を読み取り、QRやカラーコードなどで見分けるような実験をしています
『画像処理 アルゴリズム入門』西住 流 p164の移動物体の検出より、フォルダ内の動画から検出することはできたのですが、そのコードをUSBカメラをつないで映し出したものからリアルタイムで、処理をしたいのですが可能でしょうか? 手法やコードなどをご教授願います。
コード
import
1import numpy as np 2 3 4# 追跡対象の色範囲( Hue の値域) 5def is_target(roi): 6 return (roi <= 30) | (roi >= 150) 7 8 9# マスクから面積最大ブロブの中心座標を算出 10def max_moment_point(mask): 11 # ラベリング処理 12 label = cv2.connectedComponentsWithStats(mask) 13 data = np.delete(label[2], 0, 0) # ブロブのデータ 14 center = np.delete(label[3], 0, 0) # 各ブロブの中心座標 15 moment = data[:,4] # 各ブロブの面積 16 max_index = np.argmax(moment) # 面積最大のインデックス 17 return center[max_index] # 面積最大のブロブの中心座標 18 19 20# パーティクルの初期化 21def initialize(img, N): 22 mask = img.copy() # 画像のコピー 23 mask[is_target(mask) == False] = 0 # マスク画像の作成(追跡対象外の色なら画素値 0 ) 24 x, y = max_moment_point(mask) # マスクから面積最大ブロブの中心座標を算出 25 w = calc_likelihood(x, y, img) # 尤度の算出 26 ps = np.ndarray((N, 3), dtype=np.float32) # パーティクル格納用の配列を生成 27 ps[:] = [x, y, w] # パーティクル用配列に中心座標と尤度をセット 28 return ps 29 30 31# 1. リサンプリング ( 前状態の重みに応じてパーティクルを再選定 ) 32def resampling(ps): 33 34 # 累積重みの計算 35 ws = ps[:, 2].cumsum() 36 last_w = ws[ws.shape[0] - 1] 37 38 # 新しいパーティクル用の空配列を生成 39 new_ps = np.empty(ps.shape) 40 41 # 前状態の重みに応じてパーティクルをリサンプリング(重みは 1.0 ) 42 for i in range(ps.shape[0]): 43 w = np.random.rand() * last_w 44 new_ps[i] = ps[(ws > w).argmax()] 45 new_ps[i, 2] = 1.0 46 return new_ps 47 48 49# 2. 推定(パーティクルの位置) 50def predict_position(ps, var=13.0): 51 # 分散に従ってランダムに少し位置をずらす 52 ps[:, 0] += np.random.randn((ps.shape[0])) * var 53 ps[:, 1] += np.random.randn((ps.shape[0])) * var 54 55 56# 尤度の算出 57def calc_likelihood(x, y, img, w=30, h=30): 58 59 # 画像から座標 (x,y) を中心とする幅 60 x1, y1 = max(0, x-w/2), max(0, y-h/2) 61 x2, y2 = min(img.shape[1], x+w/2), min(img.shape[0], y+h/2) 62 x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2) 63 roi = img[y1:y2, x1:x2] 64 65 # 矩形領域中に含まれる追跡対象 ( 色 ) の存在率を尤度として計算 66 count = roi[is_target(roi)].size 67 return (float(count) / img.size) if count > 0 else 0.0001 68 69 70# パーティクルの重み付け 71def calc_weight(ps, img): 72 73 # 尤度に従ってパーティクルの重み付け 74 for i in range(ps.shape[0]): 75 ps[i][2] = calc_likelihood(ps[i, 0], ps[i, 1], img) 76 77 # 重みの正規化 78 ps[:, 2] *= ps.shape[0] / ps[:, 2].sum() 79 80 81# 3. 観測(全パーティクルの重み付き平均を取得) 82def observer(ps, img): 83 # パーティクルの重み付け 84 calc_weight(ps, img) 85 86 # 重み和の計算 87 x = (ps[:, 0] * ps[:, 2]).sum() 88 y = (ps[:, 1] * ps[:, 2]).sum() 89 90 # 重み付き平均を返す 91 return (x, y) / ps[:, 2].sum() 92 93 94# 「パーティクル・フィルタ」 95def particle_filter(ps, img, N=300): 96 # パーティクルが無い場合 97 if ps is None: 98 ps = initialize(img, N) # パーティクルを初期化 99 100 ps = resampling(ps) # 1. リサンプリング 101 predict_position(ps) # 2. 推定 102 x, y = observer(ps, img) # 3. 観測 103 return ps, int(x), int(y) 104 105 106def main(): 107 108 # 動画のキャプチャ 109 cap = cv2.VideoCapture("input1.mp4") 110 ps = None 111 112 while(cap.isOpened()): 113 114 ret, frame = cap.read() 115 hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV_FULL) 116 h = hsv[:, :, 0] 117 118 # S, V を 2 値化(大津の手法) 119 ret, s = cv2.threshold(hsv[:, :, 1], 0, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU) 120 ret, v = cv2.threshold(hsv[:, :, 2], 0, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU) 121 h[(s == 0) | (v == 0)] = 100 122 123 # 「パーティクル・フィルタ」 124 ps, x, y = particle_filter(ps, h, 300) 125 126 if ps is None: 127 continue 128 129 # 画像の範囲内にあるパーティクルのみ取り出し 130 ps1 = ps[(ps[:, 0] >= 0) & (ps[:, 0] < frame.shape[1]) & 131 (ps[:, 1] >= 0) & (ps[:, 1] < frame.shape[0])] 132 133 # パーティクルを赤色で塗りつぶす 134 for i in range(ps1.shape[0]): 135 frame[int(ps1[i, 1]), int(ps1[i, 0])] = [0, 0, 200] 136 137 # パーティクルの集中部分を赤い矩形で囲む 138 cv2.rectangle(frame, (x-20, y-20), (x+20, y+20), (0, 0, 200), 5) 139 cv2.imshow('Result', frame) 140 141 # q キーが押されたら終了 142 if cv2.waitKey(25) & 0xFF == ord('q'): 143 break 144 145 cap.release() 146 cv2.destroyAllWindows() 147 148 149if __name__ == "__main__": 150 main() 151コード
Windows10、spyder(python3.7)で実行しています。
カメラはUSBなら何でもよいのですが、使っているカメラはLOAS‐15BKです。
##添付ファイル
input.mp4 の動画が添付できませんでした。
先端が赤い振り子が揺れている動画でした。
上記のコードでは問題なくレスポンスを受け取れました。
よろしくお願いいたします。