Raspberry Pi 備忘録 / Mbedもあるよ!

Raspberry Pi であれこれやった事の記録

Raspberry pi でロボットアームを動かす その7 カメラモジュールv2に変更

カメラを、WEBカメラからカメラモジュールv2に変更しました。

それにともなってコードも少しだけ変わりました。

コーディング

#!/usr/bin/python
# coding: utf-8 

import sys
import io
import cv2
import numpy as np
import pprint as pp
import picamera

def capture_camera():
        blue_min = np.array([110, 100, 100], np.uint8)
        blue_max = np.array([140, 255, 255], np.uint8)
        green_min = np.array([40, 70, 70], np.uint8)
        green_max = np.array([80, 255, 255], np.uint8)

        with picamera.PiCamera() as camera:
                camera.hflip = True
                camera.vflip = True
                camera.resolution = (640, 480)
                camera.framerate = 10
                stream = io.BytesIO()

                while True:
                        camera.capture(stream, format="jpeg", use_video_port=True)
                        frame = np.fromstring(stream.getvalue(), dtype=np.uint8)
                        stream.seek(0)
                        frame = cv2.imdecode(frame, 1)

                        # 2値化
                        image_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)      # HSV, range of Hue is 0-180
                        h = image_hsv[:, :, 0]
                        s = image_hsv[:, :, 1]
                        v = image_hsv[:, :, 2]
                        width   = h[0,:].size
                        height  = h[:,0].size
#                       print( 'width %s, height %s' % (width, height) )

                        threshold_green_img = cv2.inRange(image_hsv, green_min, green_max)
                        # 輪郭抽出
                        contours, hierarchy = cv2.findContours(threshold_green_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#                       pp.pprint( contours )

                        cv2.drawContours(frame, contours, -1, (0,255,0), 3)

                        if len(contours) > 0 :
                                rects = []
                                for contour in contours:
                                        approx = cv2.convexHull(contour)
                                        rect = cv2.boundingRect(approx) # x,y,w,h 
                                        rects.append(rect)  
                                pp.pprint( len(rects) )
                                max_rect        = getBiggestRect( rects )
                                center_x        = max_rect[0] + max_rect[2]/2
                                center_y        = max_rect[1] + max_rect[3]/2
                                # 囲む
                                cv2.rectangle(frame, (max_rect[0], max_rect[1]), (max_rect[0]+max_rect[2], max_rect[1]+max_rect[3]), (0, 0, 255), 3)
                                # 線を引く
                                cv2.line(frame, (center_x, 0), (center_x, height), (0, 0, 255)) # Draw Red Line
                                cv2.line(frame, (0, center_y), (width, center_y), (0, 0, 255)) # Draw Red Line

                        cv2.imshow('threshold_green_img', frame)

                        #frameを表示
                        #cv2.imshow('camera capture', frame)

                        #10msecキー入力待ち
                        k = cv2.waitKey(10)
                        #Escキーを押されたら終了
                        if k == 27:
                                break

def getBiggestRect( rects ):
        pre_area        = 0
        biggest_index   = 0
        for i, rect in enumerate(rects):
                area    = rect[2] * rect[3]
                if area > pre_area:
                        pre_area        = area
                        biggest_index   = i
        return rects[biggest_index]

if __name__ == '__main__':
        try:
                while True:
                        capture_camera()
                        break

        except KeyboardInterrupt:
                        pass

#キャプチャを終了
cv2.destroyAllWindows()

実行

f:id:pongsuke:20170201131510j:plain