示例#1
0
def showSobelLaplacian(segmentation_type, input_img):
    if (segmentation_type != "none"):
        img = cv2.imread(input_img, 0)  # uint8 image in grayscale
    else:
        img = cv2.imread(input_img)

    results = list()
    img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)
    results.append(img)
    if (segmentation_type == "otsu"):
        segmented_img = processedSegmentation.imgSegmentation(img)
    elif (segmentation_type == "gauss"):
        segmented_img = processedSegmentation.adaptiveSegmentationGaussian(img)
    elif (segmentation_type == "mean"):
        segmented_img = processedSegmentation.adaptiveSegmentationMean(img)

    if (segmentation_type != "none"):
        cv2.imwrite('./processedImg/segmented_img.jpg', segmented_img)
        img = cv2.imread('./processedImg/segmented_img.jpg')
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    laplacian = cv2.Laplacian(img,
                              cv2.CV_64F)  # processed with Laplacian operator
    cv2.imwrite("./processedImg/laplacian_img.jpg", laplacian)
    laplacian_img = cv2.imread("./processedImg/laplacian_img.jpg", 0)
    results.append(laplacian_img)
    sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0,
                       ksize=5)  # processed with Sobel on x-axis
    cv2.imwrite("./processedImg/sobelx_img.jpg", sobelx)
    sobelx_img = cv2.imread("./processedImg/sobelx_img.jpg", 0)
    results.append(sobelx_img)
    sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1,
                       ksize=5)  # processed with Sobel on y-axis
    cv2.imwrite("./processedImg/sobely_img.jpg", sobely)
    sobely_img = cv2.imread("./processedImg/sobely_img.jpg", 0)
    results.append(sobely_img)

    titles = [
        'Original normalized image', 'Applied Laplacian operator',
        'Applied Sobel operator of x axis', 'Applied Sobel operator of y axis'
    ]

    fig = plt.figure(figsize=(11, 11))
    i = 0
    for a in results:
        ax = fig.add_subplot(2, 2, i + 1)
        ax.imshow(a, cmap='gray')
        ax.set_title(titles[i], fontsize=10)
        ax.set_xticks([])
        ax.set_yticks([])
        i = i + 1

    fig.tight_layout()
    plt.show()

    return
示例#2
0
def showLBP(segmentation_type, input_img):
    if (segmentation_type != "none"):
        img = cv2.imread(input_img, 0)  # uint8 image in grayscale
    else:
        img = cv2.imread(input_img)
#img = cv2.resize(img,(400,400)) # resize of image
    img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)  # normalize image
    #segmented_img = adaptiveSegmentationMean(img)
    if (segmentation_type == "otsu"):
        segmented_img = processedSegmentation.imgSegmentation(img)
    elif (segmentation_type == "gauss"):
        segmented_img = processedSegmentation.adaptiveSegmentationGaussian(img)
    elif (segmentation_type == "mean"):
        segmented_img = processedSegmentation.adaptiveSegmentationMean(img)
#cv2.imshow('Segmented image', segmented_img)
    if (segmentation_type != "none"):
        cv2.imwrite('./processedImg/segmented_img.jpg', segmented_img)
        img = cv2.imread('./processedImg/segmented_img.jpg')

    height, width, channel = img.shape
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    lbp_image = np.zeros((height, width, 3), np.uint8)

    # processing LBP algorithm
    lbp_values = []
    for i in range(0, height):
        for j in range(0, width):
            lbp_image[i, j] = processLBP(img_gray, i, j, lbp_values)

    cv2.imshow("lbp image", lbp_image)
    hist_lbp = cv2.calcHist([lbp_image], [0], None, [256], [0, 256])

    figure = plt.figure(figsize=(30, 30))
    image_plot = figure.add_subplot(1, 2, 1)
    image_plot.imshow(lbp_image)
    image_plot.set_xticks([])
    image_plot.set_yticks([])
    image_plot.set_title("LBP image", fontsize=10)
    current_plot = figure.add_subplot(1, 2, 2)
    current_plot.plot(hist_lbp, color=(0, 0, 0.2))
    #current_plot.set_xlim([0,260])
    current_plot.set_xlim([0, 256])
    current_plot.set_ylim([0, 6000])
    current_plot.set_title("LBP histogram", fontsize=10)
    current_plot.set_xlabel("Intensity")
    current_plot.set_ylabel("Count of pixels")
    ytick_list = [int(i) for i in current_plot.get_yticks()]
    current_plot.set_yticklabels(ytick_list, rotation=90)
    plt.show()

    cv2.waitKey(0)
    cv2.destroyAllWindows()

    return
