Exemple #1
0
def test_dHash(aOriginalImages,
               aComparativeImages,
               lThreshold=0.2,
               lHashSize=16,
               oCache=None):

    # create dictionary of metadata
    dicMetadata = {
        "algorithm": "dHash",
        "hash_size": lHashSize,
        "threshold": lThreshold
    }

    # compare every image
    aDecisions = []
    for i, sOriginalImagePath in enumerate(aOriginalImages):
        sComparativeImagePath = aComparativeImages[i]

        if oCache:
            # create unique cache key for original and comparative key
            aCacheKeyBase = ["dHash", lHashSize]
            sOriginalImageCacheKey = oCache.calc_unique_key(
                *aCacheKeyBase, sOriginalImagePath)
            sComparativeImageCacheKey = oCache.calc_unique_key(
                *aCacheKeyBase, sComparativeImagePath)

            # check for existence of keys in cache
            aHashOriginal = oCache.get(sOriginalImageCacheKey)
            aHashComparative = oCache.get(sComparativeImageCacheKey)

        # get images from path and calculate hash if not in hash already
        # add to cache if calculated the first time and cache is active
        if aHashOriginal is None:
            aOriginalImage = load_image(sOriginalImagePath)
            aHashOriginal = aHash(aOriginalImage, hash_size=lHashSize)
            if oCache:
                oCache.set(sOriginalImageCacheKey, aHashOriginal)

        if aHashComparative is None:
            aComparativeImage = load_image(sComparativeImagePath)
            aHashComparative = aHash(aComparativeImage, hash_size=lHashSize)
            if oCache:
                oCache.set(sComparativeImageCacheKey, aHashOriginal)

        # calculate deviation
        dDeviation = hamming_distance(aHashComparative, aHashOriginal)

        # make decision
        bDecision = False
        if (dDeviation <= lThreshold):
            # images are considered to be the same
            bDecision = True

        # push decision to array of decisions
        aDecisions.append(bDecision)

    # return decision and dictionary of metadata
    return aDecisions, dicMetadata
Exemple #2
0
def overlay_hook(originalImagesPathes, attackedImagesTargetPath):

    attackName = "overlay"

    print("\nSpecify the full path to the overlay image.")
    overlayImage = None
    overlayImageFilePath = None
    while True:
        overlayImageFilePath = utils.escape_home_in_path(
            input("Overlay image: "))
        if utils.check_if_file_exists(overlayImageFilePath):
            # return all images in path as sorted list
            try:
                overlayImage = utils.load_image(overlayImageFilePath)
                break
            except:
                print("%s seems to be no image file." % overlayImageFilePath)
        else:
            print("image %s is not existend" % overlayImageFilePath)
            correctionDecision = input(
                "would you like to correct it or quit [c/Q]: ")
            print(correctionDecision)
            if not correctionDecision.lower() == "c":
                sys.exit(1)

    originalImagesPathesResult = []
    attackedImagesPathesResult = []
    for originalImagePath in originalImagesPathes:
        originalImage = utils.load_image(originalImagePath)
        originalImageName = utils.get_filename_without_extension(
            originalImagePath)

        # apply attack
        attackedImage = atk.blend_pattern(originalImage,
                                          aPatternImage=overlayImage)
        imageName = "%s_%s_%s" % (
            originalImageName, attackName,
            utils.get_filename_without_extension(overlayImageFilePath))
        # save image
        attackedImagePath = save_attacked_image(attackedImage,
                                                attackedImagesTargetPath,
                                                imageName, "png")
        originalImagesPathesResult.append(originalImagePath)
        attackedImagesPathesResult.append(attackedImagePath)

    targetDecisions = np.full(len(originalImagesPathesResult),
                              True,
                              dtype=bool)

    return originalImagesPathesResult, attackedImagesPathesResult, targetDecisions, {
        "attack": attackName,
        "blend_image": overlayImageFilePath
    }
