hamza
hamza

Reputation: 3

how to process multiple images in one script?

The code below processes only a single image. I have 3 images (named 1.tif, 2.tif, 3.tif) in the same location.

I need to do the same processing sequentially for all 3 images, in the same script and avoid code duplication.

I think it can be done with .glob or os.walk, but I do not have the necessary knowledge in python for this operation. Thank you so much.

    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 )

Upvotes: 0

Views: 518

Answers (2)

Sachin Prabhu
Sachin Prabhu

Reputation: 152

use glob. glob returns a list of paths of all files that match your pattern.

import glob

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

Upvotes: 1

holdenweb
holdenweb

Reputation: 37033

glob is indeed your friend, as it will allow you to process all appropriate files in a loop.

The trick it to separate out the filename from the path, so you can create the replacement file in the right place.

[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 )

Upvotes: 0

Related Questions