Search code examples
image-extraction

Extract the 3×3image segment from the input image centred around the position (x,y)


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 !


Solution

  • 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)