示例#3
0
def showWavelet(segmentation_type, input_img, wavelet_type):
    if (segmentation_type != "none"):
        img = cv2.imread(input_img, 0)  # uint8 image in grayscale
    else:
        img = cv2.imread(input_img)

    img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)  # normalize image

    # choose type of segmentation
    if (segmentation_type == "otsu"):
        segmented_img = processedSegmentation.imgSegmentation(img)
    elif (segmentation_type == "gauss"):
        segmented_img = processedSegmentation.adaptiveSegmentationGaussian(img)
    elif (segmentation_type == "mean"):
        segmented_img = processedSegmentation.adaptiveSegmentationMean(img)

    if (segmentation_type != "none"):
        cv2.imwrite('./processedImg/segmented_img.jpg', segmented_img)
        img = cv2.imread('./processedImg/segmented_img.jpg')

    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Convert to float32 for more resolution for use with pywt
    img = np.float32(img)
    img /= 255

    titles = [
        'Approximation (LL)', ' Horizontal detail (LH)',
        'Vertical detail (HL)', 'Diagonal detail (HH)'
    ]
    coeffs2 = pywt.dwt2(img, wavelet_type)
    LL, (LH, HL, HH) = coeffs2
    fig = plt.figure(figsize=(11, 11))
    for i, a in enumerate([LL, LH, HL, HH]):
        ax = fig.add_subplot(2, 2, i + 1)
        ax.imshow(a, interpolation="nearest", cmap=plt.cm.gray)
        ax.set_title(titles[i], fontsize=10)
        ax.set_xticks([])
        ax.set_yticks([])

    fig.tight_layout()
    plt.show()
    return
示例#4
0
def vectorLBP(segmentation_type, color_type):
    # IMAGES FOR TRAINING

    # folders of trained and tested images based on chosen argument of user
    if (color_type == "b"):  # blue images
        path_training = './dataset/blueTrain/*'
        path_testing = './dataset/blueTest/*'
    elif (color_type == "g"):  # green images
        path_training = './dataset/greenTrain/*'
        path_testing = './dataset/greenTest/*'
    elif (color_type == "r"):  # red images
        path_training = './dataset/redTrain/*'
        path_testing = './dataset/redTest/*'
    elif (color_type == "all"):  # all images
        path_training = './dataset/allTrain/*'
        path_testing = './dataset/allTest/*'

    # csv files for trained images
    f = open("./csvFiles/LBPtrained.csv", "w+")
    g = open("./csvFiles/LBPtrainedResult.csv", "w+")
    for file in glob.glob(path_training):
        file_substr = file.split('/')[-1]  # get name of processed file
        print(file_substr)

        img = cv2.imread(file, 0)  # uint8 image in grayscale
        img = cv2.normalize(img, None, 0, 255,
                            cv2.NORM_MINMAX)  # normalize image

        # decide about type of segmentation
        if (segmentation_type == "otsu"):
            segmented_img = processedSegmentation.imgSegmentation(img)
        elif (segmentation_type == "gauss"):
            segmented_img = processedSegmentation.adaptiveSegmentationGaussian(
                img)
        elif (segmentation_type == "mean"):
            segmented_img = processedSegmentation.adaptiveSegmentationMean(img)

        # save, load segmented image and get their properties
        cv2.imwrite('./processedImg/segmented_img.jpg', segmented_img)
        img = cv2.imread('./processedImg/segmented_img.jpg')
        height, width, channel = img.shape
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        lbp_image = np.zeros((height, width, 3), np.uint8)

        # processing LBP algorithm
        lbp_values = []
        for i in range(0, height):
            for j in range(0, width):
                lbp_image[i, j] = processLBP(img_gray, i, j, lbp_values)

        hist_lbp = cv2.calcHist([lbp_image], [0], None, [256], [0, 256])
        histogram_list = list()
        histogram_list = hist_lbp
        sum_hist1 = 0
        sum_hist2 = 0
        sum_hist3 = 0
        sum_hist4 = 0

        # get values from LBP histogram
        for i in range(0, 64):
            hist_value = histogram_list[i]
            hist_value_n = str(hist_value[0])
            sum_hist1 = sum_hist1 + float(hist_value_n)

        for i in range(64, 128):
            hist_value = histogram_list[i]
            hist_value_n = str(hist_value[0])
            sum_hist2 = sum_hist2 + float(hist_value_n)

        for i in range(128, 192):
            hist_value = histogram_list[i]
            hist_value_n = str(hist_value[0])
            sum_hist3 = sum_hist3 + float(hist_value_n)

        for i in range(192, 256):
            hist_value = histogram_list[i]
            hist_value_n = str(hist_value[0])
            sum_hist4 = sum_hist4 + float(hist_value_n)

        # transform to more proper range for classification
        sum_hist1_div = sum_hist1 / 1000000
        sum_hist2_div = sum_hist2 / 1000000
        sum_hist3_div = sum_hist3 / 1000000
        sum_hist4_div = sum_hist4 / 1000000

        img = cv2.imread('./processedImg/segmented_img.jpg',
                         0)  # load input grayscale img

        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        # GLCM matrix characteristics - contrast, homogeinity, energy, correlation
        contrast = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast)
        contrast_float = float(contrast)
        contrast_str = contrast_float / 10  # transform to more proper range for classification

        homogeneity = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity)
        homogeneity_float = float(homogeneity)
        homogeneity_str = homogeneity_float / 10

        energy = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy)
        energy_float = float(energy)
        energy_str = energy_float / 10

        correlation = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation)
        correlation_float = float(correlation)
        correlation_str = correlation_float / 10

        saved_str = str(sum_hist1_div) + ", " + str(
            sum_hist2_div) + ", " + str(sum_hist3_div) + ", " + str(
                sum_hist4_div) + ", " + str(contrast_str) + ", " + str(
                    homogeneity_str) + ", " + str(energy_str) + ", " + str(
                        correlation_str) + "\n"
        f.write(saved_str)  # write vector to file

        # save known result of image based on its file name
        if ("fake" in file_substr):
            print("This is known FAKE image for training")
            g.write("0\n")
        elif ("live" in file_substr):
            print("This is known LIVE image for training")
            g.write("1\n")

        print()

