代码之家  ›  专栏  ›  技术社区  ›  Ubdus Samad

优化numpy阵列中的元素修改操作

  •  1
  • Ubdus Samad  · 技术社区  · 7 年前

    所以我的代码做了一个非常基本的图像处理,把一个字符串存储到一个图像中。

    因此,数组现在类似于: [ [ [odd_clr_val,odd_clr_val,odd_clr_vlue] ... ] .... ]

    现在我用一个简单的程序把它读回来。

    代码如下所示:

    from PIL import Image
    import numpy as np
    import time
    #if the value of pixel is:
    #Odd = 0 , even = 1
    #We make every element odd
    
    img = Image.open('Desktop/test.jpg')
    
    arr = np.array(img)
    x,y,z  = np.shape(arr)
    count = 0
    initial = time.time()
    
    #This nested loop makes every element odd but is very slow and in need to be optimized
    for i in range(x):
        for j in range(y):
            count += 1
            k = arr[i][j]
            arr[i][j][0] =  k[0] + int(not(k[0]%2)) # adds 1 if k[i] is odd else 0
            arr[i][j][1] =  k[1] + int(not(k[1]%2))
            arr[i][j][2] =  k[2] + int(not(k[2]%2))
    
    print("Time delta: %f"%(time.time() - initial ))
    print("The amount of data you can store in this image is: %d kiBs"%((count*3)/1024))
    #every element of this image is odd now
    
    z = input("Enter the string:")
    
    long_array = []
    for i in z:
        long_array += list(map(int,list(format(ord(i), '#010b')[2:])))
    
    
    #everything is in binary now
    
    counter = 0
    try:
        for i in range(x):
            for j in range(y):
                k = arr[i][j]
    
                arr[i][j][0] = k[0] if not(long_array[counter]) else k[0]+1
                counter += 1
    
                arr[i][j][1] = k[1] if not(long_array[counter]) else k[1]+1
                counter += 1
    
                arr[i][j][2] = k[2] if not(long_array[counter]) else k[2]+1
                counter += 1
    except IndexError:
        print("Done")
    except:
        print("An unidentified error occured!")
    
    image = Image.fromarray(arr)
    
    image.show()
    
    image.save("secret.png")
    

    我的问题 我无法优化代码的上循环,因为它需要16秒才能完成(使用800x600x3图片矩阵)。另外,我的代码的下循环比上循环快得多。

    那么,有没有一种方法来优化我的上循环使用一些numpy魔术?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Paul Panzer    7 年前

    你可以用 bitwise arithmetic

    arr |= 1
    

    嵌入位字符串:

    arr.ravel()[:len(long_array)] += np.array(long_array, arr.dtype)
    

    顺便说一句,添加一个可以创建由于溢出明显的像素变化。例如,亮红色(255,1,1)将变为黑色(0,2,2)。你可以通过减去一来避免这种情况。