Reputation: 31
def rotate_picture_90_left(img: Image) -> Image:
"""Return a NEW picture that is the given Image img rotated 90 degrees
to the left.
Hints:
- create a new blank image that has reverse width and height
- reverse the coordinates of each pixel in the original picture, img,
and put it into the new picture
"""
img_width, img_height = img.size
pixels = img.load() # create the pixel map
rotated_img = Image.new('RGB', (img_height, img_width))
pixelz = rotated_img.load()
for i in range(img_width):
for j in range(img_height):
pixelz[i, j] = pixels[i, j]
return rotated_img
I believe my code does not seem to work because of the new image I have created and the reverse width, length and reversing the coordinates in the original picture. How can I fix my code to rotate the image correctly?
Upvotes: 3
Views: 2112
Reputation: 8260
You need to consider following logic when converting coordinates:
y
turning to x
x
turning to y
but moving from end to startHere is the code:
from PIL import Image
def rotate_picture_90_left(img: Image) -> Image:
w, h = img.size
pixels = img.load()
img_new = Image.new('RGB', (h, w))
pixels_new = img_new.load()
for y in range(h):
for x in range(w):
pixels_new[y, w-x-1] = pixels[x, y]
return img_new
Example:
Upvotes: 1