Reputation: 1508
I am coding a method in python that by means of OpenCV, it processes some images from a camera and compares pixel by pixel that image to some parameters and, depending to these parameters, puts that pixel to zero. The piece of code which does that is the following:
while True:
ret, frame = cap.read() # retrieve image from the camera
for row in range(rows):
for col in range(cols):
b1 = (frame[row][col][:] < Nsigma2[row][col][:]).all();
b2 = (frame[row][col][:] > Psigma2[row][col][:]).all();
if not b1 and not b2:
frame[row][col][:] = [0,0,0];
cv.imshow('frame',frame) #show the processed image
if cv.waitKey(15) & 0xFF == ord('q'):
break
Besides correctness or not of the algorithm itself, is this the correct way to traverse and access numpy
matrices? But this is extremely slow. I think that the slowest direction is the third component of the matrices, which I access in the inner loop, but I don't find any better way to do that. I am not very used to Python so, it is normal and expectable such an slow performance?
Upvotes: 4
Views: 153
Reputation: 67427
What's slowing you down is most likely looping, which is not one of Python strengths. I doubt memory access is relevant on top of that. You can vectorize your processing, and get it all done at once, letting numpy internally loop over the values. This three lines:
b1 = np.all(frame < NSigma2, axis=-1)
b2 = np.all(frame > PSigma2, axis=-1)
frame[~(b1 | b2)] = 0
could replace your 2 nested loops. You will not be able to see the image processed pixel by pixel, as you seem to be doing now, though.
Upvotes: 2