图片切片的python代码

将图片按一定步长切成小块

# -*- coding = utf-8 -*-
import numpy as np
import cv2
import os
from pathlib import Path
import math

def slice_img(img_dir , x , y):
    
    img_save = Path('./sliced_img_pathlib/')
    img_save.mkdir(exist_ok=True,parents=True)
    
    im = cv2.imread(img_dir,1)
    sum_y,sum_x,_ = im.shape
    gap_x=sum_x%x
    gap_y=sum_y%y
    
    group_x=math.ceil(sum_x/x)
    group_y=math.ceil(sum_y/y)
    lim_x=math.floor(sum_x/x)
    lim_y=math.floor(sum_y/y)
    
    for hy in range(group_y) :
        for hx in range(group_x) :
            new_x1 = hx*x
            new_y1 = hy*y
            new_x2 = x*(hx+1)
            new_y2 = y*(hy+1)
            if new_y2<=sum_y and new_x2<=sum_x:
                new_img=im[new_y1:new_y2,new_x1:new_x2,:]
                
            elif new_y2<=sum_y and new_x2>sum_x:
                new_img=im[new_y1:new_y2,new_x1:,:]
                #new_img=np.pad(new_img, ((0,0),(0,new_x1-wx),(0,0)), 'constant', constant_values=0)
                
            elif new_y2>sum_y and new_x2<=sum_x:
                new_img=im[new_y1:,new_x1:new_x2,:]
                #new_img=np.pad(new_img, ((0,new_y1-hy),(0,0),(0,0)), 'constant', constant_values=0)
                
            else:
                new_img=im[new_y2:,new_x2:,:]
                #new_img=np.pad(new_img, ((0,new_y1-hy),(0,new_x1-wx),(0,0)), 'constant', constant_values=0)
            
            tempfilename = Path(img_dir).stem +'_'+str(new_x1)+'_'+str(new_y1)+'.jpg'
            pic_fname=img_save / tempfilename
            cv2.imwrite(str(pic_fname), new_img,[int(cv2.IMWRITE_JPEG_QUALITY), 100])

slice_img('./2020-04-20.jpg',640,640)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值