For循环不写入图像

问题描述 投票:0回答:1

我正在尝试编写一个 for 循环,打开文件夹中的每个图像,对其进行处理,然后将其输出回同一文件夹中。问题是,当我运行脚本时,什么也没有发生。我只看到命令窗口中显示的脚本。我尝试在循环之外运行脚本的每个部分,各个部分似乎都没有问题。作为参考,我在循环外部定义了高斯噪声图像,循环在原始图像上添加了高斯噪声。然后我想在新图像名称的末尾附加一个数字,这样原始图像就不会被删除。

import os
import glob
import cv2
import numpy as np
img_dir = "path to folder"
data_path = os.path.join(img_dir, '*tif')
files = glob.glob(data_path)
data = []

#Create zero image with same dimensions as input image
gauss_noise=np.zeros((400,400, 3),dtype=np.uint8) #change according to image size
cv2.randn(gauss_noise,5,95)
gauss_noise=(gauss_noise*10.5).astype(np.uint8)

#Loop
i = 0
for f1 in files:
    img = cv2.imread(f1)
    data.append(img)
    # Add gaussian noise image to original image
    gn_img = cv2.add(img, gauss_noise)
    cv2.imwrite(
        "{}{}_{:07d}.tif".format(
            img_dir,
            f1.split("/")[-1].strip(".tif"),
            i),
        gn_img)        
    i += 1
python opencv for-loop glob os.path
1个回答
0
投票

导入操作系统 导入全局 导入CV2 将 numpy 导入为 np 将 matplotlib.pyplot 导入为 plt

#Set working directory
wrking_dir = os.chdir(os.path.join("c:", os.sep, "Users", "fmriresearcher", "Documents", "Ambiguous Stimuli Categorization", "96stimuli"))

#Get images from working directory
files = glob.glob("*.tif")

#Create zero image with same dimensions as input image
gauss_noise=np.zeros((400,400, 3),dtype=np.uint8)
cv2.randn(gauss_noise,5,95)
gauss_noise=(gauss_noise*10.5).astype(np.uint8)

#Loop over images to add guassian mask and then save
i = 0
for file in files:
    img=cv2.imread(file)
    #Add gaussian noise image to OG image
    gn_img=cv2.add(img,gauss_noise)
    #cv2.imwrite("{}{}_{:02d}.tif".format(img_dir,file.split("/")[-1].strip(".tif"), i), gn_img)        
    cv2.imwrite('masked_' + file, gn_img) 
© www.soinside.com 2019 - 2024. All rights reserved.