physics_for_all
physics_for_all

Reputation: 2263

Rotate small portion of an array by 90 degrees

I want to rotate an array but not as a whole, only small portion of it.

I have 512X512 array (basically it is a Gaussian circle at the center (150,150) with 200 radius). Now I want to rotate only small portion (center around (150,150) with radius 100) of the array by 90 degree. Initially I used numpy rot90 module but it rotate each array element which is not I want.

Upvotes: 5

Views: 839

Answers (2)

fraxel
fraxel

Reputation: 35269

Here is some fuller code that does as F.J. 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)

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208405

If you can describe the elements that you would like rotated using advanced indexing, then you should be able to perform the rotation using something like the following (assuming 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 would signify the row-start and row-end of a slice, and the column-start and column-end of a slice, respectively.

Here is an example of why the np.copy call is necessary (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]])

Upvotes: 6

Related Questions