# IMAGES FOR TESTING

    h = open("./csvFiles/LBPtested.csv", "w+")  # csv file for tested images
    for file in glob.glob(path_testing):
        file_substr = file.split('/')[-1]  # get name of processed file
        print(file_substr)

        img = cv2.imread(file, 0)  # uint8 image in grayscale
        img = cv2.normalize(img, None, 0, 255,
                            cv2.NORM_MINMAX)  # normalized image

        # decide about type of segmentation
        if (segmentation_type == "otsu"):
            segmented_img = processedSegmentation.imgSegmentation(img)
        elif (segmentation_type == "gauss"):
            segmented_img = processedSegmentation.adaptiveSegmentationGaussian(
                img)
        elif (segmentation_type == "mean"):
            segmented_img = processedSegmentation.adaptiveSegmentationMean(img)

        # save, load segmented image and get their properties
        cv2.imwrite('./processedImg/segmented_img.jpg', segmented_img)
        img = cv2.imread('./processedImg/segmented_img.jpg')
        height, width, channel = img.shape
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        lbp_image = np.zeros((height, width, 3), np.uint8)

        # processing LBP algorithm
        lbp_values = []
        for i in range(0, height):
            for j in range(0, width):
                lbp_image[i, j] = processLBP(img_gray, i, j, lbp_values)

        hist_lbp = cv2.calcHist([lbp_image], [0], None, [256], [0, 256])

        histogram_list = list()
        histogram_list = hist_lbp
        sum_hist1 = 0
        sum_hist2 = 0
        sum_hist3 = 0
        sum_hist4 = 0

        # get values from LBP histogram
        for i in range(0, 64):
            hist_value = histogram_list[i]
            hist_value_n = str(hist_value[0])
            sum_hist1 = sum_hist1 + float(hist_value_n)

        for i in range(64, 128):
            hist_value = histogram_list[i]
            hist_value_n = str(hist_value[0])
            sum_hist2 = sum_hist2 + float(hist_value_n)

        for i in range(128, 192):
            hist_value = histogram_list[i]
            hist_value_n = str(hist_value[0])
            sum_hist3 = sum_hist3 + float(hist_value_n)

        for i in range(192, 256):
            hist_value = histogram_list[i]
            hist_value_n = str(hist_value[0])
            sum_hist4 = sum_hist4 + float(hist_value_n)

        # transform to more proper range for classification
        sum_hist1_div = sum_hist1 / 1000000
        sum_hist2_div = sum_hist2 / 1000000
        sum_hist3_div = sum_hist3 / 1000000
        sum_hist4_div = sum_hist4 / 1000000

        img = cv2.imread('./processedImg/segmented_img.jpg', 0)

        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        # GLCM matrix characteristics - contrast, homogeinity, energy, correlation
        contrast = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast)
        contrast_float = float(contrast)
        contrast_str = contrast_float / 10  # transform to more proper range for classification

        homogeneity = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity)
        homogeneity_float = float(homogeneity)
        homogeneity_str = homogeneity_float / 10

        energy = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy)
        energy_float = float(energy)
        energy_str = energy_float / 10

        correlation = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation)
        correlation_float = float(correlation)
        correlation_str = correlation_float / 10

        saved_str = file_substr + ", " + str(sum_hist1_div) + ", " + str(
            sum_hist2_div) + ", " + str(sum_hist3_div) + ", " + str(
                sum_hist4_div) + ", " + str(contrast_str) + ", " + str(
                    homogeneity_str) + ", " + str(energy_str) + ", " + str(
                        correlation_str) + "\n"
        print("This image will be used for liveness prediction")
        h.write(saved_str)  # write vector to file
        print()

    # properly close all csv files
    f.close()
    g.close()
    h.close()

    return
