将指定文件夹中的所有JPEG图像进行处理,并保存到另一个文件夹中。首先,代码使用os.listdir()函数列出源文件夹中的所有文件,然后使用for循环遍历文件列表。对于以".jpg"结尾的文件,它执行以下操作:
-
构建输入文件路径 (f) 和目标文件路径 (f_new)。
-
使用cv2.imread()函数读取输入图像 (img)。
-
对图像进行裁剪操作 (dstimg=img[670:874, 810:1270]),选择区域为坐标 (670, 810) 到 (874, 1270),即高度从 670 到 874,宽度从 810 到 1270 的矩形区域。
-
定义目标图像的高度和宽度 (dstheight 和 dstwidth)。
-
使用cv2.resize()函数将裁剪后的图像缩放为目标尺寸 (zoomimg=cv2.resize(dstimg,(dstwidth,dstheight),interpolation=cv2.INTER_LINEAR))。
-
使用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()