如何使用 Numpy 加速这段代码?

How to speed up this code with Numpy?

目前我正在使用以下代码将所有非黑色像素转换为白色:

def convert(self, img):
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            if img.item(i, j) != 0:
                img.itemset((i, j), 255)
    return img

我怎样才能加快速度?

所有不为 0 的元素都应更改为 255:

a[a != 0] = 255

如何使用 PIL 并制作如下函数:

def convert (self,image):
    return image.convert('1') 

测试代码:

from PIL import Image
import matplotlib.pyplot as plt

def convert (image):
    return image.convert('1')

img = Image.open('./test.png')
plt.figure(); plt.imshow(img)
BW = convert(img)
plt.figure(); plt.imshow(BW)
plt.show()

结果:

顺便说一句,如果您需要 PIL 图像对象的 numpy 数组,您可以使用以下方法轻松获取它:

matrix_of_img = numpy.asarray(img.convert('L'))