2014-05-23 60 views
5

我在這裏使用了選擇性搜索:http://koen.me/research/selectivesearch/ 這給出了可能的對象所在的區域。我想要做一些處理並只保留一些區域,然後刪除重複的邊界框以獲得最終整齊的邊界框集合。爲了丟棄不需要/重複的邊界框區域,我使用了opencv的grouprectangles函數進行修剪。python opencv TypeError:輸出數組的佈局與cv不兼容:: Mat

有一次,我從上面的鏈接「選擇性搜索算法」得到Matlab的有趣的地區,我保存在.mat文件中的結果,然後在Python程序檢索它們,就像這樣:

import scipy.io as sio 
inboxes = sio.loadmat('C:\\PATH_TO_MATFILE.mat') 
candidates = np.array(inboxes['boxes']) 
# candidates is 4 x N array with each row describing a bounding box like this: 
# [rowBegin colBegin rowEnd colEnd] 
# Now I will process the candidates and retain only those regions that are interesting 
found = [] # This is the list in which I will retain what's interesting 
for win in candidates: 
    # doing some processing here, and if some condition is met, then retain it: 
    found.append(win) 

# Now I want to store only the interesting regions, stored in 'found', 
# and prune unnecessary bounding boxes 

boxes = cv2.groupRectangles(found, 1, 2) # But I get an error here 

錯誤是:

boxes = cv2.groupRectangles(found, 1, 2) 
TypeError: Layout of the output array rectList is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels) 

怎麼了? 我在另一段代碼中做了非常類似的事情,沒有發現任何錯誤。這是無差錯的代碼:

inboxes = sio.loadmat('C:\\PATH_TO_MY_FILE\\boxes.mat') 
boxes = np.array(inboxes['boxes']) 
pruned_boxes = cv2.groupRectangles(boxes.tolist(), 100, 300) 

我可以看到的唯一區別是,boxes是numpy的陣列,其餘然後轉換爲一個列表。但在我有問題的代碼中,found已經是一個列表。

回答

4

的解決方案是found轉換到一個numpy的數組,然後把它人們重新進入名單:

found = np.array(found) 
boxes = cv2.groupRectangles(found.tolist(), 1, 2) 
21

自己的解決方案是簡單地問原數組的副本...(神&加里·布拉德斯基知道爲什麼...)

im = dbimg[i] 
bb = boxes[i] 
m = im.transpose((1, 2, 0)).astype(np.uint8).copy() 
pt1 = (bb[0],bb[1]) 
pt2 = (bb[0]+bb[2],bb[1]+bb[3]) 
cv2.rectangle(m,pt1,pt2,(0,255,0),2) 
+3

簡單地複製數組爲我工作的一個類似的錯誤,以及。 –

+0

可以證實這一點,似乎沒有明顯的區別,壽。 – Pwnna

+0

此解決方案適用於由cv2.ellipse()函數產生的類似錯誤 – DanGoodrick

0

opencv的似乎是問題的繪製與NumPy有數據類型np.int64,這是通過諸如np.array和返回的默認數據類型數組:

>>> canvas = np.full((256, 256, 3), 255) 
>>> canvas 
array([[255, 255, 255], 
     [255, 255, 255], 
     [255, 255, 255]]) 
>>> canvas.dtype 
dtype('int64') 
>>> cv2.rectangle(canvas, (0, 0), (2, 2), (0, 0, 0)) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: Layout of the output array img is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels) 

的解決方案是將數組轉換爲np.int32第一:

>>> cv2.rectangle(canvas.astype(np.int32), (0, 0), (2, 2), (0, 0, 0)) 
array([[ 0, 0, 0], 
     [ 0, 255, 0], 
     [ 0, 0, 0]], dtype=int32)