在PyTorch中測試DataLoader讀取后的圖像,對圖像畫框cv2.rectangle時報錯:
TypeError: Layout of the output array img is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)
網上搜索良久無果,維度和數值也都檢查無誤,后在Stack Overflow上發現解決方案:
img = (img.numpy().transpose((1, 2, 0))*255).astype(np.uint8)
img = img.copy()
這里使用copy后,報錯問題解決,但是Stack Overflow上也沒有人知道原因所在,
I faced the same problem with numpy 1.11.2 and opencv 3.3.0. Not sure why, but this did the job for me. Before using cv2.rectangle, add the line below:
python image = image.copy() # Change
先mark上,后面尋找詳細原因,不過根據報錯類型來看,直覺上是因為這個版本的numpy和opencv在做各種轉換的時候遺留下了MAT內部數據結構的一些坑,導致了在操作rectangle時候剛好用到了MAT中的某個屬性,不兼容后報錯,后面有時間可以再看看cv的python版源碼找找原因。