4

I have all sorts of images of rectangular shape. I need to modify them to uniform square shape (different size ok).

For that I have to layer it on top of larger squared shape. Background is black.

I figured it to the point when I need to layer 2 images:

import cv2
import numpy as np
if 1:
        img = cv2.imread(in_img)
        #get size
        height, width, channels = img.shape
        print (in_img,height, width, channels)
        # Create a black image
        x = height if height > width else width
        y = height if height > width else width
        square= np.zeros((x,y,3), np.uint8)
        cv2.imshow("original", img)
        cv2.imshow("black square", square)
        cv2.waitKey(0)

How do I stack them on top of each other so original image is centered vertically and horizontally on top of black shape?

Alex B
  • 2,165
  • 2
  • 27
  • 37
  • Possible duplicate of [resize image canvas to maintain square aspect ratio in Python, OpenCv](https://stackoverflow.com/questions/44720580/resize-image-canvas-to-maintain-square-aspect-ratio-in-python-opencv) – alkasm Aug 12 '17 at 07:22

2 Answers2

2

I figured it. You need to "broadcast into shape":

square[(y-height)/2:y-(y-height)/2, (x-width)/2:x-(x-width)/2] = img

Final draft:

import cv2
import numpy as np
if 1:
        img = cv2.imread(in_img)
        #get size
        height, width, channels = img.shape
        print (in_img,height, width, channels)
        # Create a black image
        x = height if height > width else width
        y = height if height > width else width
        square= np.zeros((x,y,3), np.uint8)
        #
        #This does the job
        #
        square[int((y-height)/2):int(y-(y-height)/2), int((x-width)/2):int(x-(x-width)/2)] = img
        cv2.imwrite(out_img,square)
        cv2.imshow("original", img)
        cv2.imshow("black square", square)
        cv2.waitKey(0)
Parikshit Chalke
  • 3,745
  • 2
  • 16
  • 26
Alex B
  • 2,165
  • 2
  • 27
  • 37
  • 1
    How to create white background? OR simply background of any other color? – Parikshit Chalke Jan 22 '20 at 06:31
  • @ParikshitChalke To get any color, replace `square= np.zeros((x,y,3), np.uint8)` with: `square= np.ones((x,y,3), np.uint8) * (B, G, R)` Where B, G, R are the standard RGB values for colors with integers between 0 and 255. For Grayscale images replace these lines: `height, width = img.shape` `print (in_img,height, width)` `square = np.ones((x,y), np.uint8) * value` Where 'value' is the greyscale value for the background (0 for black and 255 for white) – Snery May 24 '23 at 12:13
-5

You can use numpy.vstack to stack your images vertically and numpy.hstack to stack your images horizontally.

Please mark answered if you this resolves your problem.

Muhammad Abdullah
  • 876
  • 2
  • 8
  • 26