2016-03-03 72 views
0

在我的代碼中,我試圖導入一個灰度圖像(二維數組),然後根據我提出的經驗公式求解光密度(OD)。光密度與灰度值有關,其中f是陣列中每個元素的灰度值。然後,我將它轉換成RGB圖像。如果語句循環遍歷Python中的單個元素

我的問題是我想運行圖像數組中的每個單獨的元素到if語句中。儘管如此,它並沒有進入聲明。我想要做的是根據光密度滿足什麼條件來增加R,G和B中每個單獨元素或像素值的強度。假設它的OD值落在b和c之間,它會將[128,0,0]添加到滿足該條件的每個元素。

t = Image.open("IMG_1.jpg").convert('L') #grayscale image 
f = array(t) #Convert test image into an array 

OD = 0.51*((f-22.08)/(176.09-f))**(1./-1.519) #Empirical Rodbard formula 
OD[np.isnan(OD)] = 0 

def to_rgb5(im): 
    OD.resize((OD.shape[0], OD.shape[1], 1)) 
    return np.repeat(OD.astype(np.uint8), 3, 2) 

cmap = plt.get_cmap('jet') 

rgba_img = cmap(OD) 
rgb_img = np.delete(rgba_img, 3, 2) 

a = 0.08 
b = 0.11 
c = 0.15 

if np.all(OD < a): 
    background_noise = rgb_img 
    if np.all(OD < b): 
     small = rgb_img + [128, 0, 0] 
    elif np.all(OD >= c): 
     large = rgb_img + [0, 0, 128] 


Red = f + small 
Green = f 
Blue = f + large 
+2

請問你的代碼拋出錯誤建議np.where?製表看起來不對,':'缺少 – Stuart

+0

對不起,我失去了應對它。唯一發生的是它說「NameError:name'small'沒有定義」 –

+0

懷疑它。 'else np.all(OD> = C)'不能工作。 –

回答

0

我能得到它的工作使用@Stuart

t = Image.open("IMG_1.jpg").convert('L') #grayscale image 
f = array(t) #Convert test image into an array 

OD = 0.51*((f-22.08)/(176.09-f))**(1./-1.519) #Empirical Rodbard formula 
OD[np.isnan(OD)] = 0 

thB = 0.02 
ththin = 0.11 
ththick = 0.15 

GSb = 162 
GSthin = 150 
GSthick = 145 

if np.where(OD < ththin): 
    thresholded = threshold(f, GSthin, GSb) 
def to_rgb1(thresholded): 
    thresholded.resize((thresholded.shape[0], thresholded.shape[1], 1)) 
    return np.repeat(thresholded.astype(np.uint8), 3, 2)  
cmap = plt.get_cmap('jet') 
rgba_img1 = cmap(thresholded) 
rgb_img1 = np.delete(rgba_img1, 3, 2) 
view = rgb_img1[:, :, 2] 
view[view < 0.1] += 128 
thin = rgb_img1 

if np.where(OD > ththick): 
    thresholded2 = threshold(f, threshmax = GSthick) 
def to_rgb2(thresholded2): 
    thresholded2.resize((thresholded2.shape[0], thresholded2.shape[1], 1)) 
    return np.repeat(thresholded2.astype(np.uint8), 3, 2)  
cmap = plt.get_cmap('jet') 
rgba_img2 = cmap(thresholded2) 
rgb_img2 = np.delete(rgba_img2, 3, 2) 
view2 = rgb_img2[:, :, 0] 
view2[view2 > 0] += 128 
thick = rgb_img2 
+0

您確定這可行嗎?我不認爲這是'where'的正確用法。我認爲你需要類似'small = np.where(OD Stuart

+0

當我這樣做時出現此錯誤ValueError:操作數無法一起廣播與形狀(1080,1920)(2,)' –

+0

是的,你需要檢查數組被添加在一起是相同的形狀。這只是'np.where'應該如何工作的一個例子。 – Stuart