2015-07-21 115 views
1

當我嘗試對jpeg matlab圖像的文件夾進行平均時,我所得到的全部都是空白圖像。我已經完成了一百萬次我的代碼,並且我不知道我在哪裏出錯 。 (我也知道我硬編碼的一些數字,但只是因爲我想它需要一個特定的文件夾,我仔細檢查過那些上百萬次,他們是對的。)在matlab中對圖像進行平均的問題

  %takes all the images in a folder and averages their values 
    %opens folder 
    function avg_image = average_images() 
    folder_name = uigetdir; 
    folder_directory = dir(folder_name); 
    filename = folder_directory(3).name; 
    len = length(folder_directory); 
    org_image = imread(filename); 
    sum_image = org_image; 
    %adds files together 
    for i = 4:len 
     filename = folder_directory(i).name; 
    org_image = imread(filename); 
    sum_image = sum_image + org_image; 
    end 
    %calculates average 
    avg_image = sum_image/(len-2); 
    %saves average as a fits file and displays it 
    imwrite(avg_image, 'averagefile.jpg'); 
    read_image = imread('averagefile.jpg'); 
    imshow(read_image) 
    end 

回答

1

的問題你的代碼是你正在用JPG格式讀取uint8(默認),然後用圖像作爲uint8(0-255整數)的矩陣進行數學運算。正如您在org_image中讀取的,在for循環的上面和內部,將結果轉換爲雙精度:org_image = double(imread(filename))。平均完成後,您需要將其恢復,avg_image = uint8(sum_image/(len-2))

當你使用uint8進行數學運算時,由於小數點被截斷,所以部分是混亂的。當雙方都是雙打時,4除以8會得到0.5。當兩者都是整數時,您得到0.