菜鸟代码,python学习日常(一)批处理图片

学习opencv,从处理图片开始入手,对于大量的图片需要进行批处理,这里写一个for循环函数能省下不少工作,这里需要用到一个python中重要的库os。
对目标图片的读取,可以用到这个代码。

imageFiles = [f for f in os.listdir(inputFolder) if f.endswith('.jpg')]

对目标文件夹中的图片进行读取,主要读取jpg的图片,如果有JPG的则看作JPG。
写一个for循环读取目标文件夹中的图片。

for i ,inputFile in enumerate(imageFiles,start  = 1): 
	inputFilePath = os.path.join(inputFolder,inputFile) 
	inputImage = cv2.imread(inputFilePath)

循环第一行为历遍imageFiles中所有的文件,并将文件索引出差你在 i 中,索引的第一个值为 start = 1 .
第二行为将两个括号内的两个文件变量的路径合并并储存在 inputFilePath 中。
第三行为读取目标文件中的所有图片。

   if inputImage is None:
            print(f"Failed to read input image: {inputFilePath}")
            continue
   # image process define
   processedImage = cv2.cvtColor(inputImage,cv2.COLOR_BGR2GRAY)

这里是将对读取图片路i纪念馆的判断,将图像处理函数放在判断后面。

在这之后就是保存图片的命名,这里需要重新命名,即需要将文件名字与文件格式后缀分离。

fileName, extension = os.path.splitext(inputFile)
outputFileName = f"{fileName}_{i}{extension}"
outputFile = os.path.join(outputFolder, outputFileName)

第一行将代码分离成文件名与 .jpg 形式。
第二行重命名将在保存的图片文件中间插入序号。
第三行将文件名与保存路径合并。

基本上这个代码的逻辑就是这样。将其整理成函数就可以直接调用了。

下面是完整代码

def batchProcessImages(inputFolder, outputFolder):
    imageFiles = [f for f in os.listdir(inputFolder) if f.endswith('.jpg')]

    for i, inputFile in enumerate(imageFiles, start=1):
        inputFilePath = os.path.join(inputFolder, inputFile)
        inputImage = cv2.imread(inputFilePath)

        if inputImage is None:
            print(f"Failed to read input image: {inputFilePath}")
            continue

        # 在这里进行你的图像处理操作
        processedImage = cv2.cvtColor(inputImage,cv2.COLOR_BGR2GRAY)  # 这里仅做示例,复制原图作为处理结果

        fileName, extension = os.path.splitext(inputFile)
        print(fileName)
        print(extension)
        outputFileName = f"{fileName}_{i}{extension}"
        outputFile = os.path.join(outputFolder, outputFileName)

        if not cv2.imwrite(outputFile, processedImage):
            print(f"Failed to write output image: {outputFile}")
            continue

        print(f"Processed image saved: {outputFile}")


inputFolder = "inputPath"  # 输入图片文件夹路径
outputFolder = "outputPaht"  # 输出图片文件夹路径
if __name__ == "__main__"
	batchProcessImages(inputFolder, outputFolder)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值