python实现批量裁剪图片

将指定文件夹中的所有JPEG图像进行处理,并保存到另一个文件夹中。首先,代码使用os.listdir()函数列出源文件夹中的所有文件,然后使用for循环遍历文件列表。对于以".jpg"结尾的文件,它执行以下操作:

  1. ​构建输入文件路径 (f) 和目标文件路径 (f_new)。

  2. 使用cv2.imread()函数读取输入图像 (img)。

  3. 对图像进行裁剪操作 (dstimg=img[670:874, 810:1270]),选择区域为坐标 (670, 810) 到 (874, 1270),即高度从 670 到 874,宽度从 810 到 1270 的矩形区域。

  4. 定义目标图像的高度和宽度 (dstheight 和 dstwidth)。

  5. 使用cv2.resize()函数将裁剪后的图像缩放为目标尺寸 (zoomimg=cv2.resize(dstimg,(dstwidth,dstheight),interpolation=cv2.INTER_LINEAR))。

  6. 使用cv2.imwrite()函数将缩放后的图像保存到目标文件中。

import os
import shutil
import cv2
import numpy as np

srcpath=r'C:\Users\user\Pictures\V\1\0'
dstpath=r'C:\Users\user\Pictures\V\2\0'
listfile = os.listdir(srcpath)
for i in listfile:
    if i.endswith('.jpg'):
        f=srcpath+'\\'+i
        f_new = dstpath + '\\' + i
        img=cv2.imread(f)
        dstimg=img[670:874, 810:1270]
        dstheight = 136
        dstwidth = 215
        zoomimg=cv2.resize(dstimg,(dstwidth,dstheight),interpolation=cv2.INTER_LINEAR)
        cv2.imwrite(f_new,zoomimg)

# cv2.namedWindow('imgdst',cv2.WINDOW_NORMAL)
# cv2.namedWindow('zoomimg',cv2.WINDOW_NORMAL)
# cv2.namedWindow('p2',cv2.WINDOW_NORMAL)
#
# cv2.imshow('imgdst', imgdst)
# cv2.imshow('zoomimg', zoomimg)
# cv2.imshow('p2', p2)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值