如何使用OpenCV+Keras+Tensorflow实现去噪算法与自定义预处理函数

磐创AI

    理解问题在处理计算机视觉问题时,我们经常遇到需要对整个数据集应用某种形式的转换的情况。Keras中的ImageDataGenerator类提供了各种转换,如翻转、规格化等。然而,应用在Keras中不可用的自定义转换变得非常困难。
    在我们的特定示例中,我们将对我们的数据集应用去噪算法作为预处理转换。一种简单的方法是对数据集中的所有图像应用去噪函数,并将处理后的图像保存在另一个目录中。然而,这同时消耗了我们的时间和空间。另一种方法是使用preprocessing_function属性动态地执行这个转换。
    为了加载用于训练的图像,我使用了Keras中实现的.flow_from_directory()方法。使用OpenCV去噪是相当简单的,OpenCV提供了几个内置算法来实现这一点。
    在本文中,我将展示如何定义我们自己的预处理函数,将其传递给训练生成器,并将图像直接提供给模型,从而无需保存它们。本教程大致分为两部分实现去噪算法扩展预处理函数让我们马上开始吧!第一部分 实现去噪算法让我们准备一个函数,将图像作为输入,应用内置的去噪算法,并返回处理后的图像。import cv2
    import numpy as np
    def preprocessing_fun(filename):
        img = cv2.imread(filename)
        dst = cv2.fastN1MeansDenoisingColored(img, None, 10, 10, 7, 21)
        return dst
    我们使用OpenCV的fastN1MeansDenoisingColored算法,因为该算法适用于彩色图像。OpenCV还提供了使用单通道处理图像的其他算法。fastN1MeansDenoisingColored:https://docs.opencv.org/master/d1/d79/group__photo__denoise.html#ga03aa4189fc3e31dafd638d90de335617现在我们已经实现了我们的算法,让我们在ImageDataGenerator类中使用它。第2部分 扩展预处理函数这里,我们使用训练生成器中前一节定义的函数。img_datagen = ImageDataGenerator(rescale=1./255,
                               preprocessing_function = preprocessing_fun)
    training_gen = img_datagen.flow_from_directory(PATH, target_size=(224,224),
                              color_mode='rgb',batch_size=32, shuffle=True)
    在定义ImageDataGenerator对象的前两行中,你可以注意到我们已经将去噪函数传递给了preprocessing_function参数。通过这样做,我们将指示我们的数据生成器在将图像提供给模型之前,将这个函数应用到每个图像上作为预处理步骤。这样,我们就不需要处理所有图像并将它们写入一个单独的目录。专业提示:如果你需要执行一系列在不同函数中定义的转换,你可以在你的训练生成器中以以下方式使用它。def transform1(img):
        #Applies a transformation such as horizontal flip and returns the image
        return cv2.flip(img, 1)
    def transform2(img):
        #Applies a transformation such as vertical flip and returns the image
        return cv2.flip(img, 0)
    def transform3(img):
        #Applies 180-degree rotation and returns the image
        return cv2.rotate(img, cv2.ROTATE_180)
    def our_preprocessing_function(filename):
        #Combines all the transformations
        img = cv2.imread(filename)
        img1 = transform1(img)
        img2 = transform2(img1)
        final_img = transform3(img2)
        return final_img
    img_datagen = ImageDataGenerator(rescale=1./255,
    preprocessing_function = our_preprocessing_function)
    training_generator = img_datagen.flow_from_directory(PATH,
    target_size=(224,224), color_mode='rgb', batch_size=32,
     class_mode='categorical', shuffle=True)
    通过这种方式,我们可以提供一系列自定义转换,将它们包装在一个函数中,并将它们应用到我们的数据集。此方法简单但功能强大,在资源受限的环境中工作很方便。