示例#5
0
def vectorSobelLaplacian(color_type):
    # IMAGES FOR TRAINING

    # folders of trained and tested images based on chosen argument of user
    if (color_type == "b"):  # blue images
        path_training = './dataset/blueTrain/*'
        path_testing = './dataset/blueTest/*'
    elif (color_type == "g"):  # green images
        path_training = './dataset/greenTrain/*'
        path_testing = './dataset/greenTest/*'
    elif (color_type == "r"):  # red images
        path_training = './dataset/redTrain/*'
        path_testing = './dataset/redTest/*'
    elif (color_type == "all"):  # all images
        path_training = './dataset/allTrain/*'
        path_testing = './dataset/allTest/*'

    # csv files for trained images
    f = open("./csvFiles/SLtrained.csv", "w+")
    g = open("./csvFiles/SLtrainedResult.csv", "w+")
    for file in glob.glob(path_training):
        img = cv2.imread(file, 0)  # uint8 image in grayscale
        img = cv2.normalize(img, None, 0, 255,
                            cv2.NORM_MINMAX)  # normalize image
        segmented_img = processedSegmentation.imgSegmentation(img)
        cv2.imwrite('./processedImg/segmented_img.jpg', segmented_img)

        image = cv2.imread('./processedImg/segmented_img.jpg')
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        laplacian = cv2.Laplacian(
            image, cv2.CV_64F
        )  # get result of image processing with Laplacian operator
        cv2.imwrite("./processedImg/laplacian_img.jpg", laplacian)
        sobelx = cv2.Sobel(
            image, cv2.CV_64F, 1, 0, ksize=5
        )  # get result of x-axis for image processed with Sobel operator
        cv2.imwrite("./processedImg/sobelx_img.jpg", sobelx)
        sobely = cv2.Sobel(
            image, cv2.CV_64F, 0, 1, ksize=5
        )  # get result of y-axis for image processed with Sobel operator
        cv2.imwrite("./processedImg/sobely_img.jpg", sobelx)

        # PROCESS LAPLACIAN IMAGE
        img = cv2.imread('./processedImg/laplacian_img.jpg', 0)
        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        # GLCM matrix characteristics - contrast, homogeinity, energy, correlation
        contrast = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast)
        contrast_float = float(contrast)
        contrast_str = contrast_float / 10

        homogeneity = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity)
        homogeneity_float = float(homogeneity)
        homogeneity_str = homogeneity_float / 10

        energy = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy)
        energy_float = float(energy)
        energy_str = energy_float / 10

        correlation = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation)
        correlation_float = float(correlation)
        correlation_str = correlation_float / 10

        # PROCESS SOBEL ON X-AXIS IMAGE
        img = cv2.imread('./processedImg/sobelx_img.jpg', 0)
        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        contrast2 = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast2)
        contrast_float2 = float(contrast2)
        contrast_str2 = contrast_float2 / 10

        homogeneity2 = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity2)
        homogeneity_float2 = float(homogeneity2)
        homogeneity_str2 = homogeneity_float2 / 10

        energy2 = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy2)
        energy_float2 = float(energy2)
        energy_str2 = energy_float2 / 10

        correlation2 = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation2)
        correlation_float2 = float(correlation2)
        correlation_str2 = correlation_float2 / 10

        # PROCESS SOBEL ON Y-AXIS IMAGE
        img = cv2.imread('./processedImg/sobely_img.jpg', 0)
        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        contrast3 = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast3)
        contrast_float3 = float(contrast3)
        contrast_str3 = contrast_float3 / 10

        homogeneity3 = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity3)
        homogeneity_float3 = float(homogeneity3)
        homogeneity_str3 = homogeneity_float3 / 10

        energy3 = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy3)
        energy_float3 = float(energy3)
        energy_str3 = energy_float3 / 10

        correlation3 = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation3)
        correlation_float3 = float(correlation3)
        correlation_str3 = correlation_float3 / 10

        saved_str = (str(contrast_str) + ", " + str(homogeneity_str) + ", " +
                     str(energy_str) + ", " + str(correlation_str) + ", " +
                     str(contrast_str2) + ", " + str(homogeneity_str2) + ", " +
                     str(energy_str2) + ", " + str(correlation_str2) + ", " +
                     str(contrast_str3) + ", " + str(homogeneity_str3) + ", " +
                     str(energy_str3) + ", " + str(correlation_str3) + "\n")
        print(saved_str)

        file_substr = file.split('/')[-1]

        f.write(saved_str)  # write vector to file

        # save known result of image based on its file name
        if ("fake" in file_substr):
            print("This is FAKE image.")
            g.write("0\n")
        elif ("live" in file_substr):
            print("This is LIVE image.")
            g.write("1\n")

