Emil Pettersson
Emil Pettersson

Reputation: 21

What is the inverse of this for loop?

I have a code that shears an image in python, and I do that using forward mapping. However, my assignment also requires me to do backward mapping, i.e. finding the input from the output. My code looks as follows, and my question is: What does the inverse of this for loop look like in code form?

for y in range(height):
   for x in range(50, 450):
        img[int(x * By + y), int(x + y * Bx)] = img[y, x]

height is the height of the image, img is said image. Bx and By are just factors, numbers I choose myself. For clarification, the formula of shearing looks like this in maths:

x' = x + y · Bx

y' = x · By + y

My guess is this, but I get an index out of bounds error:

for y in range(height):
    for x in range(50, 450):
        img[int(x * 1/By - y), int(x - y * 1/Bx)] = img[y, x]

Thanks in advance, I hope you can help me

Upvotes: 0

Views: 366

Answers (1)

Maiki Bodhisattva
Maiki Bodhisattva

Reputation: 218

Your output has different dimensions than the input. You can't use the original ranges for output indexes. I think the easiest option would be to just invert the assignment statement:

for y in range(height):
   for x in range(50, 450):
        img_1[y, x] = img_2[int(x * By + y), int(x + y * Bx)]

Upvotes: 1

Related Questions