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

Python 优化numpy阵列中的元素修改操作,python,python-3.x,numpy,Python,Python 3.x,Numpy,因此,我的代码执行一种非常基本的图像处理形式,并将字符串存储到图像中 它主要通过将图像转换成一个numpy数组(x*y*3),然后首先使每个数字元素为奇数来实现 因此,阵列现在类似于: 现在,我要做的是将要存储的文本转换为二进制数据,并根据需要修改数组中的任意多个元素,使其具有奇偶校验以表示零,偶数表示1 现在我用一个简单的程序把它读回 代码如下所示: from PIL import Image import numpy as np import time #if the value of p

因此,我的代码执行一种非常基本的图像处理形式,并将字符串存储到图像中

它主要通过将图像转换成一个numpy数组(x*y*3),然后首先使每个数字元素为奇数来实现

因此,阵列现在类似于:

现在,我要做的是将要存储的文本转换为二进制数据,并根据需要修改数组中的任意多个元素,使其具有奇偶校验以表示零,偶数表示1

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

代码如下所示:

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魔术优化我的上循环?

您可以使用。将所有像素设为奇数可以在一行中完成:

arr |= 1
嵌入您的位字符串:

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

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

太棒了!!非常感谢,你能不能给我一些链接来解释(如果可能的话)你对arr所做的使它们变得奇怪的魔力。@UbdusSamad添加了一个到文档的链接。一定要看例子;他们被很好地解释了。