Exemple #1
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 #2
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 #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 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 #5
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 #6
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 #7
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 #8
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 #9
0
def add_custom_challenges():
    # Path to original images
    # path to comparative images
    # rule: "<imageName>_[S,D]"
    # add special attributes

    challengeName = get_challenge_name()

    # get path to original images
    originalImages = get_source_image_path(target="original")

    # get path to comparative images
    comparativeImages = get_source_image_path(target="comparative")

    # filter originals ans comparatives if they are in the same folder
    regMatcher = r"_[SD]\."
    originalImages = [
        imgPath for imgPath in originalImages
        if not re.search(regMatcher, imgPath)
    ]
    comparativeImages = [
        imgPath for imgPath in comparativeImages
        if re.search(regMatcher, imgPath)
    ]

    # check whether every original has a comparative
    originalImageNamesSet = set([
        utils.get_filename_without_extension(imgPath)
        for imgPath in originalImages
    ])
    comparativeImageNames = [
        utils.get_filename_without_extension(imgPath)
        for imgPath in comparativeImages
    ]
    targetDecisions = [
        True if name[-1] == "S" else False for name in comparativeImageNames
    ]
    comparativeImageNamesSet = set(
        [name[:-2] for name in comparativeImageNames])

    if (originalImageNamesSet ^ comparativeImageNamesSet):
        print(originalImageNamesSet)
        print(comparativeImageNamesSet)
        print(
            "ERROR: We can not match all comparative images with original images.\nPlease check the amount of images and whether\nevery image has its counterpart and vice versa...Exit"
        )
        sys.exit(1)

    while True:
        print(
            '\nSpecify additional metadata in form of a python dictionary {"attribute": "value"}.'
        )
        attributesString = input("Attributes [default {}]: ")
        try:
            if attributesString == "":
                attributesDict = {}
                break
            attributesDict = ast.literal_eval(attributesString)
            if type(attributesDict) is dict:
                break
            print(
                "\nThe input is no python dictionary.\nInsert a dictionary or leave it blank to finish."
            )
        except:
            print("ERROR: The input is no valid python code.")

    # save challenge object in db
    tw.add_challenge(challengeName, originalImages, comparativeImages,
                     targetDecisions, attributesDict)

    print("Challenge %s was added ..." % challengeName)
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
    }