gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:29:21 24 4
gpt4 key购买 nike

下面的代码仅处理单个图像。我在同一位置有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 )

最佳答案

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

技巧是从路径中分离出文件名,因此您可以在正确的位置创建替换文件。

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

关于python - 如何在一个脚本中处理多个图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56850032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com