[SOLVED] How to reshape numpy array from image on different monitor's resolution

Issue

I have code:

def get_image_array(data):
    fig = plt.figure(figsize=(1.5, 1.5), dpi=100)
    plt.plot(data, '-o', c='r')
    plt.axis('off')
    fig.canvas.draw()

    img_arr = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
    img_arr = img_arr.reshape(fig.canvas.get_width_height()[::-1] + (3,)).astype(np.float32)
    img_arr = img_arr[None, :]
    plt.close()

    return img_arr

where I create figure with figure size 150×150 (RGB), convert it to numpy array for using in CNN model. I launch it on FullHD monitor and it works, but it doesn’t work on 2k, 4k monitors. The
erros is:

ValueError: cannot reshape array of size 270000 into shape (150,150,3)

How can I create figure with figure size 150×150 for different types of resolution?

Solution

Reshape just reconfigures the existing information so if you have 67500 data points (150*150*3) you can have that as one long array or you can nest it as (150,150,3) or (22500,3) and so on. However if you want to go to bigger resolutions you’d need more information than you’ve got available and so you need to make something up.

Like you could double the size of a pixel to cover 4 pixels instead of 1 or you can copy the array multiple times or you can pad it with 0s or other values. There are functions like numpy.resize but you should check beforehand what you actually want it to be like.

Also usually the other way around is easier, that is you start with a high definition image and then resize it to become smaller. In that case you lose information in rescaling and so you don’t have to make something up.

Answered By – haxor789

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *