opencv計算機視覺學習筆記五
第六章 影象檢索以及基於影象描述符的搜尋
通過提取特徵進行影象的匹配與搜尋
1 特徵檢測演算法
常見的特徵和提取演算法:
Harris 檢測角點
Sift 檢測斑點(blob) 有專利保護
Surf 檢測斑點 有專利保護
Fast 檢測角點
Brief 檢測斑點
Orb 帶方向的fast演算法和具有旋轉不變性的brief演算法
特徵的定義
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2016/12/5 12:30 # @Author : Retacn # @Site : 檢測影象的角點 # @File : cornerHarris.py # @Software: PyCharm__author__ = "retacn" __copyright__ = "property of mankind." __license__ = "CN" __version__ = "0.0.1" __maintainer__ = "retacn" __email__ = "[email protected]" __status__ = "Development" import cv2 import numpy as np # 讀入影象 img = cv2.imread('../test1.jpg') # 轉換顏色空間 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = np.float32(gray)# 檢測影象角點 dst = cv2.cornerHarris(gray, 2, 23, # sobel運算元的中孔,3-31之間的奇數 0.04) # 將檢測到有角點標記為紅色 img[dst > 0.01 * dst.max()] = [0, 0, 255] while (True): cv2.imshow("corners", img) if cv2.waitKey(33) & 0xFF == ord('q'): breakcv2.destroyAllWindows()
使用dog和sift進行特徵提取和描述
示例程式碼如下:
import cv2 import sys import numpy as py # 讀入影象 # imgpath=sys.argv[1] imgpath = '../test1.jpg' img = cv2.imread(imgpath) # 更換顏色空間 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 建立sift物件,計算灰度影象,會使用dog檢測角點 sift = cv2.xfeatures2d.SIFT_create() keypoints, descriptor = sift.detectAndCompute(gray, None) # print(keypoints) # 關鍵點有以下幾個屬性 # angle 表示特徵的方向 # class_id 關鍵點的id # octave 特徵所在金字塔的等級 # pt 影象中關鍵點的座標 # response 表示關鍵點的強度 # size 表示特徵的直徑 img = cv2.drawKeypoints(image=img, outImage=img, keypoints=keypoints, color=(51, 163, 236), flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # 顯示影象 cv2.imshow('sift_keypoints', img) while (True): if cv2.waitKey(int(1000 / 12)) & 0xFF == ord('q'): break cv2.destroyAllWindows()
使用心有快速hessian演算法和SURF來提取特徵
示例程式碼發如下:
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2016/12/10 17:30 # @Author : Retacn # @Site : sift用於檢測斑點 # @File : sift.py # @Software: PyCharm __author__ = "retacn" __copyright__ = "property of mankind." __license__ = "CN" __version__ = "0.0.1" __maintainer__ = "retacn" __email__ = "[email protected]" __status__ = "Development" import cv2 import sys import numpy as py # 讀入影象 # imgpath=sys.argv[1] # alg=sys.argv[2] # threshold=sys.argv[3] imgpath = '../test1.jpg' img = cv2.imread(imgpath) # alg = 'SURF' alg = 'SIFT' # threshold = '8000' # 閾值越小特徵點越多 threshold = '4000' def fd(algorithm): if algorithm == 'SIFT': return cv2.xfeatures2d.SIFT_create() if algorithm == 'SURF': # return cv2.xfeatures2d.SURF_create(float(threshold) if len(sys.argv) == 4 else 4000) return cv2.xfeatures2d.SURF_create(float(threshold)) # 更換顏色空間 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 建立sift物件,計算灰度影象,會使用dog檢測角點 fd_alg = fd(alg) keypoints, descriptor = fd_alg.detectAndCompute(gray, None) # print(keypoints) # 關鍵點有以下幾個屬性 # angle 表示特徵的方向 # class_id 關鍵點的id # octave 特徵所在金字塔的等級 # pt 影象中關鍵點的座標 # response 表示關鍵點的強度 # size 表示特徵的直徑 img = cv2.drawKeypoints(image=img, outImage=img, keypoints=keypoints, color=(51, 163, 236), flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # 顯示影象 cv2.imshow('keypoints', img) while (True): if cv2.waitKey(int(1000 / 12)) & 0xFF == ord('q'): break cv2.destroyAllWindows()
基於ORB的特徵檢測和特徵匹配
ORB是基於
FAST(featuresfrom accelerated segment test)關鍵點檢測技術
在畫素周圍繪製一個圓,包含16個畫素
BRIEF(binaryrobust independent elementary features) 描述符
暴力(brute-force)匹配法
比較兩個描述符,併產生匹配結果
ORB特徵匹配
示例程式碼如下:
import numpy as np import cv2 from matplotlib import pyplot as plt cv2.ocl.setUseOpenCL(False) # 讀入灰度影象 img1 = cv2.imread('../test2_part.jpg', cv2.IMREAD_GRAYSCALE) img2 = cv2.imread('../test2.jpg', cv2.IMREAD_GRAYSCALE) # 建立orb特徵檢測器和描述符 orb = cv2.ORB_create() kp1, des1 = orb.detectAndCompute(img1, None) kp2, des2 = orb.detectAndCompute(img2, None) # 暴力匹配 bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) matches = bf.match(des1, des2) matches = sorted(matches, key=lambda x: x.distance) # 顯示影象 img3 = cv2.drawMatches(img1, kp1, img2, kp2, matches[:40], img2, flags=2) plt.imshow(img3), plt.show()
報如下錯誤:
cv2.error: D:\Build\OpenCV\opencv-3.1.0\modules\python\src2\cv2.cpp:163:error: (-215) The data should normally be NULL! in functionNumpyAllocator::allocate
解決辦法,新增如下程式碼 :
cv2.ocl.setUseOpenCL(False)
k最鄰近配匹
import numpy as np import cv2 from matplotlib import pyplot as plt cv2.ocl.setUseOpenCL(False) # 讀入灰度影象 img1 = cv2.imread('../test2_part.jpg', cv2.IMREAD_GRAYSCALE) img2 = cv2.imread('../test2.jpg', cv2.IMREAD_GRAYSCALE) # 建立orb特徵檢測器和描述符 orb = cv2.ORB_create() kp1, des1 = orb.detectAndCompute(img1, None) kp2, des2 = orb.detectAndCompute(img2, None) # knn匹配,返回k個匹配 bf = cv2.BFMatcher(cv2.NORM_L1, crossCheck=False) matches = bf.knnMatch(des1, des2, k=2) # 顯示影象 img3 = cv2.drawMatchesKnn(img1, kp1, img2, kp2, matches, img2, flags=2) plt.imshow(img3), plt.show()
Flann匹配法
Fast library for approximate nearestneighbors 近似最近鄰的快速庫
import numpy as np import cv2 from matplotlib import pyplot as plt # 讀入影象 queryImage = cv2.imread('../test2_part.jpg', cv2.IMREAD_GRAYSCALE) trainingImage = cv2.imread('../test2.jpg', cv2.IMREAD_GRAYSCALE) # 建立sift物件 sift = cv2.xfeatures2d.SIFT_create() kp1, des1 = sift.detectAndCompute(queryImage, None) kp2, des2 = sift.detectAndCompute(trainingImage, None) FLANN_INDEX_KDTREE = 0 # 建立字典引數 indexParams = dict(algorithm=FLANN_INDEX_KDTREE, trees=5) # 處理索引 searchParams = dict(checks=50) # 建立物件,用來指定索引樹的遍歷次數 flann = cv2.FlannBasedMatcher(indexParams, searchParams) matches = flann.knnMatch(des1, des2, k=2) matchesMask = [[0, 0] for i in range(len(matches))] for i, (m, n) in enumerate(matches): if m.distance < 0.7 * n.distance: matchesMask[i] = [1, 0] drawParams = dict(matchColor=(0, 255, 0), singlePointColor=(255, 0, 0), matchesMask=matchesMask, flags=0) resultImage = cv2.drawMatchesKnn(queryImage, kp1, trainingImage, kp2, matches, None, **drawParams) plt.imshow(resultImage), plt.show()
執行結果如下:
Flann單應性匹配
示例程式碼如下:
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2016/12/11 12:02 # @Author : Retacn # @Site : flann的單應性匹配 # @File : flann_homography.py # @Software: PyCharm __author__ = "retacn" __copyright__ = "property of mankind." __license__ = "CN" __version__ = "0.0.1" __maintainer__ = "retacn" __email__ = "[email protected]" __status__ = "Development" import numpy as np import cv2 from matplotlib import pyplot as plt MIN_MATCH_COUNT = 10 # 讀入影象 img1 = cv2.imread('../test3_part.jpg', cv2.IMREAD_GRAYSCALE) img2 = cv2.imread('../test3.jpg', cv2.IMREAD_GRAYSCALE) # 建立sift物件 sift = cv2.xfeatures2d.SIFT_create() # 查詢特徵點和描述符 kp1, des1 = sift.detectAndCompute(img1, None) kp2, des2 = sift.detectAndCompute(img2, None) FLANN_INDEX_KDTREE = 0 # 建立字典引數 indexParams = dict(algorithm=FLANN_INDEX_KDTREE, trees=5) # 處理索引 searchParams = dict(checks=50) # 建立物件,用來指定索引樹的遍歷次數 flann = cv2.FlannBasedMatcher(indexParams, searchParams) matches = flann.knnMatch(des1, des2, k=2) good = [] for m, n in matches: if m.distance < 0.7 * n.distance: good.append(m) if len(good) > MIN_MATCH_COUNT: # 在原始影象和訓練影象中查詢特徵點 src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2) dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2) # 單應性 M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) matchesMask = mask.ravel().tolist() # 對第二張圖片計算相對於原始影象的投影畸變,並繪製邊框 h, w = img1.shape pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2) dst = cv2.perspectiveTransform(pts, M) img2 = cv2.polylines(img2, [np.int32(dst)], True, 255, 3, cv2.LINE_AA) else: print("Not enough matches are found -%d/%d" % (len(good), MIN_MATCH_COUNT)) matchesMask = None # 顯示影象 draw_params = dict(matchColor=(0, 255, 0), # 綠線 singlePointColor=None, matchesMask=matchesMask, flags=2) img3 = cv2.drawMatches(img1, kp1, img2, kp2, good, None, **draw_params) plt.imshow(img3, 'gray'), plt.show()
執行結果如下:
基於紋身取證的應用程式示例
A 將影象描述符儲存到檔案中
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2016/12/11 13:52 # @Author : Retacn # @Site : 將影象描述符儲存到檔案中 # @File : generate_descriptors.py # @Software: PyCharm __author__ = "retacn" __copyright__ = "property of mankind." __license__ = "CN" __version__ = "0.0.1" __maintainer__ = "retacn" __email__ = "[email protected]" __status__ = "Development" import cv2 import numpy as np from os import walk from os.path import joinimport sys # 建立描述符 def create_descriptors(folder): files = [] for (dirpath, dirnames, filenames) in walk(folder): files.extend(filenames) for f in files: save_descriptor(folder, f, cv2.xfeatures2d.SIFT_create()) # 儲存描述符 def save_descriptor(folder, image_path, feature_detector): print("reading %s" % image_path) if image_path.endswith("npy") or image_path.endswith("avi"): return img = cv2.imread(join(folder, image_path), cv2.IMREAD_GRAYSCALE) keypoints, descriptors = feature_detector.detectAndCompute(img, None) descriptor_file = image_path.replace("jpg", "npy") np.save(join(folder, descriptor_file), descriptors) # 從執行引數中取得檔案目錄 dir = sys.argv[1] create_descriptors(dir)
B 掃描匹配
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2016/12/11 14:05 # @Author : Retacn # @Site : 掃描匹配 # @File : scan4matches.py # @Software: PyCharm __author__ = "retacn" __copyright__ = "property of mankind." __license__ = "CN" __version__ = "0.0.1" __maintainer__ = "retacn" __email__ = "[email protected]" __status__ = "Development" from os.path import join from os import walk import numpy as np import cv2 from sys import argv from matplotlib import pyplot as plt # 建立檔名陣列 folder = argv[1] query = cv2.imread(join(folder, 'part.jpg'), cv2.IMREAD_GRAYSCALE) # 建立全域性的檔案,圖片,描述符 files = [] images = [] descriptors = [] for (dirpath, dirnames, filenames) in walk(folder): files.extend(filenames) for f in files: if f.endswith('npy') and f != 'part.npy': descriptors.append(f) print(descriptors) # 建立sift檢測器 sift = cv2.xfeatures2d.SIFT_create() query_kp, query_ds = sift.detectAndCompute(query, None) # 建立flann匹配 FLANN_INDEX_KDTREE = 0 index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5) search_params = dict(checks=50) flann = cv2.FlannBasedMatcher(index_params, search_params) # 最小匹配數 MIN_MATCH_COUNT = 10 potential_culprits = {} print(">> Initiating picture scan...") for d in descriptors: print("--------- analyzing %s for matches ------------" % d) matches = flann.knnMatch(query_ds, np.load(join(folder, d)), k=2) good = [] for m, n in matches: if m.distance < 0.7 * n.distance: good.append(m) if len(good) > MIN_MATCH_COUNT: print('%s is a match! (%d)' % (d, len(good))) else: print('%s is not a match ' % d) potential_culprits[d] = len(good) max_matches = None potential_suspect = None for culprit, matches in potential_culprits.items(): if max_matches == None or matches > max_matches: max_matches = matches potential_suspect = culprit print("potential suspect is %s" % potential_suspect.replace("npy", "").upper())
相關推薦
opencv計算機視覺學習筆記五
第六章 影象檢索以及基於影象描述符的搜尋 通過提取特徵進行影象的匹配與搜尋 1 特徵檢測演算法 常見的特徵和提取演算法: Harris 檢測角點 Sift 檢測斑點(blob) 有專利保護 Surf 檢測斑點 有專利保護 Fast 檢測角點 Brief 檢測斑點 Or
opencv計算機視覺學習筆記一
第二章 處理檔案 攝像頭和圖形使用者介面 1 基本i/o指令碼 讀寫影象檔案 示例程式碼如下: #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2016/11/27 12:22 # @Author :
opencv計算機視覺學習筆記七
第八章 目標跟蹤 1檢測目標的移動 基本的運動檢測,示例程式碼如下: import cv2 import numpy as np # 捕獲攝像頭影象 camera = cv2.VideoCapture(0) # es = cv2.getStructuringEleme
opencv3計算機視覺學習筆記-詞袋+svm
BOW實現步驟: 1.建立詞彙(特徵)詞典 2.得到訓練資料到字典的對映 3.選擇適當的分類器進行訓練 4.對新來的樣本,先對映到字典空間,然後利用得到的分類器進行分類 1.建立詞彙(特徵)詞典 以SIFT 128維特徵作為例子。例如現在有1000張訓練圖片,對每一
(一)影象座標:我想和世界座標談談(A) 【計算機視覺學習筆記--雙目視覺幾何框架系列】
玉米竭力用輕鬆具體的描述來講述雙目三維重建中的一些數學問題。希望這樣的方式讓大家以一個輕鬆的心態閱讀玉米的《計算機視覺學習筆記》雙目視覺數學架構系列部落格。這個系列部落格旨在捋順一下已標定的雙目視覺中的數學主線。數學推導是有著幾分枯燥的,但奇妙的計算機視覺世界
計算機視覺論文筆記五:Maximal Linear Embedding for Dimensionality Reduction
版權論文作者所有,本筆記僅用作學術交流,主要是做個筆記。這篇論文寫的很友好,很清楚,你腦子裡出現了什麼疑問,下一句就是答案。而且是工科思維,很多實現細節作者也會提到,整篇論文幾乎就是有不能更詳細註釋的程式碼!!我的鴿,被校友的論文圈粉了。我也要向著這種方向思考,寫作。IEEE
OpenCV計算機視覺學習(1)——影象基本操作(影象視訊讀取,ROI區域擷取,常用cv函式解釋)
1,計算機眼中的影象 我們開啟經典的 Lena圖片,看看計算機是如何看待圖片的: 我們點選圖中的一個小格子,發現計算機會將其分為R,G,B三種通道。每個通道分別由一堆0~256之間的數字組成,那OpenCV如何讀取,處理圖片呢,我們下面詳細學習。 2,影象的載入,顯示和儲存 我們看
OpenCV計算機視覺學習(2)——影象算術運算 & 掩膜mask操作(數值計算,影象融合,邊界填充)
如果需要處理的原圖及程式碼,請移步小編的GitHub地址 傳送門:請點選我 如果點選有誤:https://github.com/LeBron-Jian/ComputerVisionPractice 在OpenCV中我們經常會遇到一個名字:Mask(掩膜)。很多函式都使用到它,那麼這個Mask到底是
OpenCV計算機視覺學習(3)——影象灰度線性變換與非線性變換(對數變換,伽馬變換)
如果需要處理的原圖及程式碼,請移步小編的GitHub地址 傳送門:請點選我 如果點選有誤:https://github.com/LeBron-Jian/ComputerVisionPractice 下面主要學習影象灰度化的知識,結合OpenCV呼叫 cv2.cvtColor()函式實現影象灰度化,
OpenCV計算機視覺學習(4)——影象平滑處理(均值濾波,高斯濾波,中值濾波,雙邊濾波)
如果需要處理的原圖及程式碼,請移步小編的GitHub地址 傳送門:請點選我 如果點選有誤:https://github.com/LeBron-Jian/ComputerVisionPractice “平滑處理”(smoothing)也稱“模糊處理”(bluring),是一項簡單且使用頻率很高的影象
OpenCV計算機視覺學習(5)——形態學處理(腐蝕膨脹,開閉運算,禮帽黑帽,邊緣檢測)
如果需要處理的原圖及程式碼,請移步小編的GitHub地址 傳送門:請點選我 如果點選有誤:https://github.com/LeBron-Jian/ComputerVisionPractice 形態學操作簡單來說,就是改變物體的形狀,下面學習一下,首先本文的目錄如下: 1,定義結構元素 2,
OpenCV計算機視覺學習(7)——影象金字塔(高斯金字塔,拉普拉斯金字塔)
如果需要處理的原圖及程式碼,請移步小編的GitHub地址 傳送門:請點選我 如果點選有誤:https://github.com/LeBron-Jian/ComputerVisionPractice 本節學習影象金字塔,影象金字塔包括高斯金字塔和拉普拉斯金字塔。它是影象中多尺度表達的一種,最主要用於
OpenCV計算機視覺學習(8)——影象輪廓處理(輪廓繪製,輪廓檢索,輪廓填充,輪廓近似)
如果需要處理的原圖及程式碼,請移步小編的GitHub地址 傳送門:請點選我 如果點選有誤:https://github.com/LeBron-Jian/ComputerVisionPractice 1,簡單幾何影象繪製 簡單幾何影象一般包括點,直線,矩陣,圓,橢圓,多邊形等等。 下面學習一下
OpenCV計算機視覺學習(9)——影象直方圖 & 直方圖均衡化
如果需要處理的原圖及程式碼,請移步小編的GitHub地址 傳送門:請點選我 如果點選有誤:https://github.com/LeBron-Jian/ComputerVisionPractice 1,如何提高影象畫素 對曝光過度或者逆光拍攝的圖片可以通過直方圖均衡化的方法用來增強區域性或者整體的
OpenCV計算機視覺學習(10)——影象變換(傅立葉變換,高通濾波,低通濾波)
如果需要處理的原圖及程式碼,請移步小編的GitHub地址 傳送門:請點選我 如果點選有誤:https://github.com/LeBron-Jian/ComputerVisionPractice 在數字影象處理中,有兩個經典的變換被廣泛應用——傅立葉變換和霍夫變化。其中,傅立葉變換主要是將時間域
OpenCV計算機視覺學習(11)——影象空間幾何變換(影象縮放,影象旋轉,影象翻轉,影象平移,仿射變換,映象變換)
如果需要處理的原圖及程式碼,請移步小編的GitHub地址 傳送門:請點選我 如果點選有誤:https://github.com/LeBron-Jian/ComputerVisionPractice 影象的幾何變換是在不改變影象內容的前提下對影象畫素進行空間幾何變換,主要包括了影象的平移變換,縮放,
OpenCV計算機視覺學習(12)——影象量化處理&影象取樣處理(K-Means聚類量化,區域性馬賽克處理)
如果需要處理的原圖及程式碼,請移步小編的GitHub地址 傳送門:請點選我 如果點選有誤:https://github.com/LeBron-Jian/ComputerVisionPractice 準備:影象轉陣列,陣列轉影象 將RGB影象轉換為一維陣列的程式碼如下: # 影象二維畫素轉換為一維
OpenCV計算機視覺學習(13)——影象特徵點檢測(Harris角點檢測,sift演算法)
如果需要處理的原圖及程式碼,請移步小編的GitHub地址 傳送門:請點選我 如果點選有誤:https://github.com/LeBron-Jian/ComputerVisionPractice 前言 特徵點檢測廣泛應用到目標匹配,目標跟蹤,三維重建等應用中,在進行目標建模時會對影象進行目標特徵
【python下使用OpenCV實現計算機視覺讀書筆記2】圖像與字節的變換
ng- == color and pytho avi data- imwrite center import cv2 import numpy import os # Make an array of 120,000 ran
計算機英語學習筆記(五)
引導 benefit begin 基於 body 表現 bool 網絡 nal 序號 單詞 音標 註釋 1 balance · [‘b?l?ns] v.(使)平衡 2 bar · [bɑr] n.欄 3 base