简体   繁体   中英

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

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?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM