9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Cython 型指定一覧

Last updated at Posted at 2021-07-01

はじめに

Cython という Python に型指定をするだけで処理によっては高速にすることができるライブラリを導入したのですが、型指定の種類がまとまった記事がなかったため、まとめることにしました。

Cython概要

Cython(サイソン)は、C言語によるPythonの拡張モジュールの作成の労力を軽減することを目的として開発されたプログラミング言語である。
その言語仕様は__ほとんどPythonのもの__と同じ (上位互換) だが、Cの関数を直接呼び出したり、C言語の変数の型やクラスを宣言できるなどの拡張が行われている。
Cythonの処理系ではソースファイルをCのコードに変換し、コンパイルすればPythonの拡張モジュールになるようにして出力する。
(参考) https://ja.wikipedia.org/wiki/Cython

詳細な使い方については、すでに記事が上がっていますのでそちらを参考にしてください。

参考リンク

型一覧 (基本)

基本的な型についてはこちらにまとめました。

cdef: 
    # string
    str string_test

    # integer
    int integer_test

    # float
    float float_test

    # boolean
    bint boolean_test

    # list (array)
    list list_test

    # tuple (array)
    tuple tuple_test

    # dict (hash)
    dict dict_test

OpenCV frame 型指定

OpenCVの使い方については他に記事が上がっていますので、そちらをご参考ください。

cnp.ndarray[unsigned char, ndim=3]こちらの型で型指定をすることができます。

import cv2
cimport numpy as cnp  # cython用のnumpyをインポートする

cdef:
    # frame 型指定
    cnp.ndarray[unsigned char, ndim=3] frame

cam = cv2.VideoCapture(0)
ret, frame = cam.read()

まとめ

Cython化するだけで高速化される可能性が高いので、可読性を下げないように積極的に使っていきたいと思っています。
他にも役立ちそうな型指定を見つけたら追記していこうと思います。


会社紹介

株式会社 Mosaica
最先端テクノロジーで社会課題を解決し、持続可能な未来を創造する IT カンパニー。
AI ソリューション、クラウド統合、DX 推進、経営コンサルティングなど包括的なサービスでビジネス変革を支援しています。

詳しくは 公式サイト までお気軽にご相談ください。
公式サイト: https://mosaica.co.jp/

9
3
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
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?