首页 > 解决方案 > OpenCV - Python将底部添加到现有图像

问题描述

我需要使用 Python 函数迭代到图像目录中,对于每个图像我需要添加额外的底部部分: 在此处输入图像描述

我正在考虑加载图像,计算尺寸,创建更大的黑色图像,然后粘贴:

import numpy as np
import cv2

def add_border(image):
    s_img = cv2.imread(image)
    dimensions = s_img.shape
    blank_image = np.zeros((s_img.shape[0]+200,s_img.shape[1],3), np.uint8)
    x_offset=y_offset=50
    blank_image[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img

    cv2.imshow("black", blank_image)
    cv2.imwrite('C:\\test\\' + 'black.jpg', blank_image)

    return (True)

add_border('C:\\test\\img001.JPG')

我收到以下错误:

blank_image[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img
ValueError: could not broadcast input array from shape (522,928,3) into shape (522,878,3)

有什么建议吗?谢谢

标签: python-3.xopencv

解决方案


你真的不需要任何 Python 来做到这一点,你可以使用安装在大多数 Linux 发行版上并且可用于 macOS 和 Windows的ImageMagick来完成。就在终端中(Windows 上的命令提示符):

magick image.png -background "rgb(68,114,196)" -gravity south -splice 0x40%  result.png

在此处输入图像描述

如果您想将 10% 的额外拼接到顶部,请使用:

magick image.png -background "rgb(68,114,196)" -gravity north -splice 0x10%  result.png

在此处输入图像描述


如果您的 ImageMagick 早于 v7,请使用convert代替magick上述命令。


如果您想在一个目录中处理所有图像,请进入该目录并为您的结果创建一个新的子目录,然后使用mogrify

cd <WHERE THE IMAGES ARE>
mkdir results
magick mogrify -path results -background "rgb(68,114,196)" -gravity south -splice 0x40%  *png

如果你想使用 OpenCV 和 Python,你可以这样做:

import cv2
import Numpy as np

# Load image
im = cv2.imread('image.png')

# Make a blue pad to append to bottom, same width as original and 30 pixels tall
# ... remembering OpenCV uses BGR ordering
pad = np.full((30,im.shape[1],3), [196,114,68], dtype=np.uint8)

# Stack pad vertically below the original image and save
result = np.vstack((im,pad))
cv2.imwrite('result.png',result)

推荐阅读