简体   繁体   中英

How to determine the dimensions of an array by the length of a list

I wanted to display a varying number of images today in matplotlib subplot and ran into an interesting question I thought was simple but I can't seem to figure out. Don't worry about how to display it, I'm just wondering about the algorithm.

The Problem:

Given an length list of images determine the most square/efficient matrix to represent them.

Examples:

Given the following number of images, the output matrix would be ideal.

3 -> [2,2]

5 -> [2,3] or [3,2]

12 -> [4,3] or [3,4]

22 -> [5,5] is better than [6,4] for squareness but not efficiency

33 - > [6,6] or [7,5] for efficiency

I couldn't find the answer anywhere so I figured it would be fun to get some ideas. This is the code I was going to implement.

    for i in range(list_size):
        plt.subplot(0, 0, i + 1), plt.imshow(image_list[i], 'gray')
        plt.title(image_name[i])
        plt.xticks([]), plt.yticks([])

Aran-Fey is probably on the right track. Depending on whether you want a tall or wide aspect ratio, you could start by calculating an integer number of rows or columns based on a square. Integer columns gives a tall result because the "mod" type remainder will be added as a partial row below the squared part.

For a Square matrix that adds a partial row to the end...

matrixCols = int(sqrt(list_len))

round up to number of integer rows

matrixRows = math.ceil(list_len / matrixCols)

For a square matrix that adds a partial column to the end...

matrixRows = int(sqrt(list_len))

round up to number of integer columns

matrixCols = math.ceil(list_len / matrixCols)

It does seem that the most efficient matrix array is the one that sizes the images based on what will fit onto the screen/window until the size hits the smallest visible/usable image size and scrolls from there. The most efficient row/col matrix is going to depend on the aspect ratio of your screen/window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM