LoginSignup
3
4

More than 3 years have passed since last update.

Python OpenCV Mat Typeの取得

Posted at

想定している状況

OpenCVを用いて、Laplacianフィルタなどをかける場合
cv2.(input, CV_8U) のように、Mat Type(CV_8Uなどの値)を指定する必要がある。

C++やC#ならばこのMatTypeは input.depth() で得られる。
しかし、Pythonの場合 input の画像はNumpyで読み込まれるため、Mat Typeを得ることができない。そのため毎回input画像の型によってプログラムを書き直す必要性がある。

打開策

Numpy で input画像のチャンネル数とデータ型を調べる。
得られた情報をもとにif文でMat Typeを判別

具体的には

チャンネル数の調べ方  

if np.ndim(input) == 3:
_, _, ch = input.shape

elif np.ndim(input) ==2: #グレースケールの場合
ch = 1

データ型の調べ方

input.dtype ##uint8 などのような値が得られる

これらの情報を元にMat Type を判別する

スクリーンショット 2019-07-31 17.50.18.png

引用:http://ninghang.blogspot.com/2012/11/list-of-mat-type-in-opencv.html
この表を見るとチャンネル数とデータ型によってMat Typeの数字が決まることが確認できる。

幸い、cv2.Laplacianなどで指定するMatTypeは数字である。(CV_8Uの中身は数字)

スクリーンショット 2019-07-31 18.14.02.png

このように書けば大丈夫なはず。

問題点

どちらにせよめんどくさい。
もっと綺麗な書き方
もしくは、簡単にやるやり方を知ってる方いらしたら教えてください。

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