# IMAGES FOR TESTING
    h = open("./csvFiles/SLtested.csv", "w+")  # csv file for tested images
    for file in glob.glob(path_testing):
        img = cv2.imread(file, 0)  # uint8 image in grayscale
        img = cv2.normalize(img, None, 0, 255,
                            cv2.NORM_MINMAX)  # normalize image
        segmented_img = processedSegmentation.imgSegmentation(img)
        cv2.imwrite('./processedImg/segmented_img.jpg', segmented_img)

        image = cv2.imread('./processedImg/segmented_img.jpg')
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        laplacian = cv2.Laplacian(
            image, cv2.CV_64F
        )  # get result of image processing with Laplacian operator
        cv2.imwrite("./processedImg/laplacian_img.jpg", laplacian)
        sobelx = cv2.Sobel(
            image, cv2.CV_64F, 1, 0, ksize=5
        )  # get result of x-axis for image processed with Sobel operator
        cv2.imwrite("./processedImg/sobelx_img.jpg", sobelx)
        sobely = cv2.Sobel(
            image, cv2.CV_64F, 0, 1, ksize=5
        )  # get result of y-axis for image processed with Sobel operator
        cv2.imwrite("./processedImg/sobely_img.jpg", sobelx)

        # PROCESS LAPLACIAN IMAGE
        img = cv2.imread('./processedImg/laplacian_img.jpg', 0)
        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        # GLCM matrix characteristics - contrast, homogeinity, energy, correlation
        contrast = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast)
        contrast_float = float(contrast)
        contrast_str = contrast_float / 10

        homogeneity = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity)
        homogeneity_float = float(homogeneity)
        homogeneity_str = homogeneity_float / 10

        energy = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy)
        energy_float = float(energy)
        energy_str = energy_float / 10

        correlation = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation)
        correlation_float = float(correlation)
        correlation_str = correlation_float / 10

        # PROCESS SOBEL ON X-AXIS IMAGE
        img = cv2.imread('./processedImg/sobelx_img.jpg', 0)
        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        contrast2 = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast2)
        contrast_float2 = float(contrast2)
        contrast_str2 = contrast_float2 / 10

        homogeneity2 = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity2)
        homogeneity_float2 = float(homogeneity2)
        homogeneity_str2 = homogeneity_float2 / 10

        energy2 = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy2)
        energy_float2 = float(energy2)
        energy_str2 = energy_float2 / 10

        correlation2 = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation2)
        correlation_float2 = float(correlation2)
        correlation_str2 = correlation_float2 / 10

        # PROCESS SOBEL ON Y-AXIS IMAGE
        img = cv2.imread('./processedImg/sobely_img.jpg', 0)
        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        contrast3 = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast3)
        contrast_float3 = float(contrast3)
        contrast_str3 = contrast_float3 / 10

        homogeneity3 = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity3)
        homogeneity_float3 = float(homogeneity3)
        homogeneity_str3 = homogeneity_float3 / 10

        energy3 = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy3)
        energy_float3 = float(energy3)
        energy_str3 = energy_float3 / 10

        correlation3 = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation3)
        correlation_float3 = float(correlation3)
        correlation_str3 = correlation_float3 / 10

        file_substr = file.split('/')[-1]

        saved_str = (file_substr + ", " + str(contrast_str) + ", " +
                     str(homogeneity_str) + ", " + str(energy_str) + ", " +
                     str(correlation_str) + ", " + str(contrast_str2) + ", " +
                     str(homogeneity_str2) + ", " + str(energy_str2) + ", " +
                     str(correlation_str2) + ", " + str(contrast_str3) + ", " +
                     str(homogeneity_str3) + ", " + str(energy_str3) + ", " +
                     str(correlation_str3) + "\n")
        print(saved_str)

        h.write(saved_str)  # write vector to file

    # properly close all csv files
    f.close()
    g.close()
    h.close()

    return
