python-3.x - 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 来做到这一点,你可以使用安装在大多数 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)
推荐阅读
- excel - 在 Excel 中制作唯一的动态列表
- c++ - 在动态库中使用 Poco::JSON::Object 时堆栈粉碎
- php - 为 WHERE 条件选择相等数量的记录
- python - 在 Windows 上安装 Python RAWPY 包的问题
- php - 以这样的方式排列记录,D 类别总是在前,然后是 E & F,它将按照 1:1 的比例排列
- android - 为什么我的应用无法与 firebase 成功同步
- angular - 以热图比例显示值(以单位为单位)(泳道/ngx 图表)
- google-apps-script - 称为值的边框和排序公式
- java - 记录器的 Junit 测试用例
- cmake - Cmake - 导出和导入库