0

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

  • You should catch the error and print the values that generates an index out of bounds. This should help you understanding the problem in your calculus. – Maxime Chéramy Nov 16 '18 at 13:21
  • Seconding @MaximeChéramy. Here's an idea as to what might be happening though: your error implies that `[int(x * 1/By - y), int(x - y * 1/Bx)]` isn't in `img`. You might have to reconsider the ranges you're choosing when doing the inverse shear. Perhaps the image you are unshearing doesn't have the same dimensions as the image you sheared. – Battery_Al Nov 16 '18 at 13:27
  • You might be a victim of [integer division rounding](https://stackoverflow.com/questions/183853/what-is-the-difference-between-and-when-used-for-division). Maybe try `1.0 / By` and `1.0 / Bx`. – Peter Wood Nov 16 '18 at 13:30

1 Answers1

1

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)]