如何使用OpenCV和Python将矩形图像变为正方形?

4

我有各种矩形形状的图片。我需要将它们修改为统一的正方形形状(不同大小可以)。

为此,我必须将其放置在更大的正方形形状之上。背景是黑色的。

我已经想到了需要将2张图片叠加在一起的步骤:

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)

如何将它们堆叠在一起,使原始图像在黑色形状的上方垂直和水平居中?

2个回答

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

最终草稿:

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)

1
如何创建白色背景?或者其他任何颜色的背景? - Parikshit Chalke
要获取任何颜色,请将 square= np.zeros((x,y,3), np.uint8) 替换为:square= np.ones((x,y,3), np.uint8) * (B, G, R) 其中 B、G、R 是标准 RGB 值,整数介于 0 和 255 之间。对于灰度图像,请替换以下行: height, width = img.shape print (in_img,height, width) square = np.ones((x,y), np.uint8) * value 其中 'value' 是背景的灰度值(黑色为 0,白色为 255)。 - Snery

-5

您可以使用numpy.vstack将图像垂直堆叠,使用numpy.hstack将图像水平堆叠。

如果这解决了您的问题,请标记为已回答。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接