Bagus Prasetyo W - 1 year ago 209
Python Question

# only rotate part of image python

Can someone tell me how to rotate only part of an image like this:

How to find coordinate / center of this image:

i can rotate all pict using this

``````from PIL import Image

def rotate_image():
img = Image.open("nime1.png")

img.rotate(45).save("plus45.png")
img.rotate(-45).save("minus45.png")

img.rotate(90).save("90.png")
img.transpose(Image.ROTATE_90).save("90_trans.png")

img.rotate(180).save("180.png")

if __name__ == '__main__':
rotate_image()
``````

You can crop an area of the picture as a new variable. In this case, I cropped a 120x120 pixel box out of the original image. It is rotated by 90 and then pasted back on the original.

``````from PIL import Image

img = Image.open('./image.jpg')
sub_image = img.crop(box=(200,0,320,120)).rotate(90)
img.paste(sub_image, box=(200,0))
``````

So I thought about this a bit more and crafted a function that applies a circular mask to the cropped image before rotations. This allows an arbitrary angle without weird effects.

``````def circle_rotate(image, x, y, radius, degree):
img_arr = numpy.asarray(image)
crop = image.crop(box=box)
crop_arr = numpy.asarray(crop)
for i in range(crop_arr.shape[0]):
for j in range(crop_arr.shape[1]):
# create the new circular image
sub_img_arr = numpy.empty(crop_arr.shape ,dtype='uint8')
sub_img_arr[:,:,:3] = crop_arr[:,:,:3]