Bagus Prasetyo W Bagus Prasetyo W - 8 months ago 52
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 ="nime1.png")




if __name__ == '__main__':


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.jpg')
sub_image = img.crop(box=(200,0,320,120)).rotate(90)
img.paste(sub_image, box=(200,0))

enter image description here

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)
    box = (x-radius, y-radius, x+radius+1, y+radius+1)
    crop = image.crop(box=box)
    crop_arr = numpy.asarray(crop)
    # build the cirle mask
    mask = numpy.zeros((2*radius+1, 2*radius+1))
    for i in range(crop_arr.shape[0]):
        for j in range(crop_arr.shape[1]):
            if (i-radius)**2 + (j-radius)**2 <= radius**2:
                mask[i,j] = 1
    # create the new circular image
    sub_img_arr = numpy.empty(crop_arr.shape ,dtype='uint8')
    sub_img_arr[:,:,:3] = crop_arr[:,:,:3]
    sub_img_arr[:,:,3] = mask*255
    sub_img = Image.fromarray(sub_img_arr, "RGBA").rotate(degree)
    i2 = image.copy()
    i2.paste(sub_img, box[:2], sub_img.convert('RGBA'))
    return i2

i2 = circle_rotate(img, 260, 60, 60, 45)

enter image description here