【问题标题】:How do I make rectangular image squared using OpenCV and Python?如何使用 OpenCV 和 Python 制作矩形图像?
【发布时间】:2020-01-22 17:30:00
【问题描述】:

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

为此,我必须将它叠加在较大的方形顶部。 背景是黑色的。

当我需要对 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)

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

【问题讨论】:

标签: python opencv


【解决方案1】:

我想通了。你需要“广播成形”:

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)

【讨论】:

  • 如何创建白色背景?或者只是任何其他颜色的背景?
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多