LoginSignup
20
19

More than 3 years have passed since last update.

【CoreMotion】iPhoneのモーションデータ(加速度や角速度など)をCSVで記録するアプリを作成してみた

Last updated at Posted at 2019-09-06

はじめに

iPhoneには加速度センサーや角速度センサー(ジャイロ)といったセンサー類が搭載されており、Core Motionというフレームワークを使うことでこれらのセンサーデータを簡単に取得することができます(機種による違いはありますが)。
モーションセンサーによる行動認識系の論文を見ていると、スマートフォンを使った研究もけっこう多かったりします(お手軽にデータを記録できる端末ということなんでしょう)。

私もiPhoneから得られたモーションデータを機械学習させたいなということでそれらをCSVファイルとして記録する簡易アプリを作成したのですが、せっかくなのでGitHubでも公開しました。注意事項や使い方などはREADMEをご参照ください。

今回はシンプルに、CoreMotionの中でもCMDeviceMotion経由で得られる以下の項目に限定しています。

  • Attitude(姿勢)
  • Rotation Rate(角速度)
  • Gravity(重力加速度)
  • User Acceleration(加速度)

本記事ではデータの取得部分のコードだけ抜粋して載せておきます。
他にもCoreMotionを使用することで磁気センサーや気圧センサー等のデータも取得可能ですので、興味ある方は良さげに改良してください(すでにそういうのも転がっているかも)。

モーションデータの取得例

// CMMotionManagerのインスタンスを生成
let motionManager = CMMotionManager()

// モーションデータの取得を開始
func startSensorUpdates(intervalSeconds:Double) {
    if motionManager.isDeviceMotionAvailable{
        motionManager.deviceMotionUpdateInterval = intervalSeconds

        motionManager.startDeviceMotionUpdates(to: OperationQueue.current!, withHandler: {(motion:CMDeviceMotion?, error:Error?) in
            self.getMotionData(deviceMotion: motion!)

        })
    }
}

// モーションデータの取得(例としてコンソールへ出力)
func getMotionData(deviceMotion:CMDeviceMotion) {
    print("attitudeX:", deviceMotion.attitude.pitch)
    print("attitudeY:", deviceMotion.attitude.roll)
    print("attitudeZ:", deviceMotion.attitude.yaw)
    print("gyroX:", deviceMotion.rotationRate.x)
    print("gyroY:", deviceMotion.rotationRate.y)
    print("gyroZ:", deviceMotion.rotationRate.z)
    print("gravityX:", deviceMotion.gravity.x)
    print("gravityY:", deviceMotion.gravity.y)
    print("gravityZ:", deviceMotion.gravity.z)
    print("accX:", deviceMotion.userAcceleration.x)
    print("accY:", deviceMotion.userAcceleration.y)
    print("accZ:", deviceMotion.userAcceleration.z)
}

intervalSecondsでデータの更新間隔(秒)を指定してあげてください。ちなみにstartDeviceMotionUpdates後はIntervalを変更できないみたいなので、ひとまず今回は変更するたびに毎回stopDeviceMotionUpdatesするようにしてみました(GitHubのコードを参照)。

おまけ

スマートフォンのセンサーデータの活用にはZIG SIMというアプリも便利です。昔に書いたQiita記事でちょっと使わせていただいていたりしています。
https://qiita.com/FollowTheDarkside/items/1a4632ca7c75e2b90127

また、機械学習では靴型のウェアラブルデバイスORPHEを使ってブレイクダンスの動作識別をしていたりします。よろしければそちらの記事もご覧ください!
https://qiita.com/FollowTheDarkside/items/956b78869d3198982c9c
http://hahaeatora.hateblo.jp/entry/2018/10/14/183000

20
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
19