2017-07-24 170 views
1

我試圖使用Pycaffe 來分類GoogleNet中的一些圖像一切都處於其默認狀態,deploy.prototxt以及預訓練的模型。但是,當我想運行代碼時,出現以下錯誤:ValueError:無法從形狀(1,3,256,256)廣播輸入數組形成(1,3,224,224),同時減去caffe中的均值文件

ValueError: could not broadcast input array from shape (1,3,256,256) into shape (1,3,224,224) 

發生在我想從平均文件中減去圖像時發生的情況! 這是我使用的代碼:

# Extract mean from the mean image file 
    mean_blobproto_new = caffe.proto.caffe_pb2.BlobProto() 
    f = open(args.mean, 'rb') 
    mean_blobproto_new.ParseFromString(f.read()) 
    mean_image = caffe.io.blobproto_to_array(mean_blobproto_new) 

for i, image, label in reader: 
    image_caffe = image.reshape(1, *image.shape) 

    out = net.forward(data=np.asarray([ image_caffe ])- mean_image) 
    plabel = int(out['pred'][0].argmax(axis=0)) 

,這是deploy.prototxt文件,(該網絡進行訓練的256x256圖像裁剪爲224x224就像GoogleNet和GoogleNet意味着文件是用來爲好):https://pastebin.com/2QEtEeHW

這裏有什麼問題?
不應該Caffe首先減去圖像,然後裁剪它,所以這個錯誤不會發生? 我該怎麼辦?

+0

不是googlenet減去每個通道的平均值(3矢量,而不是「平均圖像」)? – Shai

+0

我使用了這個分支的文件:https://github.com/mrgloom/kaggle-dogs-vs-cats-solution ,並從他們的分支中獲得了所有文件+ meanfile! 上一個鏈接引用並表示他們從他們的googlenet實現中獲得的caffe分支,儘管如此,每個頻道的平均值也是如此。 – Breeze

+1

它不。你可以看看我如何做到這一點https://stackoverflow.com/questions/44119176/caffe-model-gives-same-output-for-every-image。 – Harjatin

回答

0

爲了這個工作我有3個選擇!

  1. 使用transformer.preprocess()方法,這是非常緩慢的!
  2. 將圖像和平均文件大小調整爲裁剪大小,然後使用平均文件
  3. 中心裁剪就像Caffe一樣,繼續進行!

這裏是我爲此寫的代碼,請注意我正在讀取一個lmdb數據庫,所以樣本已經轉置和通道交換了! :

ims=[]    
for x in range(len(batch)): 
    img = batch[x][1] 
    #img has c,h,w shape! its already gone through transpose and channel swap when it was being saved into lmdb! 
    #method I: crop the both the image and mean file 
    #ims.append(img[:,0:224,0:224] - mean_image[0][:,0:224,0:224]) 
    #Method II : resize the image to the desired size(crop size) 
    #img = caffe.io.resize_image(img.transpose(2,1,0), (224, 224)) 
    #Method III : use center crop just like caffe does in test time 
    #center crop 
    c,h,w = img.shape 
    startx = h//2 - cropx//2 
    starty = w//2 - cropy//2 
    img = img[:, startx:startx + cropx, starty:starty + cropy]     
    #transpose the image so we can subtract from mean, and in the meanwhile, change it to float! 
    img = np.array(img.transpose(2,1,0),dtype=np.float32) 
    img -= mean_image[0].mean(1).mean(1) 
    #transpose back to the original state 
    img = img.transpose(2,1,0) 
    ims.append(img)   

net1.blobs['data'].data[...] = ims[:] 
相關問題