【OpenCV】OpenCV3以降でDense SIFTを使いたい
画像から特徴量抽出する方法として、Dense SIFTを使いたいと思ったのですが、何故かOpenCV2のあるバージョンで削除されてしまったようです。ただ幸いkeypointを指定することでDense SIFTを実施できるようなのでメモします(とはいえSIFTの特許の問題があるので2019年3月までは様子見、もしくは別の抽出器を利用でしょうか)。
# dense_feature_detector.py import cv2 class DenseFeatureDetector(object): def __init__(self, detector, step, scale, start): self._detector = detector self._step = step self._scale = scale self._start = start pass def detect(self, image): # Convert image to gray if it is color if len(image.shape) == 3: gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) else: gray_image = image # Create dense keypoints keypoints = self._create_keypoints(gray_image) _, features = self._detector.compute(image, keypoints) return keypoints, features def _create_keypoints(self, gray_image): keypoints = [] rows, cols = gray_image.shape for y in range(self._start, rows, self._step): for x in range(self._start, cols, self._step): keypoints.append(cv2.KeyPoint(float(x), float(y), self._scale)) return keypoints
# main.py import cv2 from dense_feature_detector import DenseFeatureDetector if __name__ == '__main__': image = cv2.imread('lenna.jpg') sift = cv2.xfeatures2d.SIFT_create() detector = DenseFeatureDetector(sift, step=15, scale=15, start=15) keypoints, features = detector.detect(image) dense_keypoints_on_image = cv2.drawKeypoints(image, keypoints, None) cv2.imwrite('dense.png', dense_keypoints_on_image)