I want to ask how to Extract the a n×n image segment from an input image centered around the position (x,y), the image has format like this [[num,num,num],[num,numm,num],[num,num,num]........], size of image is about 10 * 10. Thank you !
-
Hi, what have you tried so far? What programming language do you want to use? – Leander Mar 12 '21 at 20:20
-
oh, my mistake I am using python, – Amaranta Arcadio Mar 12 '21 at 20:20
-
I am trying to use for loop solving it but I don't have any clue – Amaranta Arcadio Mar 12 '21 at 20:21
-
Do u have any thought ? – Amaranta Arcadio Mar 12 '21 at 20:22
-
is your array a numpy array? then you can do [this](https://www.w3schools.com/python/numpy_array_slicing.asp). – Leander Mar 12 '21 at 20:23
-
do u have another way that will avoid using numpy ? – Amaranta Arcadio Mar 12 '21 at 20:28
2 Answers
I do really recommend using numpy, when working with multidimensional arrays/when you want to manipulate these arrays, but here you go, a numpy solution and a solution without numpy.
import numpy as np
img = np.array([[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7],[4,5,6,7,8],[5,6,7,8,9]])
print('img:\n',img,'\n')
partOfImage = img[0:3,0:3]
print('partOfImage:\n',partOfImage)
img = [[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7],[4,5,6,7,8],[5,6,7,8,9]]
noNumpy =[[img[i][j] for j in range(0,3)] for i in range(0,3)]
print(noNumpy)

- 298
- 2
- 7
-
You are welcome, I have a quick tip for you: if you don't want to get hated on by the more strict users on stackoverflow, you should post your attempt next time, it's good practice to show what you've tried. This way it's kind of like asking someone else to solve your issue. You can find the guidlines of posting a good question [here](https://stackoverflow.com/help/how-to-ask) And make sure you put it under the right tag ;) – Leander Mar 12 '21 at 20:38
Question. So you wish to find the center of an image, expand 1 pixel left, left down, down, right down, right, right up, up, and left up to get an image from the middle of your sample. Correct? I do not have a code example, but a conceptual comment.
Fixed spatial images normally start their addressing at upper left for 0,0. Because of their even numbers of pixels approach, it's near-impossible to find a "middle". So finding a "middle pixel" means you need to apply a percentage and choose the nearest "whole pixel" to the choice. Then expand to your 3x3 dimensions.

- 1
- 1