OPEN CV - Change Pixel Coordinates
<p>AS the title suggests I have an image, whose pixel coordinates I want to change using a mathematical function. So far, I have the following code which works but is very time consuming because of the nested loop. Do you have any suggestions to make it faster? To be quantitative, it takes about 2-2.5 minutes to complete the process on a 12MPixel image.</p>

<pre><code>imgcor = np.zeros(img.shape, dtype=img.dtype)
                for f in range(rowc):
                    for k in range(colc):
                        offX = k + (f*b*c*(math.sin(math.radians(a))))
                        offY = f + (f*b*d*(math.cos(math.radians(a))))
                        imgcor[f, k] = img[int(offY)%rowc, int(offX)%colc]
</code></pre>

<p>P.S. I am using opencv 2.4.13 and python 2.7</p>

<p>There may be a way to get numpy to do some vectorized work for you, but one easy speedup is to not re-calculate some of the values every time you loop (I'm assuming a,b,c, and d are not changing in the loop). I'm curious what the speedup would be, can you report back?</p>

<pre><code>imgcor = np.zeros(img.shape, dtype=img.dtype)
offX_precalc = b*c*(math.sin(math.radians(a)))
offY_precalc = b*d*(math.cos(math.radians(a)))
for f in range(rowc):
    for k in range(colc):
        offX = k + (f*offX_precalc)
        offY = f + (f*offY_precalc)
        imgcor[f, k] = img[int(offY)%rowc, int(offX)%colc]
</code></pre>

<p>ok since the above was too slow, I added a bit of vectorization and I'm curious if it's faster:</p>

<pre><code>imgcor = np.zeros(img.shape, dtype=img.dtype)
off_base = b*(math.sin(math.radians(a)))
offX_precalc = off_base*c
offY_precalc = off_base*d+1

for f in range(rowc):
    offY = int(f*offY_precalc)%rowc
    offXs = [int(k + (f*offX_precalc))%colc for k in range(colc)]
    imgcor[f,:] = img[offY, offXs]
</code></pre>

python python-2.7 opencv image-processing transform