예제 #1
0
def median_filter(image, kernels, save, dpi, num):
    image = util.load_image_RGB(image)
    kernels = json.loads(kernels)

    # Initialize the median_images as list. Values are assigned on the for-loop
    median_images = []
    titles_images = []
    for k in kernels:
        median_images.append(cv.medianBlur(image, k))
        titles_images.append(f"Kernel {k}x{k}")

    # Copy the arrays with the images generated in the for-loop and adds the
    # original noisy image for comparison. Also copies and adds the titles.
    plot_images = median_images
    plot_images.insert(0, image)
    plot_titles = titles_images
    plot_titles.insert(0, "Noisy Image")

    # Plots the images.
    fig = util.plotImages(plot_images,
                          plot_titles,
                          show=True,
                          main_title="Median Filter - cv.medianBlur",
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #2
0
def original_pictures(orig, noisy, save, dpi, num):
    orig = util.load_image_RGB(orig)
    noisy = util.load_image_RGB(noisy)

    fig = util.plotImages([orig, noisy], ["Original", "Noisy"],
                          show=True,
                          main_title="Loaded Images",
                          cols=2,
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #3
0
def harris_detector_bsize(image, bsizes, ksize, k, threshold, filter_params,
                          save, dpi, num):
    image = util.load_image_RGB(image)
    bsizes = json.loads(bsizes)
    bsizes = np.rint(bsizes).astype(int)
    filter_params = json.loads(filter_params)

    if len(filter_params) == 2:
        print("Applying Gaussian Filter")
        image = cv.GaussianBlur(src=image,
                                ksize=(filter_params[0], filter_params[1]),
                                sigmaX=0,
                                sigmaY=0)

    gray_image = cv.cvtColor(src=image, code=cv.COLOR_RGB2GRAY)

    harris_images_bsize = []
    harris_images_titles = []
    for bsize in bsizes:
        harris_image = np.copy(image)
        mask = cv.cornerHarris(src=gray_image,
                               blockSize=bsize,
                               ksize=ksize,
                               k=k)

        harris_image[mask > threshold * mask.max()] = [255, 0, 0]
        harris_images_bsize.append(harris_image)

        harris_images_titles.append(f"block size = {bsize}")

    harris_images = harris_images_bsize
    harris_images.insert(0, image)
    titles_images = harris_images_titles
    titles_images.insert(0, "Orig Image")

    # Convert from Float 64 to Unsigned Int 8
    # Also needs to be converted from np.array to list
    harris_images = list(np.uint8(np.abs(harris_images)))

    # Plots the images.
    fig = util.plotImages(
        harris_images,
        titles_images,
        show=True,
        main_title="Harris Corner Detectorn - cv.cornerHarris"
        f"\nsobel aperture = {ksize}"
        f"\nharris parameter = {k}",
        cmap="gray",
        cols=2,
        num=num,
        dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #4
0
def canny_filter(image, minval, maxval, ksize, filter_params, save, dpi, num):
    image = util.load_image_RGB(image)
    filter_params = json.loads(filter_params)

    if len(filter_params) == 2:
        print("Applying Gaussian Filter")
        image = cv.GaussianBlur(src=image,
                                ksize=(filter_params[0], filter_params[1]),
                                sigmaX=0,
                                sigmaY=0)
    # Best bilateral_params = (6, 200, 20)
    elif len(filter_params) == 3:
        print("Applying Bilateral Filter")
        image = cv.bilateralFilter(src=image,
                                   d=filter_params[0],
                                   sigmaColor=filter_params[1],
                                   sigmaSpace=filter_params[2])

    image = cv.cvtColor(src=image, code=cv.COLOR_RGB2GRAY)

    minVal = np.uint8(np.round(np.max(image) * minval))
    maxVal = np.uint8(np.round(np.max(image) * maxval))

    # Aperture size should be odd between 3 and 7 in function
    canny_image = cv.Canny(image=image,
                           threshold1=minVal,
                           threshold2=maxVal,
                           apertureSize=ksize)

    canny_images = [image, canny_image]
    titles_images = [
        "Orig Image", f"Canny\nminVal = {minVal}, maxVal = {maxVal}"
    ]

    # Plots the images.
    fig = util.plotImages(canny_images,
                          titles_images,
                          show=True,
                          main_title="Canny Filter - cv.Canny",
                          cmap="gray",
                          cols=2,
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #5
0
def roberts_filter(image, filter_params, save, dpi, num):
    image = util.load_image_RGB(image)
    filter_params = json.loads(filter_params)

    if len(filter_params) == 2:
        print("Applying Gaussian Filter")
        image = cv.GaussianBlur(src=image,
                                ksize=(filter_params[0], filter_params[1]),
                                sigmaX=0,
                                sigmaY=0)
    # Best bilateral_params = (6, 200, 20)
    elif len(filter_params) == 3:
        print("Applying Bilateral Filter")
        image = cv.bilateralFilter(src=image,
                                   d=filter_params[0],
                                   sigmaColor=filter_params[1],
                                   sigmaSpace=filter_params[2])

    image = cv.cvtColor(src=image, code=cv.COLOR_RGB2GRAY)

    kernel_x = np.array([[1, 0], [0, -1]])
    kernel_y = np.array([[0, 1], [-1, 0]])

    roberts_x = cv.filter2D(src=image, ddepth=cv.CV_64F, kernel=kernel_x)
    roberts_y = cv.filter2D(src=image, ddepth=cv.CV_64F, kernel=kernel_y)
    roberts_xy = cv.magnitude(roberts_x, roberts_y)

    # Before plotting we need to type convert
    roberts_x = list(np.uint8(np.abs(roberts_x)))
    roberts_y = list(np.uint8(np.abs(roberts_y)))
    roberts_xy = list(np.uint8(np.abs(roberts_xy)))

    roberts_images = [image, roberts_x, roberts_y, roberts_xy]
    titles_images = ["Orig Image", "Roberts xx", "Roberts yy", "Magnitude"]

    # Plots the images.
    fig = util.plotImages(roberts_images,
                          titles_images,
                          show=True,
                          main_title="Roberts Filter - cv.filter2D",
                          cmap="gray",
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #6
0
def canny_filter_animate(image, minvals, maxvals, ksize, filter_params, save):
    image = util.load_image_RGB(image)
    minvals = json.loads(minvals)
    maxvals = json.loads(maxvals)
    filter_params = json.loads(filter_params)

    if len(filter_params) == 2:
        print("Applying Gaussian Filter")
        image = cv.GaussianBlur(src=image,
                                ksize=(filter_params[0], filter_params[1]),
                                sigmaX=0,
                                sigmaY=0)
    # Best bilateral_params = (6, 200, 20)
    elif len(filter_params) == 3:
        print("Applying Bilateral Filter")
        image = cv.bilateralFilter(src=image,
                                   d=filter_params[0],
                                   sigmaColor=filter_params[1],
                                   sigmaSpace=filter_params[2])

    image = cv.cvtColor(src=image, code=cv.COLOR_RGB2GRAY)

    # Aperture size should be odd between 3 and 7 in function
    canny_images = []
    canny_titles = []

    minvals = np.rint(np.max(image) * np.array(minvals)).astype(int)
    maxvals = np.rint(np.max(image) * np.array(maxvals)).astype(int)

    for thrsh1 in minvals:
        for thrsh2 in maxvals:
            canny_images.append(
                cv.Canny(image=image,
                         threshold1=thrsh1,
                         threshold2=thrsh2,
                         apertureSize=ksize))
            canny_titles.append(f"minVal = {np.round(thrsh1)}, "
                                f"maxVal = {np.round(thrsh2)}")
        # Do not repeat values cause thrsh1 = 200 and thrsh2 = 180 is the same
        # as thrsh1 = 180 and thrsh2 = 200
        maxvals = np.delete(maxvals, np.argwhere(maxvals == thrsh1))

    util.animateImages(images=canny_images,
                       titles=canny_titles,
                       save_name=save,
                       cmap="gray",
                       frame_interval=120,
                       verbose=True)
예제 #7
0
def scharr_filter(image, filter_params, save, dpi, num):
    image = util.load_image_RGB(image)
    filter_params = json.loads(filter_params)

    if len(filter_params) == 2:
        print("Applying Gaussian Filter")
        image = cv.GaussianBlur(src=image,
                                ksize=(filter_params[0], filter_params[1]),
                                sigmaX=0,
                                sigmaY=0)
    # Best bilateral_params = (6, 200, 20)
    elif len(filter_params) == 3:
        print("Applying Bilateral Filter")
        image = cv.bilateralFilter(src=image,
                                   d=filter_params[0],
                                   sigmaColor=filter_params[1],
                                   sigmaSpace=filter_params[2])

    image = cv.cvtColor(src=image, code=cv.COLOR_RGB2GRAY)

    scharr_x = cv.Scharr(src=image, ddepth=cv.CV_64F, dx=1, dy=0)
    scharr_y = cv.Scharr(src=image, ddepth=cv.CV_64F, dx=0, dy=1)
    scharr_xy = cv.magnitude(scharr_x, scharr_y)

    scharr_x = list(np.uint8(np.abs(scharr_x)))
    scharr_y = list(np.uint8(np.abs(scharr_y)))
    scharr_xy = list(np.uint8(np.abs(scharr_xy)))

    scharr_images = [image, scharr_x, scharr_y, scharr_xy]
    titles_images = [
        "Original Image", "Scharr dx=1", "Scharr dy=1", "Magnitude"
    ]

    # Plots the images.
    fig = util.plotImages(scharr_images,
                          titles_images,
                          show=True,
                          main_title="Scharr Filter - cv.Scharr",
                          cmap="gray",
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #8
0
def mean_filter_anchor(image, kernel, crop_corner, crop_size, save, dpi, num):
    image = util.load_image_RGB(image)
    crop_corner = json.loads(crop_corner)

    # Initialize the anchor_images as list. Values are assigned on the for-loop
    # Initializes the kernel_max which is the maximum kernel value from Mean
    # Filter section above.
    anchor_images = []
    titles_images = []

    for a in range(0, kernel, round((kernel - 1) / 2) - 1):
        anchor_images.append(cv.blur(image, (kernel, kernel), anchor=(a, a)))
        titles_images.append(f"Anchor at ({a}, {a})")

    # Crop blurred images to better see the effect of anchor.
    anchor_images_crop = []
    for i in range(len(anchor_images)):
        anchor_images_crop.append(
            anchor_images[i][crop_corner[1]:crop_corner[1] + crop_size,
                             crop_corner[0]:crop_corner[0] + crop_size])

    # Saves individual the images.
    # util.saveImages(anchor_images_crop, titles_images, dpi=300,
    #                 save_name=save)

    # Saves an animation.
    util.animateImages(images=anchor_images_crop,
                       titles=titles_images,
                       save_name=save,
                       frame_interval=120,
                       verbose=True)

    # Plots the images.
    fig = util.plotImages(anchor_images_crop,
                          titles_images,
                          show=True,
                          main_title=f"Mean Filter Anchor @ Kernel "
                          f"{kernel}x{kernel} - cv.blur",
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #9
0
def harris_detector(image, bsize, ksize, k, threshold, filter_params, save,
                    dpi, num):
    image = util.load_image_RGB(image)
    filter_params = json.loads(filter_params)

    if len(filter_params) == 2:
        print("Applying Gaussian Filter")
        image = cv.GaussianBlur(src=image,
                                ksize=(filter_params[0], filter_params[1]),
                                sigmaX=0,
                                sigmaY=0)

    gray_image = cv.cvtColor(src=image, code=cv.COLOR_RGB2GRAY)

    harris_image = np.copy(image)
    mask = cv.cornerHarris(src=gray_image,
                           blockSize=bsize,
                           ksize=ksize,
                           k=k)

    harris_image[mask > threshold * np.max(mask)] = [255, 0, 0]

    # Convert from Float 64 to Unsigned Int 8
    # Also needs to be converted from np.array to list
    harris_image = list(np.uint8(np.abs(harris_image)))

    # Plots the images.
    fig = util.plotImages([image, harris_image],
                          ["Orig Image", "Harris Output"],
                          show=True,
                          main_title="Harris Corner Detector - cv.cornerHarris"
                                     f"\nblock size = {bsize}"
                                     f"\nsobel aperture = {ksize}"
                                     f"\nharris param = {k}",
                          cols=2,
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #10
0
def laplacian_filter(image, ksize, filter_params, save, dpi, num):
    image = util.load_image_RGB(image)
    filter_params = json.loads(filter_params)

    if len(filter_params) == 2:
        print("Applying Gaussian Filter")
        image = cv.GaussianBlur(src=image,
                                ksize=(filter_params[0], filter_params[1]),
                                sigmaX=0,
                                sigmaY=0)
    # Best bilateral_params = (6, 200, 20)
    elif len(filter_params) == 3:
        print("Applying Bilateral Filter")
        image = cv.bilateralFilter(src=image,
                                   d=filter_params[0],
                                   sigmaColor=filter_params[1],
                                   sigmaSpace=filter_params[2])

    image = cv.cvtColor(src=image, code=cv.COLOR_RGB2GRAY)

    laplacian_image = cv.Laplacian(src=image, ddepth=cv.CV_64F, ksize=ksize)

    laplacian_image = np.uint8(np.abs(laplacian_image))

    laplacian_images = [image, laplacian_image]
    titles_images = ["Orig Image", "Laplacian"]

    # Plots the images.
    fig = util.plotImages(laplacian_images,
                          titles_images,
                          show=True,
                          main_title="Laplacian Filter - cv.Laplacian",
                          cmap="gray",
                          cols=2,
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #11
0
def harris_detector_animate(image, bsizes, ksizes, ks, threshold, save):
    image = util.load_image_RGB(image)
    gray_image = cv.cvtColor(src=image, code=cv.COLOR_RGB2GRAY)

    bsizes = json.loads(bsizes)
    ksizes = json.loads(ksizes)
    ks = json.loads(ks)

    bsizes = np.rint(bsizes).astype(int)
    ksizes = np.rint(ksizes).astype(int)
    ks = np.round(ks, 2)

    harris_images = []
    harris_titles = []
    for bsize in bsizes:
        for ksize in ksizes:
            for k in ks:
                # When the number its even add one to ensure ksize is odd
                ksize = ksize + 1 if ksize % 2 == 0 else ksize
                harris_image = np.copy(image)
                mask = cv.cornerHarris(src=gray_image,
                                       blockSize=bsize,
                                       ksize=ksize,
                                       k=k)

                harris_image[mask > threshold * mask.max()] = [255, 0, 0]
                harris_images.append(harris_image)

                harris_titles.append(f"bsize={bsize}, ksize={ksize}, k={k}")

    # Convert from Float 64 to Unsigned Int 8
    # Also needs to be converted from np.array to list
    harris_images = list(np.uint8(np.abs(harris_images)))

    util.animateImages(images=harris_images,
                       titles=harris_titles,
                       save_name=save,
                       cmap="gray",
                       frame_interval=120,
                       verbose=True)
예제 #12
0
def bilateral_filter(image, diameters, sigma_c, sigma_s, save, dpi, num):
    image = util.load_image_RGB(image)
    diameters = json.loads(diameters)

    # Initialize the bilateral_images as list.
    # Values are assigned on the for-loop
    bilateral_images = []
    titles_images = []
    for d in diameters:
        bilateral_images.append(
            cv.bilateralFilter(src=image,
                               d=d,
                               sigmaColor=sigma_c,
                               sigmaSpace=sigma_s))
        titles_images.append(f"D = {d}")

    # Copy the arrays with the images generated in the for-loop and adds the
    # original noisy image for comparison. Also copies and adds the titles.
    plot_images = bilateral_images
    plot_images.insert(0, image)
    plot_titles = titles_images
    plot_titles.insert(0, "Noisy Image")

    # Plots the images.
    fig = util.plotImages(plot_images,
                          plot_titles,
                          show=True,
                          main_title=f"Bilateral Filter @ sigmaC = {sigma_c}, "
                          f"sigmaS = {sigma_s} - cv.bilateralFilter",
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #13
0
def my_harris(image, bsize, ksize, k, threshold, save, dpi, num):

    assert type(bsize) is int, "blockSize must be type int"
    assert type(ksize) is int, "ksize must be type int"
    assert type(k) is float, "k must be type float"
    assert bsize > 0, "blockSize must be greater than 0"
    assert ksize == 1 or ksize == 3 or ksize == 5 or ksize == 7, \
        "ksize must be type 1, 3, 5, or 7."

    # 1st Step: Load the image and convert the image to Gray Scale
    image = util.load_image_RGB(image)
    gray_image = cv.cvtColor(src=image, code=cv.COLOR_RGB2GRAY)

    # 2nd Step: Spatial derivative calculation
    Ix = cv.Sobel(src=gray_image, ddepth=cv.CV_64F, dx=1, dy=0, ksize=ksize)
    Iy = cv.Sobel(src=gray_image, ddepth=cv.CV_64F, dx=0, dy=1, ksize=ksize)

    # 3rd Step: Get M Matrix fields
    IxIx = Ix**2
    IyIy = Iy**2
    IxIy = Ix * Iy

    # 4th Step: Calculate the determinant and the trace of the M Matrix
    # Get the shape of the image
    height, width = np.shape(gray_image)[:2]
    # Initialize the array
    R = np.empty((height, width))

    # If the determinant is determined on a specific point do the calculus as
    # it is described.
    if bsize == 1:
        # https://www.vcalc.com/equation/?uuid=ff927310-2410-11e6-9770-bc764e2038f2
        detM = IxIx * IyIy - IxIy**2
        # https://www.vcalc.com/wiki/SavannahBergen/Trace+of+a+2x2+Matrix
        traceM = IxIx + IyIy
        # 5th Step: Compute R Value
        R = detM - k * (traceM**2)

    # If the determinant is determined based on the sum of the window do the
    # calculus with the sum of the M matrix components in that window
    else:

        offset = int(bsize / 2)

        for row in range(offset, height - offset):
            for col in range(offset, width - offset):
                # 3rd Step: Get M matrix fields of the window defined
                # by the blockSize parameter and Sum them.
                Sum_IxIx = np.sum(IxIx[row - offset:row + offset + 1,
                                       col - offset:col + offset + 1])
                Sum_IyIy = np.sum(IyIy[row - offset:row + offset + 1,
                                       col - offset:col + offset + 1])
                Sum_IxIy = np.sum(IxIy[row - offset:row + offset + 1,
                                       col - offset:col + offset + 1])

                # 4th Step: Compute det and trace of M matrix
                detM = Sum_IxIx * Sum_IyIy - Sum_IxIy**2
                traceM = Sum_IxIx + Sum_IyIy

                # 5th Step: Compute R Value of the pixel at (row, col)
                R[row, col] = detM - k * (traceM**2)

    # 6th Step: Decide if it's flat, edge or corner according to R value
    threshold = threshold * np.max(R)
    flats_image = np.copy(image)
    flats_image[(R > -threshold) & (R < threshold)] = [255, 0, 0]
    edges_image = np.copy(image)
    edges_image[R <= -threshold] = [255, 0, 0]
    corners_image = np.copy(image)
    corners_image[R >= threshold] = [255, 0, 0]

    # Beautiful Plot
    fig = util.plotImages([image, flats_image, edges_image, corners_image],
                          ["Orig Image", "Flat", "Edges", "Corners"],
                          main_title="My Harris",
                          show=True,
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #14
0
def sobel_filter_ddepth(image, ksize, threshold, filter_params, save, dpi,
                        num):
    image = util.load_image_RGB(image)
    filter_params = json.loads(filter_params)

    if len(filter_params) == 2:
        print("Applying Gaussian Filter")
        image = cv.GaussianBlur(src=image,
                                ksize=(filter_params[0], filter_params[1]),
                                sigmaX=0,
                                sigmaY=0)
    # Best bilateral_params = (6, 200, 20)
    elif len(filter_params) == 3:
        print("Applying Bilateral Filter")
        image = cv.bilateralFilter(src=image,
                                   d=filter_params[0],
                                   sigmaColor=filter_params[1],
                                   sigmaSpace=filter_params[2])

    image_gray = cv.cvtColor(src=image, code=cv.COLOR_RGB2GRAY)

    sobel_1st_float64 = cv.Sobel(src=image_gray,
                                 ddepth=cv.CV_64F,
                                 dx=1,
                                 dy=0,
                                 ksize=ksize)
    sobel_1st_float64 = np.uint8(np.abs(sobel_1st_float64))

    sobel_1st_uint8 = cv.Sobel(src=image_gray,
                               ddepth=cv.CV_8U,
                               dx=1,
                               dy=0,
                               ksize=ksize)

    sobel_2nd_float64 = cv.Sobel(src=image_gray,
                                 ddepth=cv.CV_64F,
                                 dx=2,
                                 dy=0,
                                 ksize=ksize)
    sobel_2nd_float64 = np.uint8(np.abs(sobel_2nd_float64))

    sobel_2nd_uint8 = cv.Sobel(src=image_gray,
                               ddepth=cv.CV_8U,
                               dx=2,
                               dy=0,
                               ksize=ksize)

    plot_images = [
        sobel_1st_float64, sobel_1st_uint8, sobel_2nd_float64, sobel_2nd_uint8
    ]
    plot_titles = ["dx=1 64F", "dx=1 8U", "dx=2 64F", "dx=2 8U"]

    # Plots the Black and White images.
    fig = util.plotImages(plot_images,
                          plot_titles,
                          show=True,
                          main_title="Sobel Derivatives Problems 1 - cv.Sobel",
                          cmap="gray",
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save + "_1")

    image_1st_uint8 = np.copy(image)
    image_1st_float64 = np.copy(image)
    image_2nd_uint8 = np.copy(image)
    image_2nd_float64 = np.copy(image)

    image_1st_uint8[sobel_1st_uint8 > threshold * np.max(sobel_1st_uint8)] \
        = [255, 0, 0]
    image_1st_float64[sobel_1st_float64 > threshold * np.max(sobel_1st_float64)] \
        = [255, 0, 0]
    image_2nd_uint8[sobel_2nd_uint8 > threshold * np.max(sobel_2nd_uint8)] \
        = [255, 0, 0]
    image_2nd_float64[sobel_2nd_float64 > threshold * np.max(sobel_2nd_float64)] \
        = [255, 0, 0]

    plot_images = [
        image_1st_float64, image_1st_uint8, image_2nd_float64, image_2nd_uint8
    ]
    plot_titles = ["dx=1 64F", "dx=1 8U", "dx=2 64F", "dx=2 8U"]

    if num is not None:
        num += 1
    # Plots the images.
    fig = util.plotImages(plot_images,
                          plot_titles,
                          show=True,
                          main_title="Sobel Derivatives Problems 2 - cv.Sobel",
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save + "_2")

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #15
0
def sobel_filter(image, deriv_x, deriv_y, ksize, threshold, filter_params,
                 save, dpi, num):
    image = util.load_image_RGB(image)
    deriv_x = json.loads(deriv_x)
    deriv_y = json.loads(deriv_y)
    filter_params = json.loads(filter_params)

    if len(filter_params) == 2:
        print("Applying Gaussian Filter")
        image = cv.GaussianBlur(src=image,
                                ksize=(filter_params[0], filter_params[1]),
                                sigmaX=0,
                                sigmaY=0)
    # Best bilateral_params = (6, 200, 20)
    elif len(filter_params) == 3:
        print("Applying Bilateral Filter")
        image = cv.bilateralFilter(src=image,
                                   d=filter_params[0],
                                   sigmaColor=filter_params[1],
                                   sigmaSpace=filter_params[2])

    image = cv.cvtColor(src=image, code=cv.COLOR_RGB2GRAY)

    # Initialize the mean_images as list. Values are assigned on the for-loop
    sobel_images_dx = []
    titles_images_dx = []
    for dx in deriv_x:
        # If not specified or set to None KSize is 3!
        sobel_images_dx.append(
            cv.Sobel(src=image, ddepth=cv.CV_64F, dx=dx, dy=0, ksize=ksize))
        titles_images_dx.append(f"dx = {dx}")

    sobel_images_dy = []
    titles_images_dy = []
    for dy in deriv_y:
        sobel_images_dy.append(
            cv.Sobel(src=image, ddepth=cv.CV_64F, dx=0, dy=dy, ksize=ksize))
        titles_images_dy.append(f"dy = {dy}")

    mag = cv.magnitude(sobel_images_dx[-1], sobel_images_dy[-1])
    ang = cv.phase(sobel_images_dx[-1],
                   sobel_images_dy[-1],
                   angleInDegrees=True)

    # Values below threshold are set to zero.
    # Needed to visualize the orientation/angle
    _, mask = cv.threshold(mag, np.max(mag) * threshold, 1, cv.THRESH_BINARY)

    mag = np.multiply(mask, mag)
    ang = np.multiply(mask, ang)

    sobel_images_dxdy = [mag, ang]

    titles_images_dxdy = [
        f"Magnitude\ndx = {max(deriv_x)}, "
        f"dy = {max(deriv_y)}", f"Orientation\ndx = {max(deriv_x)}, "
        f"dy = {max(deriv_y)}"
    ]

    # Before plotting we need to type convert
    sobel_images_dx = list(np.uint8(np.abs(sobel_images_dx)))
    sobel_images_dy = list(np.uint8(np.abs(sobel_images_dy)))
    sobel_images_dxdy = list(np.uint8(np.abs(sobel_images_dxdy)))

    # Copy the arrays with the images generated in the for-loop and adds the
    # original noisy image for comparison. Also copies and adds the titles.
    plot_images = sobel_images_dx + sobel_images_dy + [sobel_images_dxdy[0]]
    plot_images.insert(0, image)

    plot_titles = titles_images_dx + titles_images_dy + [titles_images_dxdy[0]]
    plot_titles.insert(0, "Original Image")

    # Plots the images.
    fig = util.plotImages(plot_images,
                          plot_titles,
                          show=True,
                          main_title="Sobel Filter - cv.Sobel",
                          cmap="gray",
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    if num is not None:
        num += 1
    # Plots the images.
    fig = util.plotImages(sobel_images_dxdy,
                          titles_images_dxdy,
                          show=True,
                          main_title="Sobel Filter - cv.Sobel",
                          cols=2,
                          cmap="turbo",
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save + "_MagAng")

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #16
0
def gaussian_filter_sigma(image, sigma_x, sigma_y, crop_corner, crop_size,
                          save, dpi, num):
    image = util.load_image_RGB(image)
    sigma_x = json.loads(sigma_x)
    sigma_y = json.loads(sigma_y)
    crop_corner = json.loads(crop_corner)

    # Initialize the gaussian_images_sigma as list.
    # Values are assigned on the for-loop.
    gaussian_images_sigmaX = []
    titles_images_X = []
    for sigX in sigma_x:
        gaussian_images_sigmaX.append(
            cv.GaussianBlur(image, (9, 9), sigmaX=sigX, sigmaY=0.1))
        titles_images_X.append(f"SigmaX = {sigX}")

    gaussian_images_sigmaY = []
    titles_images_Y = []
    for sigY in sigma_y:
        # SigmaX and SigmaY is 0 so they are calculated from kernel
        gaussian_images_sigmaY.append(
            cv.GaussianBlur(image, (9, 9), sigmaX=0.1, sigmaY=sigY))
        titles_images_Y.append(f"SigmaY = {sigY}")

    # Crop filtered images to better see the effect of Sigma.
    gaussian_images_sigmaX_crop = []
    for i in range(len(gaussian_images_sigmaX)):
        gaussian_images_sigmaX_crop.append(
            gaussian_images_sigmaX[i][crop_corner[1]:crop_corner[1] +
                                      crop_size,
                                      crop_corner[0]:crop_corner[0] +
                                      crop_size])

    gaussian_images_sigmaY_crop = []
    for i in range(len(gaussian_images_sigmaY)):
        gaussian_images_sigmaY_crop.append(
            gaussian_images_sigmaY[i][crop_corner[1]:crop_corner[1] +
                                      crop_size,
                                      crop_corner[0]:crop_corner[0] +
                                      crop_size])

    # Concat the arrays of sigmaX and sigmaY to plot
    plot_images = gaussian_images_sigmaX_crop + gaussian_images_sigmaY_crop
    # Concat the titles arrays of sigmaX and sigmaY to plot
    plot_titles = titles_images_X + titles_images_Y

    # Plots the images.
    fig = util.plotImages(plot_images,
                          plot_titles,
                          show=True,
                          main_title="Gaussian Filter Sigmas @ Kernel 9x9 - "
                          "cv.GaussianBlur",
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    # Wait for a key press to close figures
    input("Press Enter to continue...")
예제 #17
0
def bilateral_filter_sigma(image, diameter, sigma_c, sigma_s, crop_corner,
                           crop_size, save, dpi, num):
    image = util.load_image_RGB(image)
    sigma_c = json.loads(sigma_c)
    sigma_s = json.loads(sigma_s)
    crop_corner = json.loads(crop_corner)

    # Initialize the bilateral_images as list.
    # Values are assigned on the for-loop
    bilateral_images_sigmaC = []
    titles_images_sigmaC = []
    _sigS = min(sigma_s)
    for sigC in sigma_c:
        bilateral_images_sigmaC.append(
            cv.bilateralFilter(src=image,
                               d=diameter,
                               sigmaColor=sigC,
                               sigmaSpace=_sigS))
        titles_images_sigmaC.append(f"SigmaC = {sigC}")

    bilateral_images_sigmaS = []
    titles_images_sigmaS = []
    _sigC = max(sigma_c)
    for sigS in sigma_s:
        bilateral_images_sigmaS.append(
            cv.bilateralFilter(src=image,
                               d=diameter,
                               sigmaColor=_sigC,
                               sigmaSpace=sigS))
        titles_images_sigmaS.append(f"SigmaS = {sigS}")

    # Crop filtered images to better see the effect of Sigma.
    bilateral_images_sigmaC_crop = []
    for i in range(len(bilateral_images_sigmaC)):
        bilateral_images_sigmaC_crop.append(
            bilateral_images_sigmaC[i][crop_corner[1]:crop_corner[1] +
                                       crop_size,
                                       crop_corner[0]:crop_corner[0] +
                                       crop_size])

    bilateral_images_sigmaS_crop = []
    for i in range(len(bilateral_images_sigmaC)):
        bilateral_images_sigmaS_crop.append(
            bilateral_images_sigmaS[i][crop_corner[1]:crop_corner[1] +
                                       crop_size,
                                       crop_corner[0]:crop_corner[0] +
                                       crop_size])

    plot_images = bilateral_images_sigmaC_crop + bilateral_images_sigmaS_crop
    plot_titles = titles_images_sigmaC + titles_images_sigmaS

    # Plots the images.
    fig = util.plotImages(plot_images,
                          plot_titles,
                          show=True,
                          main_title=f"Bilateral Filter Sigma @"
                          f"D = {diameter} - cv.bilateralFilter",
                          num=num,
                          dpi=dpi)

    # Saves the figure.
    if save != "None":
        fig.savefig(save)

    # Wait for a key press to close figures
    input("Press Enter to continue...")