Здравствуйте, попробуйте этот код, и я сделаю изображение, чтобы вы поняли:)
image = [[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[1, 1, 1, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0]]
image_width = 5
image_height = 5
lowest_x = -1
lowest_y = -1
bigest_x = -1
bigest_y = -1
# Get the square of the shape of your image (edge coordinate)
for y in range(len(image)):
for x in range(len(image[y])):
if image[y][x] != 0:
if x < lowest_x or lowest_x == -1:
lowest_x = x
if y < lowest_y or lowest_y == -1:
lowest_y = y
if x > bigest_x or bigest_x == -1:
bigest_x = x
if y > bigest_y or bigest_y == -1:
bigest_y = y
print ("Edge coordinate = " + str(lowest_y) + ":" + str(lowest_x) + " - " + str(bigest_y) + ":" + str(bigest_x))
chunk_width = bigest_x - lowest_x + 1
chunk_height = bigest_y - lowest_y + 1
print ("Chunk size = " + str(chunk_height) + " " + str(chunk_width))
y_delimiter = (image_height - chunk_height) / 2
x_delimiter = (image_width - chunk_width) / 2
print ("Start of new coord = " + str(y_delimiter) + " " + str(x_delimiter))
new_image = [[0 for i in range(image_height)] for j in range(image_width)]
for y in range(chunk_height):
for x in range(chunk_width):
new_image[y_delimiter + y][x + x_delimiter] = image[lowest_y + y][lowest_x + x]
print("")
for y in range(len(new_image)):
print ' '.join(str(x) for x in new_image[y])