Exemple #3
0
def gamma_hook(originalImagesPathes, attackedImagesTargetPath):

    attackName = "gamma"
    gammaFactors, rangeMetadata = get_range_parameter("gamma factor", 0, 10)

    originalImagesPathesResult = []
    attackedImagesPathesResult = []
    for originalImagePath in originalImagesPathes:
        originalImage = utils.load_image(originalImagePath)
        originalImageName = utils.get_filename_without_extension(
            originalImagePath)
        for gammaFactor in gammaFactors:
            # apply attack
            attackedImage = atk.gamma_adjustment(originalImage,
                                                 dGamma=gammaFactor)
            imageName = "%s_%s_%s" % (originalImageName, attackName,
                                      str(gammaFactor))
            # save image
            attackedImagePath = save_attacked_image(attackedImage,
                                                    attackedImagesTargetPath,
                                                    imageName, "png")
            originalImagesPathesResult.append(originalImagePath)
            attackedImagesPathesResult.append(attackedImagePath)

    targetDecisions = np.full(len(originalImagesPathesResult),
                              True,
                              dtype=bool)

    return originalImagesPathesResult, attackedImagesPathesResult, targetDecisions, {
        "attack": attackName,
        "parameterRangeMetadata": rangeMetadata
    }
Exemple #4
0
def contrast_hook(originalImagesPathes, attackedImagesTargetPath):

    attackName = "contrast"
    contrastFactors, rangeMetadata = get_range_parameter(
        "contrast factor", -128, 128)

    originalImagesPathesResult = []
    attackedImagesPathesResult = []
    for originalImagePath in originalImagesPathes:
        originalImage = utils.load_image(originalImagePath)
        originalImageName = utils.get_filename_without_extension(
            originalImagePath)
        for contrastFactor in contrastFactors:
            # apply attack
            attackedImage = atk.contrast(originalImage,
                                         lContrast=contrastFactor)
            imageName = "%s_%s_%s" % (originalImageName, attackName,
                                      str(contrastFactor))
            # save image
            attackedImagePath = save_attacked_image(attackedImage,
                                                    attackedImagesTargetPath,
                                                    imageName, "png")
            originalImagesPathesResult.append(originalImagePath)
            attackedImagesPathesResult.append(attackedImagePath)

    targetDecisions = np.full(len(originalImagesPathesResult),
                              True,
                              dtype=bool)

    return originalImagesPathesResult, attackedImagesPathesResult, targetDecisions, {
        "attack": attackName,
        "parameterRangeMetadata": rangeMetadata
    }
Exemple #5
0
def scale_uniform_hook(originalImagesPathes, attackedImagesTargetPath):

    attackName = "scale_uniform"
    scaleFactors, rangeMetadata = get_range_parameter("scale factor", 0, 10)

    originalImagesPathesResult = []
    attackedImagesPathesResult = []
    for originalImagePath in originalImagesPathes:
        originalImage = utils.load_image(originalImagePath)
        originalImageName = utils.get_filename_without_extension(
            originalImagePath)
        for scaleFactor in scaleFactors:
            # apply attack
            attackedImage = atk.scale(originalImage,
                                      lScalefactorX=scaleFactor,
                                      lScaleFactorY=scaleFactor)
            imageName = "%s_%s_%s" % (originalImageName, attackName,
                                      str(scaleFactor))
            # save image
            attackedImagePath = save_attacked_image(attackedImage,
                                                    attackedImagesTargetPath,
                                                    imageName, "png")
            originalImagesPathesResult.append(originalImagePath)
            attackedImagesPathesResult.append(attackedImagePath)

    targetDecisions = np.full(len(originalImagesPathesResult),
                              True,
                              dtype=bool)

    return originalImagesPathesResult, attackedImagesPathesResult, targetDecisions, {
        "attack": attackName,
        "parameterRangeMetadata": rangeMetadata
    }
Exemple #6
0
def gauss_noise_hook(originalImagesPathes, attackedImagesTargetPath):

    attackName = "gauss_noise"
    sigmaSteps, rangeMetadata = get_range_parameter("sigma", 0, 1)

    originalImagesPathesResult = []
    attackedImagesPathesResult = []
    for originalImagePath in originalImagesPathes:
        originalImage = utils.load_image(originalImagePath)
        originalImageName = utils.get_filename_without_extension(
            originalImagePath)
        for sigmaStep in sigmaSteps:
            # apply attack
            attackedImage = atk.gauss_noise(originalImage, dSigma=sigmaStep)
            imageName = "%s_%s_%s" % (originalImageName, attackName,
                                      str(sigmaStep))
            # save image
            attackedImagePath = save_attacked_image(attackedImage,
                                                    attackedImagesTargetPath,
                                                    imageName, "png")
            originalImagesPathesResult.append(originalImagePath)
            attackedImagesPathesResult.append(attackedImagePath)

    targetDecisions = np.full(len(originalImagesPathesResult),
                              True,
                              dtype=bool)

    return originalImagesPathesResult, attackedImagesPathesResult, targetDecisions, {
        "attack": attackName,
        "parameterRangeMetadata": rangeMetadata
    }