示例#6
0
def vectorWavelet(segmentation_type, color_type, wavelet_type):
    # IMAGES FOR TRAINING

    # csv files for trained images
    f = open("./csvFiles/WaveletTrained.csv", "w+")
    g = open("./csvFiles/WaveletTrainedResult.csv", "w+")

    # folders of trained and tested images based on chosen argument of user
    if (color_type == "b"):  # blue images
        path_training = './dataset/blueTrain/*'
        path_testing = './dataset/blueTest/*'
    elif (color_type == "g"):  # green images
        path_training = './dataset/greenTrain/*'
        path_testing = './dataset/greenTest/*'
    elif (color_type == "r"):  # red images
        path_training = './dataset/redTrain/*'
        path_testing = './dataset/redTest/*'
    elif (color_type == "all"):  # all images
        path_training = './dataset/allTrain/*'
        path_testing = './dataset/allTest/*'

    for file in glob.glob(path_training):
        img = cv2.imread(file, 0)  # uint8 image in grayscale
        img = cv2.normalize(img, None, 0, 255,
                            cv2.NORM_MINMAX)  # normalize image

        if (segmentation_type == "otsu"):
            segmented_img = processedSegmentation.imgSegmentation(img)
        elif (segmentation_type == "gauss"):
            segmented_img = processedSegmentation.adaptiveSegmentationGaussian(
                img)
        elif (segmentation_type == "mean"):
            segmented_img = processedSegmentation.adaptiveSegmentationMean(img)

        cv2.imwrite('./processedImg/segmented_img.jpg', segmented_img)

        image = cv2.imread('./processedImg/segmented_img.jpg')
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # Convert to float32 for more resolution for use with pywt
        image = np.float32(image)
        image /= 255

        coeffs2 = pywt.dwt2(image, wavelet_type)
        LL, (LH, HL, HH) = coeffs2

        # gaining LH, HL and HH image
        plt.imshow(LH, interpolation="nearest", cmap=plt.cm.gray)
        plt.axis('off')
        plt.savefig('./processedImg/LHimg.png',
                    transparent=True,
                    bbox_inches='tight',
                    pad_inches=0)

        plt.imshow(HL, interpolation="nearest", cmap=plt.cm.gray)
        plt.axis('off')
        plt.savefig('./processedImg/HLimg.png',
                    transparent=True,
                    bbox_inches='tight',
                    pad_inches=0)

        plt.imshow(HH, interpolation="nearest", cmap=plt.cm.gray)
        plt.axis('off')
        plt.savefig('./processedImg/HHimg.png',
                    transparent=True,
                    bbox_inches='tight',
                    pad_inches=0)

        # PROCESS LH IMAGE - Horizontal detail
        img = cv2.imread('./processedImg/LHimg.png', 0)
        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        # GLCM matrix characteristics - contrast, homogeinity, energy, correlation
        contrast2 = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast2)
        contrast_float2 = float(contrast2)
        contrast_str2 = contrast_float2 / 10

        homogeneity2 = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity2)
        homogeneity_float2 = float(homogeneity2)
        homogeneity_str2 = homogeneity_float2 / 10

        energy2 = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy2)
        energy_float2 = float(energy2)
        energy_str2 = energy_float2 / 10

        correlation2 = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation2)
        correlation_float2 = float(correlation2)
        correlation_str2 = correlation_float2 / 10

        # PROCESS HL IMAGE - Vertical detail
        img = cv2.imread('./processedImg/HLimg.png', 0)
        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        contrast3 = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast3)
        contrast_float3 = float(contrast3)
        contrast_str3 = contrast_float3 / 10

        homogeneity3 = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity3)
        homogeneity_float3 = float(homogeneity3)
        homogeneity_str3 = homogeneity_float3 / 10

        energy3 = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy3)
        energy_float3 = float(energy3)
        energy_str3 = energy_float3 / 10

        correlation3 = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation3)
        correlation_float3 = float(correlation3)
        correlation_str3 = correlation_float3 / 10

        # PROCESS HH IMAGE - Diagonal detail
        img = cv2.imread('./processedImg/HHimg.png', 0)
        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        contrast4 = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast4)
        contrast_float4 = float(contrast4)
        contrast_str4 = contrast_float4 / 10

        homogeneity4 = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity4)
        homogeneity_float4 = float(homogeneity4)
        homogeneity_str4 = homogeneity_float4 / 10

        energy4 = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy4)
        energy_float4 = float(energy4)
        energy_str4 = energy_float4 / 10

        correlation4 = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation4)
        correlation_float4 = float(correlation4)
        correlation_str4 = correlation_float4 / 10

        saved_str = (str(contrast_str2) + ", " + str(homogeneity_str2) + ", " +
                     str(energy_str2) + ", " + str(correlation_str2) + ", " +
                     str(contrast_str3) + ", " + str(homogeneity_str3) + ", " +
                     str(energy_str3) + ", " + str(correlation_str3) + ", " +
                     str(contrast_str4) + ", " + str(homogeneity_str4) + ", " +
                     str(energy_str4) + ", " + str(correlation_str4) + "\n")
        print(saved_str)

        file_substr = file.split('/')[-1]

        f.write(saved_str)  # write vector to file

        # save known result of image based on its file name
        if ("fake" in file_substr):
            print("This is FAKE image.")
            g.write("0\n")
        elif ("live" in file_substr):
            print("This is LIVE image.")
            g.write("1\n")

