Arkaik
Arkaik

Reputation: 902

Opencv - Center image into window

I'm currently using opencv-python to create an image viewer with drawing possibilities.

My aim is to have a full screen window containing the loaded image at its center.

I'm able to set the window in fullscreen and to show the image. I can also achieve some basic drawing and allow image zoom in/out with a mouse listener.

However I can't find a way to center the image into the displayed window.

Here is the sample code of the window part

#!/usr/bin/python3

import cv2

# Set screen resolution
resolution = (1920, 1080)

# Create window
cv2.namedWindow('Output')
cv2.resizeWindow("Output", resolution[0], resolution[1])

# Read and show image
inputImage = cv2.imread("stackoverflow.png")
cv2.imshow('Output', inputImage)

# Wait for keyboard input
chr = -1
while 0 < cv2.getWindowProperty("Output", cv2.WND_PROP_AUTOSIZE):
    chr = cv2.waitKey(100)

Result: enter image description here

Matplotlib does it quite well, it even resizes the printed image depending on window size.

enter image description here

I would like to implement something like that using opencv.

Upvotes: 2

Views: 4869

Answers (1)

Meto
Meto

Reputation: 658

import numpy as np
import cv2


img = cv2.imread("./car-top-view.png")

w,h,c = img.shape

# Set screen resolution
resolution = (1920, 1080)

# Create window
cv2.namedWindow("Output")
cv2.resizeWindow("Output", resolution[0], resolution[1])

new_w = int(w*1.5)
new_h = int(h*1.5)

img = cv2.resize(img, (new_w, new_h))

img = cv2.copyMakeBorder( img, int((1080-new_h)/2), int((1080-new_h)/2), int((1920-new_w)/2), int((1920-new_h)/2), 0)


cv2.imshow("Output",img)

if cv2.waitKey(0) == ord('q'):
    cv2.destroyAllWindows()

This should produce desired output. It re-scales image using custom a coefficient (1.5) in this case to keep the aspect ratio. Then pads the image with 0 all around so it would stay on the middle of the screen. Checkout cv2.copyMakeBorder for even more options.

Upvotes: 4

Related Questions