Exemple #7
0
def jpeg_quality_hook(originalImagesPathes, attackedImagesTargetPath):

    attackName = "JPEG_quality"
    qualitySteps, rangeMetadata = get_range_parameter(
        "JPEG quality in percent", 0, 100)

    originalImagesPathesResult = []
    attackedImagesPathesResult = []
    for originalImagePath in originalImagesPathes:
        originalImage = utils.load_image(originalImagePath)
        originalImageName = utils.get_filename_without_extension(
            originalImagePath)
        for qualityStep in qualitySteps:
            # apply attack
            attackedImage = atk.jpeg_compression(originalImage,
                                                 lJPEGQuality=qualityStep)
            imageName = "%s_%s_%s" % (originalImageName, attackName,
                                      str(qualityStep))
            # save image
            attackedImagePath = save_attacked_image(attackedImage,
                                                    attackedImagesTargetPath,
                                                    imageName, "png")
            originalImagesPathesResult.append(originalImagePath)
            attackedImagesPathesResult.append(attackedImagePath)

    targetDecisions = np.full(len(originalImagesPathesResult),
                              True,
                              dtype=bool)

    return originalImagesPathesResult, attackedImagesPathesResult, targetDecisions, {
        "attack": attackName,
        "parameterRangeMetadata": rangeMetadata
    }
Exemple #8
0
def crop_uniform_hook(originalImagesPathes, attackedImagesTargetPath):

    attackName = "crop_uniform"
    cropSteps, rangeMetadata = get_range_parameter(
        "crop percent of the image from top, left, bottom, right", 0, 0.5)

    originalImagesPathesResult = []
    attackedImagesPathesResult = []
    for originalImagePath in originalImagesPathes:
        originalImage = utils.load_image(originalImagePath)
        originalImageName = utils.get_filename_without_extension(
            originalImagePath)
        for cropStep in cropSteps:
            # apply attack
            attackedImage = atk.crop_percentage(originalImage,
                                                tpSlice=(cropStep, cropStep,
                                                         cropStep, cropStep))
            imageName = "%s_%s_%s" % (originalImageName, attackName,
                                      str(cropStep))
            # save image
            attackedImagePath = save_attacked_image(attackedImage,
                                                    attackedImagesTargetPath,
                                                    imageName, "png")
            originalImagesPathesResult.append(originalImagePath)
            attackedImagesPathesResult.append(attackedImagePath)

    targetDecisions = np.full(len(originalImagesPathesResult),
                              True,
                              dtype=bool)

    return originalImagesPathesResult, attackedImagesPathesResult, targetDecisions, {
        "attack": attackName,
        "parameterRangeMetadata": rangeMetadata
    }
Exemple #9
0
def rotation_fitted_hook(originalImagesPathes, attackedImagesTargetPath):

    attackName = "rotation_fitted"
    rotationAngles, rangeMetadata = get_range_parameter(
        "angle in degree", 0, 360)

    originalImagesPathesResult = []
    attackedImagesPathesResult = []
    for originalImagePath in originalImagesPathes:
        originalImage = utils.load_image(originalImagePath)
        originalImageName = utils.get_filename_without_extension(
            originalImagePath)
        for rotationAngle in rotationAngles:
            # apply attack
            attackedImage = atk.rotation(originalImage,
                                         dRotationAngle=rotationAngle,
                                         bFit=True,
                                         tpBorderValue=(0, 0, 0))
            imageName = "%s_%s_%s" % (originalImageName, attackName,
                                      str(rotationAngle))
            # save image
            attackedImagePath = save_attacked_image(attackedImage,
                                                    attackedImagesTargetPath,
                                                    imageName, "png")
            originalImagesPathesResult.append(originalImagePath)
            attackedImagesPathesResult.append(attackedImagePath)

    targetDecisions = np.full(len(originalImagesPathesResult),
                              True,
                              dtype=bool)

    return originalImagesPathesResult, attackedImagesPathesResult, targetDecisions, {
        "attack": attackName,
        "parameterRangeMetadata": rangeMetadata
    }