# IMAGES FOR TESTING

    h = open("./csvFiles/WaveletTested.csv",
             "w+")  # csv file for tested images
    for file in glob.glob(path_testing):
        img = cv2.imread(file, 0)  # uint8 image in grayscale
        img = cv2.normalize(img, None, 0, 255,
                            cv2.NORM_MINMAX)  # normalize image

        if (segmentation_type == "otsu"):
            segmented_img = processedSegmentation.imgSegmentation(img)
        elif (segmentation_type == "gauss"):
            segmented_img = processedSegmentation.adaptiveSegmentationGaussian(
                img)
        elif (segmentation_type == "mean"):
            segmented_img = processedSegmentation.adaptiveSegmentationMean(img)

        cv2.imwrite('./processedImg/segmented_img.jpg', segmented_img)
        image = cv2.imread('./processedImg/segmented_img.jpg')
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # Convert to float for more resolution for use with pywt
        image = np.float32(image)
        image /= 255

        coeffs2 = pywt.dwt2(image, wavelet_type)
        LL, (LH, HL, HH) = coeffs2

        plt.imshow(LH, interpolation="nearest", cmap=plt.cm.gray)
        plt.axis('off')
        plt.savefig('./processedImg/LHimg.png',
                    transparent=True,
                    bbox_inches='tight',
                    pad_inches=0)

        plt.imshow(HL, interpolation="nearest", cmap=plt.cm.gray)
        plt.axis('off')
        plt.savefig('./processedImg/HLimg.png',
                    transparent=True,
                    bbox_inches='tight',
                    pad_inches=0)

        plt.imshow(HH, interpolation="nearest", cmap=plt.cm.gray)
        plt.axis('off')
        plt.savefig('./processedImg/HHimg.png',
                    transparent=True,
                    bbox_inches='tight',
                    pad_inches=0)

        # PROCESS LH IMAGE
        img = cv2.imread('./processedImg/LHimg.png', 0)
        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        # GLCM matrix characteristics - contrast, homogeinity, energy, correlation
        contrast2 = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast2)
        contrast_float2 = float(contrast2)
        contrast_str2 = contrast_float2 / 10

        homogeneity2 = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity2)
        homogeneity_float2 = float(homogeneity2)
        homogeneity_str2 = homogeneity_float2 / 10

        energy2 = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy2)
        energy_float2 = float(energy2)
        energy_str2 = energy_float2 / 10

        correlation2 = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation2)
        correlation_float2 = float(correlation2)
        correlation_str2 = correlation_float2 / 10

        # PROCESS HL IMAGE
        img = cv2.imread('./processedImg/HLimg.png', 0)
        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        contrast3 = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast3)
        contrast_float3 = float(contrast3)
        contrast_str3 = contrast_float3 / 10

        homogeneity3 = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity3)
        homogeneity_float3 = float(homogeneity3)
        homogeneity_str3 = homogeneity_float3 / 10

        energy3 = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy3)
        energy_float3 = float(energy3)
        energy_str3 = energy_float3 / 10

        correlation3 = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation3)
        correlation_float3 = float(correlation3)
        correlation_str3 = correlation_float3 / 10

        # PROCESS HH IMAGE
        img = cv2.imread('./processedImg/HHimg.png', 0)
        image = img_as_ubyte(img)

        bins = np.array([
            0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
            240, 255
        ])  #16-bit
        inds = np.digitize(image, bins)

        max_value = inds.max() + 1
        matrix_coocurrence = greycomatrix(inds, [1], [0],
                                          levels=max_value,
                                          normed=False,
                                          symmetric=False)

        contrast4 = greycoprops(matrix_coocurrence, 'contrast')
        print("Contrast:")
        print(contrast4)
        contrast_float4 = float(contrast4)
        contrast_str4 = contrast_float4 / 10

        homogeneity4 = greycoprops(matrix_coocurrence, 'homogeneity')
        print("Homogeneity:")
        print(homogeneity4)
        homogeneity_float4 = float(homogeneity4)
        homogeneity_str4 = homogeneity_float4 / 10

        energy4 = greycoprops(matrix_coocurrence, 'energy')
        print("Energy:")
        print(energy4)
        energy_float4 = float(energy4)
        energy_str4 = energy_float4 / 10

        correlation4 = greycoprops(matrix_coocurrence, 'correlation')
        print("Correlation:")
        print(correlation4)
        correlation_float4 = float(correlation4)
        correlation_str4 = correlation_float4 / 10

        file_substr = file.split('/')[-1]

        saved_str = (file_substr + ", " + str(contrast_str2) + ", " +
                     str(homogeneity_str2) + ", " + str(energy_str2) + ", " +
                     str(correlation_str2) + ", " + str(contrast_str3) + ", " +
                     str(homogeneity_str3) + ", " + str(energy_str3) + ", " +
                     str(correlation_str3) + ", " + str(contrast_str4) + ", " +
                     str(homogeneity_str4) + ", " + str(energy_str4) + ", " +
                     str(correlation_str4) + "\n")
        print(saved_str)

        h.write(saved_str)  # write vector to file

    # properly close all csv files
    f.close()
    g.close()
    h.close()

    return