While building a machine vision application, I came across this requirement to fit several images in the same Open CV window. Open CV has a method cv.imshow(window_name,image_to_display) -that displays the required image in a new window. You can use cv2.namedWindow() function to reuse the same window, however displaying multiple images in the same window can be task.
After scouting the internet for hours , I developed this snippet to suit the requirement. This article will cover the process in detail.
The solution to this problem is a simple two step process.
- Resize the image to be displayed to fit the allotted space in the window.
- Calculate the coordinates and position of the image in the window.
The image to be displayed is read and resized using the following code.
Line 1 : Reading the image and storing it in variable- ‘image’
Line 2: Resizing the read image to fit the allotted dimensions in the window. The dimensions (1260,720) are the desired width and height of the resized image respectively.
Line 3: This code line is for placing the resized image at a defined position in the window “canvas”. The formula used here is :
window_name[y-coordinate of start position+height of image to be placed, x- coordinate of start position+width of image to be placed]
Note: Your resized image’s dimensions should not exceed the dimensions of the allotted place in the window else the image won’t fit and would cause an error. Something like this (Value Error: could not broadcast input array from shape (300,1000,3) into shape (300,925,3))
resized image’s height≤ allotted space’s height ;
resized image’s width≤allotted space’s width.
Final output screen with three different images within the same window: