Iterate over Two Arrays and Modify Values in Python Using Numpy

Question:

The following code has been written in C-style.

imgarr = np.frombuffer(imgbytes, dtype=np.uint8)
for j in range(0, 768, 1):
    for i in range(0, 1024, 1):
        coldmap[i + j * 1024] = coldmap[i + j * 1024] + (imgbytes[i + j * 1024] - coldmap[i + j * 1024] / (index + 1))
        index += 1

As you can expect, it is too darn slow. I’ve noticed there is a method called nditer in Numpy I can utilize. So I’ve come up with this:

for x in np.nditer([coldmap, imgarr], op_flags=['readwrite']):
    x[0] = x[0] + ((x[1] - x[0]) / (index + 1))
    index += 1

The problem, however, is x’s type is tuple and cannot be modified. I’m not even sure if this is the right approach even if I was able to modify the value. Please help me convert the routine written in C-style to a piece of Python code with a decent speed. Thank you.

Asked By: Tabasco

||

Answers:

Answering my own quesetion, this is from Mechanic Pig’s comment.

One line solution: coldmap += imgbytes – coldmap / np.arange(1, 768 * 1024 + 1)

Answered By: Tabasco
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.