||
最近业余时间学了一遍python简明教程,然后工作上正好用到python的照片切分
import cv2 import numpy as np import os import time """ 使用OpenCV截取图片 https://blog.csdn.net/qq_41982466/article/details/109602222 """ def CropImage4File(filepath): #对指定文件夹下的所有图片进行九宫格平均裁切,并输出中间部位的图片 pathDir = os.listdir(filepath) # 列出文件路径中的所有路径或文件 destpath = (filepath + "detect") # 确定输出位置 isExists = os.path.exists(destpath) # 判断路径是否存在,不存在则创建 if not isExists: os.makedirs(destpath) filenumber = len(pathDir) #计算文件数量,确定循环次数 start = time.time() #开始计时 i = 0 #定义初始变量用于循环计数 for allDir in pathDir: # 遍历指定目录,显示目录下的所有文件名 i = i+1 #循环累加 if i < filenumber + 1:#用于循环终止判断 source = os.path.join(filepath, allDir) destination = os.path.join(destpath, allDir) if os.path.isfile(source): image = cv2.imdecode(np.fromfile(source, dtype=np.uint8), cv2.IMREAD_COLOR)#支持中文路径和正反斜杠的路径 sp1 = image.shape[0]# 获取图像形状:返回横向像素数量列表 sp2 = image.shape[1]# 获取图像形状:返回纵向像素数量列表 a = int(sp1 / 3 ) # x start b = int(sp1 / 3 + sp1 /3) # x end c = int(sp2 / 3 ) # y start d = int(sp2 / 3 + sp2 /3) # y end cropImg = image[a:b, c:d] # 裁剪图像,结合上面四行,横向取中间三分之一,纵向取中间三分之一 cv2.imencode('.jpg', cropImg)[1].tofile(destination)#支持中文路径的文件保存 else: return 0 else: print("there is something wrong with cut picture!!!")#用于调试错误 else: print("裁切完成!!!")#输出运行结束语 end= time.time()#终止计时 print('运行时间: %s 秒' % (end - start))#输出运行时间 if __name__ == '__main__': filepath = 'F:\Data-Set\pic' # 源图像位置 destpath = (filepath + "detect") CropImage4File(filepath)
改了另一篇博客里的代码,网址在代码注释里,最后只需要将【源图像位置】路径改一下,就可以将路径里的照片取中甲部分,并输出到另外一个文件夹。
如果需要输出全部九张图的话稍微一改就成。
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-4-18 18:09
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社