根据这些条件增减一个值

2024-06-23 20:03:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个beb形状数组(3,8),它表示三行8位(1或0),一个copiv形状数组(3,8,2),它基本上表示图像的前8个像素,只有RGB的绿色和蓝色值。我有一个掩码,形状为(3,8)的布尔数组。如果绿色和蓝色值具有不同的奇偶校验,则掩码数组的值为True;如果它们具有相同的奇偶校验,则掩码数组的值为False。下面是它们的样子(分别是beb、mask和copiv):

beb = np.array([[0,0,0,0,0,0,1,0],[0,1,1,0,0,0,0,1],[0,1,1,0,1,0,0,0]]) #shape (3,8)


mask = np.array([[True, False, True, True, True, False, False, True],
                 [True, False, True, True, True, False, False, True],
                 [True, False, True, True, True, False, False, True]]) #shape (3,8)


copiv = np.array([
[[138, 207],[133, 201],[133, 202],[134, 203],[133, 202],[133, 203],[134, 206],[133, 204]],
[[139, 208],[133, 201],[133, 202],[134, 203],[133, 202],[133, 203],[134, 206],[134, 205]],
[[139, 208],[133, 201],[133, 202],[135, 204],[133, 202],[133, 203],[135, 207], [134, 205]]]) # shape (3,8,2)

我想要增加或减少copiv数组的第二个值(蓝色值是第二个值,第一个值是绿色值),具体取决于这些条件:

-当beb数组的位=0且绿色和蓝色值具有相同的奇偶校验(例如[1 3]或[6 8],意味着在copiv数组中它将返回False,bc相同的奇偶校验)时,我们不做任何操作

-当beb数组的位再次为0时,但这一次,绿色和蓝色的奇偶校验不同(例如[4 3],意味着在copiv数组中它将返回True),那么在这种情况下:如果蓝色是偶数值,我们递增蓝色,如果蓝色是奇数值,我们递减蓝色

-当beb的位现在为1时,如果copiv数组中的绿色和蓝色为真:我们什么也不做

-当beb的位为1时,绿色和蓝色返回False,因此它们有一个不同的奇偶校验:如果蓝色是偶数,我们增加它,如果是奇数,我们减少它

这是我的代码,但减量不起作用:

print("COPIV BEOFRE : \n", copiv)


for i in range(beb.shape[0]):
        for j in range(beb.shape[1]):

            if (beb[i][j] == 0):
                for y in range(mask.shape[0]):
                    for z in range(mask.shape[1]):
                        for x in range(copiv.shape[0]):
                                for w in range(copiv.shape[1]):
                                    if (mask[y,z] == True and copiv[x,w,1:3] % 2 == 0):                
                                        copiv[x,w,1:3] += 1                                
                                    elif (copiv[x,w,1:3] % 2 != 0):
                                        copiv[x,w,1:3] -= 1                                                                                       

            elif (beb[i][j] == 1):
                if(mask[y,z] == False and copiv[x,w,1:3] % 2 == 0):
                    copiv[x,w,1:3] += 1                                #increment B
                elif (copiv[x,w,1:3] % 2 != 0):
                    copiv[x,w,1:3] -= 1           #decrement B


print("\nCOPIV AFTER : \n", copiv)

Tags: infalsetrueforrangemask数组蓝色
2条回答

你可以实现以下目标

# first, generate boolean condition array.
cond1 = beb==1  # shape (3,8)

# then, new condition by logical operation
cond2 = np.logical_and(cond1, mask)

# finally, filter indices using boolean array, and assign value
copv[cond2,0] += 100    # 0 index for blue

那么:

copiv[...,1] ^= beb^mask

解释者:

可以检查操作“偶数递增,奇数递减”是否可以重新表述为“翻转最低位”。这是表达式中的^=位-如果r.h.s.是1,如果是0^=什么也不做

我们还可以检查r.h.s.对于所考虑的所有4种情况是否采用正确的值

相关问题 更多 >

    热门问题