Exemple #10
0
def scale_nonuniform_hook(originalImagesPathes, attackedImagesTargetPath):

    attackName = "scale_nonuniform"

    scaleSets = []
    paramMinLimit = 0
    paramMaxLimit = 10
    print("Specify scale set (x, y)")
    while True:
        scaleDic = {"x": None, "y": None}
        for scaleKey in scaleDic:
            while True:
                valueString = input(scaleKey + ": ")
                try:
                    scaleDic[scaleKey] = float(valueString)
                except:
                    print("input is no number")
                    continue
                if (paramMinLimit <= scaleDic[scaleKey] <= paramMaxLimit):
                    break
                else:
                    print(
                        "input %f is bigger or smaller as domain of attack[%s, %s]"
                        % (scaleDic[scaleKey], str(paramMinLimit),
                           str(paramMaxLimit)))
                    continue

        scaleSets.append({
            "lScalefactorX": scaleDic["x"],
            "lScaleFactorY": scaleDic["y"]
        })

        print(
            "Would you like to add (a) another set of parameters or continue (c)?"
        )
        addAdditionalParameters = input("[a/C]: ")
        if (addAdditionalParameters.lower() != "a"):
            break

    parameterSetMetadata = {"scaleSets": scaleSets}

    originalImagesPathesResult = []
    attackedImagesPathesResult = []
    for originalImagePath in originalImagesPathes:
        originalImage = utils.load_image(originalImagePath)
        originalImageName = utils.get_filename_without_extension(
            originalImagePath)
        for scaleSet in scaleSets:
            # apply attack
            attackedImage = atk.scale(originalImage, **scaleSet)
            imageName = "%s_%s_%s" % (originalImageName, attackName,
                                      utils.format_filename(str(scaleSet)))
            # save image
            attackedImagePath = save_attacked_image(attackedImage,
                                                    attackedImagesTargetPath,
                                                    imageName, "png")
            originalImagesPathesResult.append(originalImagePath)
            attackedImagesPathesResult.append(attackedImagePath)

    targetDecisions = np.full(len(originalImagesPathesResult),
                              True,
                              dtype=bool)

    return originalImagesPathesResult, attackedImagesPathesResult, targetDecisions, {
        "attack": attackName,
        "parameterSetMetadata": parameterSetMetadata
    }
Exemple #11
0
def crop_nonuniform_hook(originalImagesPathes, attackedImagesTargetPath):

    attackName = "crop_nonuniform"

    cropSets = []
    paramMinLimit = 0
    paramMaxLimit = 1
    print("Specify crop percentage (top, left, bottom, right)")
    while True:
        edgesDic = {"top": None, "left": None, "bottom": None, "right": None}
        for edgeKey in edgesDic:
            while True:
                valueString = input(edgeKey + ": ")
                try:
                    edgesDic[edgeKey] = float(valueString)
                except:
                    print("input is no number")
                    continue
                if (paramMinLimit <= edgesDic[edgeKey] <= paramMaxLimit):
                    break
                else:
                    print(
                        "input %f is bigger or smaller as domain of attack[%s, %s]"
                        % (edgesDic[edgeKey], str(paramMinLimit),
                           str(paramMaxLimit)))
                    continue
        if (edgesDic["top"] + edgesDic["bottom"]) <= 1.0 and (
                edgesDic["left"] + edgesDic["right"] <= 1.0):
            cropSets.append((edgesDic["top"], edgesDic["left"],
                             edgesDic["bottom"], edgesDic["right"]))
        else:
            print(
                "left + right and top + bottom have to be <= 1.0 ... once again"
            )
            continue
        print(
            "Would you like to add (a) another set of parameters or continue (c)?"
        )
        addAdditionalParameters = input("[a/C]: ")
        if (addAdditionalParameters.lower() != "a"):
            break

    parameterSetMetadata = {"cropSets": cropSets}

    originalImagesPathesResult = []
    attackedImagesPathesResult = []
    for originalImagePath in originalImagesPathes:
        originalImage = utils.load_image(originalImagePath)
        originalImageName = utils.get_filename_without_extension(
            originalImagePath)
        for cropSet in cropSets:
            # apply attack
            attackedImage = atk.crop_percentage(originalImage, tpSlice=cropSet)
            imageName = "%s_%s_%s" % (originalImageName, attackName,
                                      utils.format_filename(str(cropSet)))
            # save image
            attackedImagePath = save_attacked_image(attackedImage,
                                                    attackedImagesTargetPath,
                                                    imageName, "png")
            originalImagesPathesResult.append(originalImagePath)
            attackedImagesPathesResult.append(attackedImagePath)

    targetDecisions = np.full(len(originalImagesPathesResult),
                              True,
                              dtype=bool)

    return originalImagesPathesResult, attackedImagesPathesResult, targetDecisions, {
        "attack": attackName,
        "parameterSetMetadata": parameterSetMetadata
    }