python 图片 常数 代码 padding image constant pad with constant code

本文介绍如何使用Python对2D或3D图片进行padding操作,以统一图片大小,适合输入到计算机视觉网络。代码会用指定常数填充图片边缘,3D图片的最后一个维度保持不变。示例代码包含特殊情况处理,并提供了使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单来讲,计算机视觉需要将图片大小统一,这样才能输入到网络。

这个代码就是将2D或者3D的图片padding 到指定大小,边缘填充使用指定常数,

如果是3D,(512,512,3)最后一维不进行拓展

我加了注释,如果拓展的不能整除,那么左,上,也就是序号小的比序号大的差一维

rar = crop_to((5,5),np.array([[1,3,4,5],[2,3,3,3]]))
print(rar)
输出:
[[21 21 21 21]
 [21 21 21 21]
 [ 1  3  4  5]
 [ 2  3  3  3]
 [21 21 21 21]]
import numpy as np


def crop_to(tag_shape=(512,512), org_arr=np.array([0,0]),constant_value=21):
    """
    Padding a 2D array org_arr to a arbitrary tag_shape with a constant_value .
    If the horizon and vertical gap not divided by 2
    ,then left0>right0
    and up0>right0
    Only for 2D
    Args:
        tag_shape:1D array,int, target shape suppose bigger than origin array shape
        org_arr: 2D array prepared to be pad with 0 to shape equals to org_arr
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值