質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
OpenCV

OpenCV(オープンソースコンピュータービジョン)は、1999年にインテルが開発・公開したオープンソースのコンピュータビジョン向けのクロスプラットフォームライブラリです。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

3435閲覧

None type object has no attribute 'astype'

bof

総合スコア18

OpenCV

OpenCV(オープンソースコンピュータービジョン)は、1999年にインテルが開発・公開したオープンソースのコンピュータビジョン向けのクロスプラットフォームライブラリです。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2017/08/16 05:24

編集2017/08/16 09:09

python3.6 opencv3です。
ソースコードの一部エラー箇所

descriptors = descriptors.astype(np.float32)

エラーコード

AttributeError: 'NoneType' object has no attribute 'astype'

ソースコードのエラー箇所に当たるdescriptorsは下記のコードから生成しました。

keypoints, descriptors= detector.detectAndCompute(patches[x], None) ``` patch[x].dtypeはuint8なのですが、descriptorsがNonetypeになってしまいます。 どのように修正すればよいのか教えていただければ幸いです。 ```ここに言語を入力 # -*- coding: utf-8 -*- import os import sys import cv2 import numpy as np from sklearn.feature_extraction import image ## 画像データのクラスIDとパスを取得 # # @param dir_path 検索ディレクトリ # @return data_sets [クラスID, 画像データのパス]のリスト def getDataSet(dir_path): data_sets = [] sub_dirs = os.listdir(dir_path) for classId in sub_dirs: sub_dir_path = dir_path + '/' + classId img_files = os.listdir(sub_dir_path) for f in img_files: data_sets.append([classId, sub_dir_path + '/' + f]) return data_sets """ main """ # 定数定義 GRAYSCALE = 0 # KAZE特徴量抽出器 detector = cv2.xfeatures2d.SIFT_create() """ train """ print("train start") # 訓練データのパスを取得 train_set = getDataSet('train_img') # 辞書サイズ dictionarySize = 9 # Bag Of Visual Words分類器 bowTrainer = cv2.BOWKMeansTrainer(dictionarySize) x=0 # 各画像を分析 for i, (classId, data_path) in enumerate(train_set): # 進捗表示 sys.stdout.write(".") # カラーで画像読み込み color = cv2.imread(data_path, cv2.IMREAD_COLOR) size = (100,100) colora = cv2.resize(color,size) patches = image.extract_patches_2d(colora, (3, 3)) patches = patches.astype(np.uint8) #print(color.shape, patches.shape, patches.dtype) # 特徴点とその特徴を計算 while x<9604: #keypoints, descriptors= detector.detectAndCompute(patches, None) keypoints = cv2.KeyPoint(patches[x][1][0],patches[x][0][1],size=9, angele=-1, response=0, octave=0, class_id=-1) descriptors = detector.compute(patches[x], keypoints) #print(patches[x].dtype, keypoints) x=x+1 #descriptors = detector.compute(patches, keypoints) # intからfloat32に変換 descriptors = descriptors.astype(np.float32) # 特徴ベクトルをBag Of Visual Words分類器にセット bowTrainer.add(descriptors) # Bag Of Visual Words分類器で特徴ベクトルを分類 codebook = bowTrainer.cluster() # 訓練完了 print("train finish") """ test """ print("test start") # テストデータのパス取得 test_set = getDataSet("test_img") # KNNを使って総当たりでマッチング matcher = cv2.BFMatcher() # Bag Of Visual Words抽出器 bowExtractor = cv2.BOWImgDescriptorExtractor(detector, matcher) # トレーニング結果をセット bowExtractor.setVocabulary(codebook) success = 0 fail = 0 # 正しく学習できたか検証する for i, (classId, data_path) in enumerate(test_set): # グレースケールで読み込み gray = cv2.imread(data_path, cv2.IMREAD_COLOR) # 特徴点と特徴ベクトルを計算 print(gray.dtype) size = (100,100) graya = cv2.resize(gray,size) patches = image.extract_patches_2d(graya, (3, 3)) print(patches.shape) while x<9604: keypoints, descriptors= detector.detectAndCompute(patches[x], None) # intからfloat32に変換 特徴量 descriptors = descriptors.astype(np.float32) # Bag Of Visual Wordsの計算 ヒストグラム bowDescriptors = bowExtractor.compute(patches[x], keypoints) # 結果表示 className = {"0": "airplane", "1": "ferry", "2": "laptop"} actual = "???" if bowDescriptors[0][0] > bowDescriptors[0][1] and bowDescriptors[0][0] > bowDescriptors[0][2]: actual = className["0"] elif bowDescriptors[0][0] < bowDescriptors[0][1] and bowDescriptors[0][2] < bowDescriptors[0][1]: actual = className["1"] else: actual = className["2"] result = "" if actual == "???": result = " => unknown." elif className[classId] == actual: result = " => success!!" success = success + 1 else: result = " => fail" fail = fail + 1 print("expected: ", className[classId], ", actual: ", actual, result) print("suceess percentage:", success/(success+fail)) ``` 取り込んだ画像をpatchにしたものから特徴点(keypoint)を抽出する段階で、特徴点をpatchの中心に指定したいのですが,そこがうまくいってません。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

