only rotate part of image python
<p>Can someone tell me how to rotate only part of an image like this:</p>

<p><a href="http://i.stack.imgur.com/8MEVW.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/8MEVW.jpg" alt="this"></a></p>

<p>How to find coordinate / center of this image:</p>

<p><a href="http://i.stack.imgur.com/PxGtN.png" rel="nofollow"><img src="http://i.stack.imgur.com/PxGtN.png" alt="image"></a></p>

<p>i can rotate all pict using this</p>

<pre><code>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()
</code></pre>

<p>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. </p>

<pre><code>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))
</code></pre>

<p><a href="http://i.stack.imgur.com/6qc9r.png" rel="nofollow"><img src="http://i.stack.imgur.com/6qc9r.png" alt="enter image description here"></a></p>

<p>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.</p>

<pre><code>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 &lt;= 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)
i2
</code></pre>

<p><a href="http://i.stack.imgur.com/CkIVH.png" rel="nofollow"><img src="http://i.stack.imgur.com/CkIVH.png" alt="enter image description here"></a></p>

python image rotation python-imaging-library python-3.4