如何在一个脚本中处理多个图像?

时间:2019-07-02 10:07:10

标签: python opencv

下面的代码仅处理单个图像。我在同一位置有3张图像(分别名为1.tif,2.tif,3.tif)。

我需要在同一脚本中对所有3张图像依次进行相同的处理,并避免代码重复。

我认为可以用.glob或os.walk完成,但是我没有python所需的知识来进行此操作。非常感谢。

    import cv2
    import numpy as np
    import gdal

    in_imgpath = r'E:\2_PROJETS_DISK_E\test4\1.tif'

    img = cv2.imread(in_imgpath ,0)

    dataset1 = gdal.Open(in_imgpath)
    projection = dataset1.GetProjection()
    geotransform = dataset1.GetGeoTransform()

    # Processing
    blur = cv2.GaussianBlur(img,(5,5),0)
    ret1,th1 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    kernal = np.ones((3,3), np.uint8)
    dilation = cv2.dilate(th1, kernal, iterations=2)
    erosion = cv2.erode(dilation, kernal, iterations=1)
    opening = cv2.morphologyEx(erosion, cv2.MORPH_OPEN, kernal, iterations=3)
    closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernal, iterations=4)

    out_imgpath = r'E:\2_PROJETS_DISK_E\test4\1-1.tif'

    cv2.imwrite(out_imgpath ,closing)
    dataset2 = gdal.Open(out_imgpath, gdal.GA_Update)
    dataset2.SetGeoTransform( geotransform )
    dataset2.SetProjection( projection )

2 个答案:

答案 0 :(得分:1)

使用glob。 glob返回与您的模式匹配的所有文件的路径列表。

import glob

for path in glob.glob('your path/*.tif'):
    do_something(path)

答案 1 :(得分:0)

glob确实是您的朋友,因为它使您可以循环处理所有适当的文件。

通过技巧将文件名与路径分开,以便可以在正确的位置创建替换文件。

[import cv2
import numpy as np
import gdal

import os
from glob import glob

in_imgpath = r'E:\2_PROJETS_DISK_E\test4\*.tif'

for filename in glob(in_imgpath):
    img = cv2.imread(filename, 0)
    path, base_filename = os.path.split(filename)

    dataset1 = gdal.Open(in_imgpath)
    projection = dataset1.GetProjection()
    geotransform = dataset1.GetGeoTransform()

    # Processing
    blur = cv2.GaussianBlur(img,(5,5),0)
    ret1,th1 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    kernal = np.ones((3,3), np.uint8)
    dilation = cv2.dilate(th1, kernal, iterations=2)
    erosion = cv2.erode(dilation, kernal, iterations=1)
    opening = cv2.morphologyEx(erosion, cv2.MORPH_OPEN, kernal, iterations=3)
    closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernal, iterations=4)

    out_imgpath = os.path.join(path, "1-"+base_filename)

    cv2.imwrite(out_imgpath ,closing)
    dataset2 = gdal.Open(out_imgpath, gdal.GA_Update)
    dataset2.SetGeoTransform( geotransform )
    dataset2.SetProjection( projection )