Reputation: 11
I'm using OpenCV for a computer vision project, however, I need to do a pixel by pixel operation on the image which means accessing every pixel in a 640x480 image and changing it's HSV values. The image is made up of a 3D array X, Y and HSV Values, so a pixel at 130, 230 may have a HSV value of [12, 26, 18] or represented in the image: (130, 230, (12, 26, 18))
I need to perform an operation which allows me to add an amount X into the V value (element index 2) of the HSV values: (130, 230, (12, 26, 18))
I can do this using two loops:
for x in range(image.width):
for y in range(image.height/2):
initcolor = cv.Get2D(image, y, x)
initcolor2 = [0, 0, 10, 0]
summed = [sum(pair) for pair in zip(initcolor, initcolor2)]
cv.Set2D(image, y, x, summed)
But this is awfully slow and for some reason takes around 20 seconds to complete the operation over the entire image.
Is there a simpler, more faster way of achieving this?
Upvotes: 1
Views: 387
Reputation: 15192
The first and easiest thing you should do is to check to see if OpenCV can take numpy arrays as arguments. Numpy is built on fast C algorithms that can handle large loops over data structures in what are called "vectorized" operations. Each loop in Python incurs a very large overhead.
Another alternative might be to put this block of code in Cython, which can handle tight loops like this far better.
Upvotes: 1
Reputation: 5713
If I were doing computer vision in Python, I would definitely use Numpy and get my arrays into numpy format as soon as possible. I suspect you might want numpy.asarray() to convert from PIL to array.
Upvotes: 0