Jython (JES) - 90 degree rotation function

感情迁移 提交于 2019-12-11 11:52:05

问题


I need to write a function spin(pic,x) where it will take a picture and rotate it 90 degrees counter clockwise X amount of times. I have just the 90 degree clockwise rotation in a function:

def rotate(pic):
    width = getWidth(pic)
    height = getHeight(pic)
    new = makeEmptyPicture(height,width)
    tarX = 0
    for x in range(0,width):
        tarY = 0
        for y in range(0,height):
            p = getPixel(pic,x,y)
            color = getColor(p)
            setColor(getPixel(new,tarY,width-tarX-1),color)
            tarY = tarY + 1
        tarX = tarX +1
    show(new)
    return new

.. but I have no idea how I would go about writing a function on rotating it X amount of times. Anyone know how I can do this?


回答1:


You could call rotate() X amount of times:

def spin(pic, x):
    new_pic = duplicatePicture(pic)
    for i in range(x):
         new_pic = rotate(new_pic)
    return new_pic


a_file = pickAFile()
a_pic = makePicture(a_file)
show(spin(a_pic, 3))

But this is clearly not the most optimized way because you'll compute X images instead of the one you are interested in. I suggest you try a basic switch...case approach first (even if this statement doesn't exists in Python ;):

xx = (x % 4)     # Just in case you want (x=7) to rotate 3 times...

if (xx == 1):
    new = makeEmptyPicture(height,width)
    tarX = 0
    for x in range(0,width):
        tarY = 0
        for y in range(0,height):
            p = getPixel(pic,x,y)
            color = getColor(p)
            setColor(getPixel(new,tarY,width-tarX-1),color)
            tarY = tarY + 1
        tarX = tarX +1
    return new
elif (xx == 2):
    new = makeEmptyPicture(height,width)
    # Do it yourself...
    return new
elif (xx == 3):
    new = makeEmptyPicture(height,width)
    # Do it yourself...
    return new
else:
    return pic

Then, may be you'll be able to see a way to merge those cases into a single (but more complicated) double for loop... Have fun...



来源:https://stackoverflow.com/questions/19592022/jython-jes-90-degree-rotation-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!