Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make rectangular image squared using OpenCV and Python?

Tags:

python

opencv

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?

like image 328
Alex B Avatar asked Dec 06 '25 17:12

Alex B


1 Answers

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)
like image 136
Alex B Avatar answered Dec 08 '25 06:12

Alex B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!