Drawing pixel to pixel

I'm drawing a pixel by pixel image with the following code:

coord = np.where(np.all(imagen == (0, 0, 0), axis=-1))
cv2.imshow('imagen', imagen)

a = coord[0]
b = coord[1]

for x,y in zip(a,b):
rectObs.append(pygame.Rect((y,x),(1,1)))

for rect in rectObs:
pygame.draw.rect(screen, black, rect,20)


This code detects all the black pixels of an image and draws them in another window with the same coordinate. The problem is that there are so many black pixels that the processing is very very slow.

Any idea to improve performance or to graph in a more optimal (other than pixel by pixel)?

1 Answer

There're several places you could optimize your code.

First, though, I suggest profiling your current code, so you'd know which are your bottlenecks, and where you should concentrate your efforts.

The detection of the black pixels is a CPU intensive process, which means it could benefit from the techniques mentioned above.

The copying of the black pixels, on the other hands, is an I/O intensive process, which you can optimize in two ways:

1. Instead of copying the pixels as they are discovered to the other window, build a data structure - in memory - that represents the data for this other window, and then do the copy as one memory image copying, instead of a set of single pixels. Or,
2. Break the pixel copying into several threads/processes that will work in parallel. Note that this may not be possible, depending on your algorithm.