The fastest way to iterate over all the pixels of an image in python

I already read the image as an array:

import numpy as np
from scipy import misc
face1=misc.imread('face1.jpg')
Dimensions

face1: (288, 352, 3)

I need to iterate over each pixel and fill a column yin the training set, I used the following approach:

Y_training = np.zeros([1,1],dtype=np.uint8)

for i in range(0, face1.shape[0]): # We go over rows number 
    for j in range(0, face1.shape[1]): # we go over columns number
        if np.array_equiv(face1[i,j],[255,255,255]):
           Y_training=np.vstack(([0], Y_training))#0 if blank
        else:
           Y_training=np.vstack(([1], Y_training))

b = len(Y_training)-1
Y_training = Y_training[:b]
np.shape(Y_training)`

Wall time: 2.57 s

As I need to do the above process for about 2000 images, is there any faster approach where we could reduce the runtime to milliseconds or seconds

+4
source share
1 answer

broadcasting : [255, 255, 255] ALL .all(axis=-1) , , int dtype. , .

, -

(~((face1 == [255,255,255]).all(-1).ravel())).astype(int)

, -

1-(face1 == [255,255,255]).all(-1).ravel()
+7

Source: https://habr.com/ru/post/1682418/


All Articles