当前位置:   article > 正文

Python+OpenCV之图片批处理(一)_opencv批量读取图片python

opencv批量读取图片python

在平时的工作中,会遇到以下这种情况。当我们的需求是处理一批图片,而不仅仅是一张图片。这时候,我们可以利用python来批量处理大量的图片集,提高工作效率。

批量读取图片

下面展示的是我的电脑路径下的Image文件夹里的内容:

Image batch processing

1.从当前目录Image文件夹里,读取后缀名为.jpg格式的图片

    for files in glob.glob(r'demo\image database1\standard_test_images\*.jpg'):
        imgsrc = cv.imread(files)
  • 1
  • 2

Image batch processing_01

2.读取当前Image文件夹中的所有文件:

#自定义一个路径函数read_path(),用来读取文件夹里全部内容
def read_path():
    #文件夹目录
    path = './demo\image database1\standard_test_images'
    #得到文件夹下所有文件的名称
    files = os.listdir(path)
    #遍历文件夹
    for file in files:  #或者这样写循环 for file in os.listdir(path):
        print(file)
    print('读取文件结束')

if __name__ == '__main__':
    read_path()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

Image batch processing_02

完整代码

下面介绍的这部分,包括:
如何来批量读取一个文件中的图片pichuli( )
如何读取文件夹下的所有文件read_path( )

# -*- coding: utf-8 -*-
# @Time    : 2022/7/28 9:25
import cv2 as cv
import glob
import os

# 图片批量处理
def pichuli():
    nums = 1
    for files in glob.glob(r'demo\image database1\standard_test_images\*.jpg'):
        imgsrc = cv.imread(files)
        Shape = imgsrc.shape
        print(Shape)
        # 输出路径
        opfile = r'demo\test1py_data_pic\inner_pic_B'
        # 判断opfile是否存在,不存在则创建
        # if (os.path.isdir(opfile) == False):
        #     os.mkdir(opfile)
        image_path = opfile + '('+str(nums)+')'+'.jpg'
        cv.imwrite(image_path, imgsrc)
        nums += 1
        # print('批处理结束')
    return Shape

#自定义一个路径函数read_path(),用来读取文件夹里全部内容
def read_path():
    #文件夹目录
    path = './demo\image database1\standard_test_images'
    #得到文件夹下所有文件的名称
    files = os.listdir(path)
    #遍历文件夹
    for file in files:  #或者这样写循环 for file in os.listdir(path):
        print(file)
    print('读取文件结束')
    
if __name__ == '__main__':
    pichuli()
    read_path()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

实用的图像集 The USC-SIPI Image Database 链接

本文中图像集 standard_test_images
链接:https://pan.baidu.com/s/10Z7o3yYY7NiOj2BobEQQRA
提取码:x49h

对大量图片进行重命名 链接

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号