PROJECTS / RESIZE IMAGE TO FIT SCREEN

2022

Resize image to fit screen

Languages:

While dealing with OpenCV projects involving images we want the output image to be smaller than screen size in order to be able to see our results.

On this project we are going to implement a simple program in order to resize an image multiple times until it's size is smaller than screen's.

Feel free to check the following video on Youtube for a better and visual understanding of this project and it's concepts.

Load Initial image

To load the initial image which is too large to display on screen we use cv2 library and cv2.imread("image_path") function.
# Import libraries
import cv2

# Load initial image
image = cv2.imread("image.jpg")
Initial Image with mountains

Calculate sizes - width & height

We are going to calculate initial image's size and screen's size. For this calculations we need to use shape function from cv2 library and size function from pyautogui library respectively.

import pyautogui
# Calculate screen size
screen_width, screen_height = pyautogui.size()

# Calculate initial image size
# (0: height, 1: width, 2: channels)
(image_height, image_width, _) = image.shape 

Resize metric

At this point we are going to define our resize metric. Notice that the value of this metric must be less than 1 in order to reduce the inital image size. Let's say that we set variable resize_metric = 0.8.

Resize image until it's fully visible

Add a while loop where we will keep resizing the given image until it's size is smaller than screen's. For both image's width and height replace the values with the 80% of the previous inside the loop. If both width and height are smaller than screen's width and height then break this loop.

while True:
    if(image_height < screen_height and image_width < screen_width):
        break

    # Calculate new size
    image_width = int(image_width * resize_metric)
    image_height = int(image_height * resize_metric)

    # Calculate new image size
    image = cv2.resize(image, (image_width, image_height))

Finally show the new image and check if it fits on the screen.

# Show image
cv2.imshow("Image", image)

For a better and visual understanding of this project and it's concepts, watch the video on Youtube.