Efficiently set a list of pixels value in python?

Viewed 45

How can i set a list of pixels efficiently using python.

For example if i have:

import numpy as np

img = np.zeros((700, 200, 3), dtype=np.uint8)

l = [[300, 101], [200, 102], [150, 103], [300, 104], [88, 105], [66, 106], [666, 107]]

i just want to set pixels with l coordinates to black color.

I know i can do something like this:

for p in l:
    img[p[0], p[1]] = (0, 0, 0)

I wonder if there is something more efficient.

1 Answers

Your example is confusing (at least for me :D ) but I think this might be more "efficient"

import cv2
import numpy as np
#an array:

img=255*np.ones((700,700,3),dtype=np.uint8)

list = [[444, 101], [200, 102], [150, 103], [300, 104], [88, 105], [66, 106], [666, 107]]

#with for loop

def set_pixels(img, list):
    for i in range(len(list)):
        x = list[i][0]
        y = list[i][1]
        img[x, y] = [0, 0, 0]

without for loop (Alex Alex mentioned)

def set_pixels_2(img, list):
    list = np.array(list)
    img[list[:,0], list[:,1]] = [0, 0, 0]
set_pixels(img, list)
set_pixels2(img, list)
cv2.imshow('image', img)
cv2.waitKey(0)
Related