AndantinoAllegretto
AndantinoAllegretto

Reputation: 13

How to speed up this code with Numpy?

Currently I am using the following code to convert all non-black pixels to white:

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

How can I speed it up?

Upvotes: 1

Views: 56

Answers (2)

Kennet Celeste
Kennet Celeste

Reputation: 4771

How about using PIL and make the function like this:

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

Test code:

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()

result :

enter image description here enter image description here

And btw, in case you needed the numpy array of the PIL image object, you can easily get it using:

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

Upvotes: 0

Amadan
Amadan

Reputation: 198526

All elements that are not 0 should change to 255:

a[a != 0] = 255

Upvotes: 2

Related Questions