LouiS0616

2017/08/16 05:48

detectorはどのように初期化しましたか?
bof

2017/08/16 06:35

detector = cv2.xfeatures2d.SIFT_create()としました
LouiS0616

2017/08/16 07:41

エラーを再現できません。全体のコードをお示しいただけますか?
bof

2017/08/16 09:01

全体のコードを載せました
bof

2017/08/16 09:56 編集

そうです。
guest

回答1

0

ベストアンサー

難しく考えすぎて、わけがわからなくなっている気がします。
sklearn.feature_extraction.image.extract_patches_2dはこの場合不要です。

また、既に特徴点を検出しているのなら、改めてdetectを行う必要はありません。
detectAndComputeより、単にcomputeを用いた方が簡潔です。


参考までに、次のようにして簡単に網目状の検出を行うことができます。
特徴点の位置は全ての画像で共通していますから、一回だけ計算して使いまわせますね。

Python

1import cv2 2import numpy as np 3import itertools 4 5def detect_dense_keypoints(image_side, interval=3): 6 keys = np.arange(0, image_side + 1, interval) 7 keys = list(itertools.product(keys, keys)) 8 9 ret_keypoints = [] 10 for key in keys: 11 ret_keypoints.append(cv2.KeyPoint(*key, interval)) 12 13 return ret_keypoints 14 15def main(): 16 IMAGE_SIDE = 100 17 18 src_image = cv2.imread('Lenna.png') 19 src_image = cv2.resize(src_image, (IMAGE_SIDE, IMAGE_SIDE)) 20 21 keypoints = detect_dense_keypoints(image_side=IMAGE_SIDE) 22 dst_image = cv2.drawKeypoints(src_image, keypoints, None) 23 24 descriptor = cv2.xfeatures2d.SIFT_create() 25 _, values = descriptor.compute(image=src_image, keypoints=keypoints) 26 27 cv2.imshow('src', src_image) 28 cv2.imshow('dst', dst_image) 29 cv2.waitKey() 30 31if __name__ == '__main__': 32 main()

正直に言うと、私自身記述子がNoneになる原因は未だ突き止めていません。
しかし、特徴点の検出をもう少しスマートにすることで、見通しがつくのではないでしょうか。
直接的な回答になっておらずすみません、また上手くいかないことがあればご質問ください。

投稿2017/08/16 10:43

編集2017/08/16 11:03
LouiS0616

総合スコア35658

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

bof

2017/08/16 10:54

ご回答ありがとうございました。特徴点の検出について修正してみたいと思います。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問