前提・実現したいこと
ラズパイ,opencv,picameraを組み合わせ赤色の物体を識別し,その物体が中心に来るようにモーターを制御したいです.色識別のプログラムは下記のコードで完成しています.あとは識別した物体をウィンドウの真ん中に持ってこれるようにモーターの制御をしたいです.全てにおいて初心者なのでご協力お願いします.
該当のソースコード
python3
1import cv2 2import numpy as np 3 4def find_rect_of_target_color(image): 5 hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV_FULL) 6 h = hsv[:, :, 0] 7 s = hsv[:, :, 1] 8 mask = np.zeros(h.shape, dtype=np.uint8) 9 mask[((h < 20) | (h > 200)) & (s > 128)] = 255 10 contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 11 rects = [] 12 for contour in contours: 13 approx = cv2.convexHull(contour) 14 rect = cv2.boundingRect(approx) 15 rects.append(np.array(rect)) 16 return rects 17if __name__ == "__main__": 18 capture = cv2.VideoCapture(0) 19 while cv2.waitKey(30) < 0: 20 _, frame = capture.read() 21 rects = find_rect_of_target_color(frame) 22 if len(rects) > 0: 23 rect = max(rects, key=(lambda x: x[2] * x[3])) 24 cv2.rectangle(frame, tuple(rect[0:2]), tuple(rect[0:2] + rect[2:4]), (0, 0, 255), thickness=2) 25 cv2.imshow('red', frame) 26 capture.release() 27 cv2.destroyAllWindows()
あなたの回答
tips
プレビュー