Rotate a small portion of an array 90 degrees in python

I want to rotate the array, but not in general, only a small part of it. I have an array of 512X512 (basically this is a Gaussian circle in the center (150,150) with a radius of 200). Now I want to rotate only a small part (in the center around (150,150) with a radius of 100) of the array 90 degrees. I originally used the numpy rot90 module, but it rotated every element of the array that I don't need. I would appreciate any feedback.

thanks

-Viral

+4
source share
2 answers

If you can describe the elements you want to rotate using advanced indexing , then you can rotate using something like the following (if your array is called arr ):

 arr[rs:re,cs:ce] = np.rot90(np.copy(arr[rs:re,cs:ce])) 

Here rs , re , cs and ce mean the beginning of the line and the end of the slice line and the beginning of the column and the end of the column, respectively.

Here is an example of why you need to call np.copy (at least in numpy 1.3.0):

 >>> import numpy as np >>> m = np.array([[i]*4 for i in range(4)]) >>> m array([[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]) >>> m[1:3,1:3] = np.rot90(m[1:3,1:3]) # rotate middle 2x2 >>> m array([[0, 0, 0, 0], [1, 1, 2, 1], # got 1, 2 expected 1, 2 [2, 1, 1, 2], # 1, 1 1, 2 [3, 3, 3, 3]]) 
+5
source

Here is a more complete code that works as FJ has already explained.

enter image description here

And here is the code:

 import numpy as np import scipy def circle(im, centre_x, centre_y, radius): grid_x, grid_y = np.mgrid[0:im.shape[0],0:im.shape[1]] return (grid_x-centre_x)**2 + (grid_y-centre_y)**2 < radius**2 centre_x, centre_y, radius = 150, 200, 100 x_slice = slice(centre_x - radius, centre_x + radius) y_slice = slice(centre_y - radius, centre_y + radius) im = scipy.misc.imread('1_tree.jpg') rotated_square = np.rot90(im[x_slice,y_slice].copy()) im[circle(im, centre_x, centre_y,radius)] = rotated_square[circle(rotated_square, radius, radius, radius)] scipy.misc.imsave('sdffs.png',im) 
+1
source

All Articles