if语句循环遍历Python中的数组中的各个元素

时间:2016-03-03 20:08:53

标签: python arrays if-statement rgb

在我的代码中,我试图导入灰度图像(2D阵列),然后根据我提出的经验公式求解光密度(OD)。光密度与灰度值有关系,其中OD = 0.51*((f-22.08)/(176.09-f))**(1./-1.519)其中f是阵列中每个元素的灰度值。然后,我将其转换为RGB图像。

我的问题是我试图将图像数组的每个单独元素运行到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

1 个答案:

答案 0 :(得分:0)

我能够使用@Stuart

建议的np.where来使其工作
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