图片扩展---基于opencv-python实现

目标: 将一张长方形图片扩展成一张正方形图片,例如: 200x300x3的一张图片扩展成一张300x300x3的图片,填充部分使用白色.

代码:

import cv2
import os

imglist = os.listdir('.')
os.mkdir('./img')

for item in imglist:
    if item.endswith('.jpg'):
        src = os.path.join(os.path.abspath('.'), item)
        img = cv2.imread(src)
        shape = max(img.shape)
        high = img.shape[0]
        length = img.shape[1]

        top = int((shape - high) / 2)
        bottom = shape - high - top
        left = int((shape - length) / 2)
        right = shape - length - left

        newimg = cv2.copyMakeBorder(
            img,
            top,
            bottom,
            left,
            right,
            cv2.BORDER_CONSTANT,
            value=[
                255,
                255,
                255])
        cv2.imwrite("./img/" + item, newimg)

范例:

原图尺寸: (350, 277, 3)

 

扩展后图片尺寸: (350, 350, 3)

讨论:

cv2.copyMakeBorder(src,top, bottom, left, right ,borderType,value)

src:源图像

top,bottem,left,right: 分别表示四个方向上边界的长度

borderType: 边界的类型有以下几种:

BORDER_REFLICATE     # 直接用边界的颜色填充, aaaaaa | abcdefg | gggg
BORDER_REFLECT      # 倒映,abcdefg | gfedcbamn | nmabcd
BORDER_REFLECT_101   # 倒映,和上面类似,但在倒映时,会把边界空开,abcdefg | egfedcbamne | nmabcd
BORDER_WRAP        # 类似于这种方式abcdf | mmabcdf | mmabcd
BORDER_CONSTANT    # 常量,增加的变量通通为value色 [value][value] | abcdef | [value][value][value]

 

  

参考: https://www.cnblogs.com/pakfahome/p/3914318.html

转载于:https://www.cnblogs.com/congyucn/p/8302321.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值