Exemplo n.º 1
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the either the img or the kernel.
        (2) pads the img or the flipped img.
            this step handles pixels along the border of the img,
            and makes sure that the output img is of the same size as the input image.
        (3) applies the flipped kernel to the image or the kernel to the flipped image,
            using nested for loop.

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), image.
    """
    # TODO: implement this function.
    # raise NotImplementedError
    flipped_img = utils.flip2d(img)
    convoluted_img = copy.deepcopy(flipped_img)

    padded_img = utils.zero_pad(convoluted_img, 1, 1)

    for i in range(len(convoluted_img)):
        for j in range(len(convoluted_img[0])):
            convoluted_img[i][j] = utils.add_matrix(
                utils.elementwise_mul(
                    utils.crop(padded_img, i, i + 3, j, j + 3), kernel))

    return utils.flip2d(convoluted_img)
Exemplo n.º 2
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips either the img or the kernel.
        (2) pads the img or the flipped img.
            this step handles pixels along the border of the img,
            and makes sure that the output img is of the same size as the input image.
        (3) applies the flipped kernel to the image or the kernel to the flipped image,
            using nested for loop.

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), image.
    """
    # TODO: implement this function.
    flipped_img = utils.flip2d(img)
    padded_img = utils.zero_pad(flipped_img, 1, 1)
    img_conv = np.zeros((len(img), len(img[0])))
    for i in range(1, len(padded_img)-2):
        for j in range(1, len(padded_img[0])-2):
            img_sec = utils.crop(padded_img, i-1, i+2, j-1, j+2)
            prod = utils.elementwise_mul(kernel, img_sec)
            res = 0
            for g in range(len(prod)):
                for h in range(len(prod[0])):
                    res += prod[g][h]
            img_conv[i-1][j-1] = res
    img_conv = utils.flip2d(img_conv)
    # raise NotImplementedError
    return img_conv
Exemplo n.º 3
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calucates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """

    ### Creating a output buffer ###\
    # output = np.zeros_like(img)

    ### Padding the image with zeros on all sides ###
    padding_width = 1
    image_array = np.array(utils.zero_pad(img, padding_width, padding_width))
    # image_shape = {'width': len(image_array[0]), 'height': len(image_array)}
    ''' 
    Flattening and flipping the kernel
    flattening the kernel so that I can perform
    linear convolution operation(on 1D array) on the image 
    '''
    # kernel = np.array(kernel).flatten()[::-1]

    # for h in range(image_shape['height']-2):
    #     for w in range(image_shape['width']-2):
    #         a = image_array[h:h+3,w:w+3].flatten()

    #         # Performing linear convolution operation on image with kernel
    #         sum = np.sum(kernel * a, dtype=np.uint8)
    #         output[h][w] = sum

    # for h in range(image_shape['height']-2):
    #     for w in range(image_shape['width']-2):
    #         subImg = image_array[h:h+3,w:w+3]
    #         b = utils.elementwise_mul(subImg,flip_kernel)
    #         ### Performing linear convolution operation on image with kernel ###
    #         output[h][w] = np.sum(b, dtype=np.uint8)

    output = []
    flip_kernel = utils.flip2d(kernel)

    for h in range(len(img) - 2):
        w_op = []
        for w in range(len(img[0]) - 2):
            sum_img = 0
            for k in range(len(flip_kernel)):
                for l in range(len(flip_kernel[0])):
                    sum_img += img[h + k][w + l] * flip_kernel[k][l]
            w_op.append(sum_img)
        output.append(w_op)

    return output
Exemplo n.º 4
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calucates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    # TODO: implement this function.
    flipped_kernel = utils.flip2d(kernel)
    pad_size = int((len(kernel) - 1) / 2)
    padded_img = utils.zero_pad(img, pad_size, pad_size)
    filtered_img = copy.deepcopy(img)

    for i, row in enumerate(img):
        for j, pix in enumerate(row):
            patch = utils.crop(padded_img, i, i + 2 * pad_size + 1, j,
                               j + 2 * pad_size + 1)
            patch = utils.elementwise_mul(patch, kernel)
            filtered_img[i][j] = sum([sum(l) for l in patch])

    return filtered_img
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calucates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    # TODO: implement this function.
    kl = len(kernel)
    pad = int(len(kernel) / 2)
    kernel = utils.flip2d(kernel)
    img_padded = utils.zero_pad(img, pad, pad)
    for x, row in enumerate(img):
        for y, num in enumerate(row):
            if (x < len(img[0]) - (round(len(kernel) / 2))
                    or y < len(img) - (round(len(kernel) / 2))):
                imgfoc = utils.elementwise_mul(
                    kernel, utils.crop(img_padded, x, x + kl, y, y + kl))
                sumele = 0
                for i in range(len(imgfoc)):
                    sumele += sum(subl[i] for subl in imgfoc)
                img[x][y] = sumele
    return img
    raise NotImplementedError
Exemplo n.º 6
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the either the img or the kernel.
        (2) pads the img or the flipped img.
            this step handles pixels along the border of the img,
            and makes sure that the output img is of the same size as the input image.
        (3) applies the flipped kernel to the image or the kernel to the flipped image,
            using nested for loop.

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), image.
    """
    # TODO: implement this function.
    img_conv = [[0 for i in range(len(img[0]))] for j in range(len(img))]
    flipped_kernel = utils.flip2d(kernel)
    padded_img = utils.zero_pad(img, 1, 1)  #Padding = (size of kernel - 1) / 2
    neighbors = [(0, 0), (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1),
                 (-1, 1), (-1, -1)]
    for r in range(1, len(padded_img) - 1):
        for c in range(1, len(padded_img[0]) - 1):
            for _r, _c in neighbors:
                img_conv[r - 1][c - 1] += padded_img[r + _r][
                    c + _c] * flipped_kernel[1 + _r][1 + _c]
    #raise NotImplementedError
    return img_conv
Exemplo n.º 7
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the either the img or the kernel.
        (2) pads the img or the flipped img.
            this step handles pixels along the border of the img,
            and makes sure that the output img is of the same size as the input image.
        (3) applies the flipped kernel to the image or the kernel to the flipped image,
            using nested for loop.

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), image.
    """
    # TODO: implement this function.
    kernel = utils.flip2d(kernel)
    img = zero_pad(img)
    height = len(img)
    width = len(img[0])
    img_conv = []
    for i in range(1, height - 1):
        row = []
        for j in range(1, width - 1):
            total = 0
            for p in range(3):
                for q in range(3):
                    total += (img[i - 1 + p][j - 1 + q] * kernel[p][q])
            row.append(total)
        img_conv.append(row)
    #raise NotImplementedError
    return img_conv
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the either the img or the kernel.
        (2) pads the img or the flipped img.
            this step handles pixels along the border of the img,
            and makes sure that the output img is of the same size as the input image.
        (3) applies the flipped kernel to the image or the kernel to the flipped image,
            using nested for loop.

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), image.
    """
    # TODO: implement this function.
    # raise NotImplementedError

    kernel_flip = utils.flip2d(kernel)
    img_pad = utils.zero_pad(img,1,1)

    kernel_row = len(kernel)
    kernel_col = len(kernel[0])

    # img_conv = np.zeros(np.shape(img_pad))

    image_ = copy.deepcopy(img_pad)
    # print(kernel_flip_y)

    # for row_index,row_value in enumerate(img_pad[1:-1]):
    #     for col_index, col_value in enumerate(row_value[1:-1]):
    #        sum_ = 0 
    #        for i in range(-1,2):
    #            for j in range(-1,2):
    #                sum_ += img_pad[row_index+i][col_index+j]*kernel_flip_y[1+i][1+j]
    #        image_[row_index][col_index]= sum_   


    for row_index, row_value in enumerate(img_pad[:-2]):
        for col_index,col_val in enumerate(row_value[:-2]):
            img_temp = utils.crop(img_pad,row_index,(row_index+kernel_row),col_index,(col_index+kernel_col))
            imp_temp_1 = utils.elementwise_mul(img_temp,kernel)
            img_conv_sum = pixel_conv_sum(imp_temp_1)
            image_[row_index+1][col_index+1] = img_conv_sum


    img_conv = image_
    img_conv = utils.crop(img_conv,1,257,1,257)
    # print(f'The Type for convo is {type(img_conv)}')
    return img_conv
Exemplo n.º 9
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.
    
    Steps:
        (1) flips either the img or the kernel.

        (2) pads the img or the flipped img. This step handles pixels along the border of the img,
            and makes sure that the output img is of the same size as the input image.

        (3) applies the flipped kernel to the image or the kernel to the flipped image,using nested for loop.

    Args:
        img   : nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), image.
    """
    # TODO: DONE

    padding_layer = len(kernel) // 2

    kernel = utils.flip2d(kernel)  # flip the kernel
    img = utils.zero_pad(img, padding_layer,
                         padding_layer)  # padding the image

    row_count = len(img)
    col_count = len(img[0])

    # output image having same size as the input image
    img_conv = []

    zeros = [0] * (col_count - 2 * padding_layer)

    for i in range(row_count - 2 * padding_layer):
        img_conv.insert(0, [0 for value in enumerate(zeros)])

    kernel_h = len(kernel)
    kernel_w = len(kernel[0])

    for i in range(row_count - kernel_h + 1):
        for j in range(col_count - kernel_w + 1):
            # multiplying the cropped portion with kernel
            mult_result = utils.elementwise_mul(
                utils.crop(img, i, i + kernel_h, j, j + kernel_w), kernel)
            sum = 0
            for p in range(len(mult_result)):
                for q in range(len(mult_result[p])):
                    sum += mult_result[p][q]
            img_conv[i][j] = sum

    #raise NotImplementedError
    return img_conv
Exemplo n.º 10
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calculates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    """" Step 1: Flip the kernel """ ""
    utils.flip2d(kernel)
    """" Step 2: Pad the image """ ""
    padded_img = utils.zero_pad(img, 1, 1)
    """" Step 3: Calculate convolved image using nested for loop. """ ""
    # nested for loops to iterate through image to select each pixel
    for i in range(len(img)):
        for j in range(len(img[0])):

            pixel_val = 0

            # iterate through kernel to compute sum
            for k in range(len(kernel)):
                for l in range(len(kernel[0])):
                    pixel = padded_img[i + k][j + l]
                    pixel_val = pixel_val + (pixel * kernel[k][l])

            img[i][j] = pixel_val

    return img

    # TODO: implement this function.
    raise NotImplementedError
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calucates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    # TODO: implement this function.

    # Flipping the kernel to x-axis and then y-axis
    flip_kernel = utils.flip2d(kernel, axis=None)

    # Checking the kernel matrix dimension
    kernel_height = len(flip_kernel)
    kernel_width = len(flip_kernel[0])
    pwx = (kernel_height - 1) // 2
    pwy = (kernel_width - 1) // 2

    # Padding the image with zero padding
    img_padding = utils.zero_pad(img, pwx, pwy)
    # Checking the padded image dimension
    img_padding_h = len(img_padding)
    img_padding_w = len(img_padding[0])

    # Creating a copy of input image
    output = copy.deepcopy(img)

    for x in range(img_padding_h - (pwx * 2)):
        for y in range(img_padding_w - (pwx * 2)):
            # Cropping the image as kernel dimension
            crop_img = utils.crop(img_padding, x, x + kernel_height, y,
                                  y + kernel_width)
            # Multiplying the elements of Cropped image matrix and kernel matrix
            img_mult = utils.elementwise_mul(crop_img, flip_kernel)
            sum_elem = 0
            for m in range(len(img_mult)):
                for n in range(len(img_mult[0])):
                    # Adding the matrix elements
                    sum_elem = sum_elem + img_mult[m][n]
            output[x][y] = sum_elem

    return output
Exemplo n.º 12
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calucates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    # TODO: implement this function.
    #raise NotImplementedError

    # flip
    kernel = utils.flip2d(kernel)
    #########################
    #padding

    pr = int((len(kernel) - 1) / 2)
    pc = int((len(kernel[0]) - 1) / 2)

    img = utils.zero_pad(img, pr, pc)

    ###########################
    #cnn

    temp = []
    dotp = []
    k_flat = flat(kernel)
    new = []
    img_conv = []
    for k in range(len(img) - len(kernel) + 1):
        for l in range(len(img[0]) - len(kernel[0]) + 1):

            for i in range(len(kernel)):
                for j in range(len(kernel[0])):
                    temp.append(img[i + k][j + l])
            dotp = dotpro(temp, k_flat)
            temp = []
            new.append(dotp)
        img_conv.append(new)
        new = []

    return img_conv
Exemplo n.º 13
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calucates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    # TODO: implement this function.
    flipped_kernel=utils.flip2d(kernel)
    #number of row and cols padding will, be equal to length of rows and columns minus 1 respectively
    padding_rows=len(kernel)-1
    padding_cols=len(kernel[0])-1
    padded_image=utils.zero_pad(img,padding_rows,padding_cols)
    #copied the padded image to a temporary variable to modify the convolution changes
    temp_array=copy.deepcopy(padded_image)
    for i in range(len(padded_image)-1):
        for j in range(len(padded_image[0])-1):
            #created patches of each matrices which overlap with kernel
            xmin=i
            xmax=i+len(flipped_kernel)
            ymin=j
            ymax=j+len(flipped_kernel[0])
            patch = padded_image[xmin: xmax]
            patch = [row[ymin: ymax] for row in patch]
            #multiplied each element of patch with corresponding element of flipped kernel and calculated the end summation
            multiplied=utils.elementwise_mul(patch,flipped_kernel)
            summation=0
            for m in range(len(multiplied)):
                for n in range(len(multiplied[0])):
                    summation+=multiplied[m][n]
            temp_array[i][j]=summation
    #set min and max x and y for croping the padded image
    min_x=padding_rows-1
    max_x=len(padded_image)-(padding_rows+1)
    min_y=padding_cols-1
    max_y=len(padded_image[0])-(padding_cols+1)
    temp_array=utils.crop(temp_array,min_x,max_x,min_y,max_y)
    return temp_array
Exemplo n.º 14
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the either the img or the kernel.
        (2) pads the img or the flipped img.
            this step handles pixels along the border of the img,
            and makes sure that the output img is of the same size as the input image.
        (3) applies the flipped kernel to the image or the kernel to the flipped image,
            using nested for loop.

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), image.
    """
    # TODO: implement this function.

    row_zero = len(img)
    pixel_zero = len(img[0])
    width = pixel_zero
    height = row_zero
    dim = (height, width)
    pad_len = 1
    kernel_dim = 3

    img_conv = np.zeros(dim)
    # print(str(len(img_conv)) + str(len(img_conv[0])))
    kernel_flip = utils.flip2d(kernel)
    pad_img = utils.zero_pad(img, pad_len, pad_len)

    i_conv = 0
    for i in range(1, row_zero + 1):
        j_conv = 0
        for j in range(1, pixel_zero + 1):
            for k in range(0, kernel_dim):
                for l in range(0, kernel_dim):
                    x = i + k - 1
                    y = j + l - 1
                    img_conv[i_conv][j_conv] += (pad_img[x][y] * kernel_flip[k][l])
            j_conv += 1
        i_conv += 1

    return img_conv
Exemplo n.º 15
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calucates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    # TODO: implement this function.
    # Initialization and Primary Calculation
    img_height = len(img)
    kernel_height = len(kernel)
    kernel_width = len(kernel[0])
    pwx = (kernel_height - 1) // 2
    pwy = (kernel_height - 1) // 2
    flip_kernel = utils.flip2d(
        kernel, axis=None)  #flipping the kernel along x-axis and y-axis
    Zero_padded_image = utils.zero_pad(img, pwx, pwy)  #Image with zero padding
    Zero_padded_image_h = len(Zero_padded_image)  #Height of zero padded image
    Zero_padded_image_w = len(
        Zero_padded_image[0])  #Width of zero padded image
    img_res = copy.deepcopy(img)

    for x in range(Zero_padded_image_h - (pwx * 2)):
        for y in range(Zero_padded_image_w - (pwy * 2)):
            img_crop = utils.crop(
                Zero_padded_image, x, x + kernel_height, y, y + kernel_width
            )  #Cropping the zero padded image with flipped kernel
            mult_element = utils.elementwise_mul(img_crop, flip_kernel)

            sum_element = 0
            for i in range(len(mult_element)):
                for j in range(len(mult_element[0])):
                    sum_element = sum_element + mult_element[i][j]
            img_res[x][y] = sum_element  #Creating output image

    return img_res
Exemplo n.º 16
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the either the img or the kernel.
        (2) pads the img or the flipped img.
            this step handles pixels along the border of the img,
            and makes sure that the output img is of the same size as the input image.
        (3) applies the flipped kernel to the image or the kernel to the flipped image,
            using nested for loop.

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), image.
    """
    #print(len(img),len(img[0]))
    pwx = 1
    pwy = 1
    #print(kernel)
    kernel = utils.flip2d(kernel, None)
    #print(kernel)
    img = utils.zero_pad(img, pwx, pwy)
    #print(len(img),len(img[0]))
    img_conv = copy.deepcopy(img)
    for i in range(1, len(img) - 1):
        for j in range(1, len(img[0]) - 1):
            img_inter = utils.elementwise_mul(
                utils.crop(img, i - 1, i + 2, j - 1, j + 2), kernel)
            #print(img_inter)
            sum = 0
            for k in [0, 1, 2]:
                for l in [0, 1, 2]:
                    sum += img_inter[k][l]
            #print(sum)
            img_conv[i][j] = sum
    img_conv = utils.crop(img_conv, 1,
                          len(img_conv) - 1, 1,
                          len(img_conv[0]) - 1)
    #print(len(img_conv),len(img_conv[0]))
    # TODO: implement this function.
    #raise NotImplementedError
    return img_conv
Exemplo n.º 17
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calculates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    # flips the kernel
    flipped_kernel = utils.flip2d(kernel)
    # using 2k+1 form to calc the value of k
    k = int((len(kernel) - 1) / 2)

    # padding the image
    padded_img = utils.zero_pad(img, k, k)

    # TODO:implement this function.
    # implementing convolution
    # master loop for img array
    for row in range(0, len(img)):
        for col in range(0, len(img[0])):
            # creating the convolution matrix for applying the filter from img
            convolve_img_matrix = utils.crop(padded_img, row,
                                             row + len(kernel), col,
                                             col + len(kernel[0]))
            convolve_img_matrix_mul_kernel = utils.elementwise_mul(
                convolve_img_matrix, flipped_kernel)
            # calculating the convoluted value for the pixel
            convoluted_value = 0
            for val_list in convolve_img_matrix_mul_kernel:
                for val in val_list:
                    convoluted_value = convoluted_value + val
            # replacing the value in padded_img
            img[row][col] = convoluted_value

    return img
Exemplo n.º 18
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the either the img or the kernel.
        (2) pads the img or the flipped img.
            this step handles pixels along the border of the img,
            and makes sure that the output img is of the same size as the input image.
        (3) applies the flipped kernel to the image or the kernel to the flipped image,
            using nested for loop.

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), image.
    """
    kernel = utils.flip2d(kernel)
    img = utils.zero_pad(img, 1, 1)
    ConvolutedImg = []
    m = 0
    n = 0
    sum = 0
    for i in range(0, len(img) - 2):
        row = []
        for j in range(0, len(img) - 2):
            m = 0
            for k in range(i, i + 3):
                for l in range(j, j + 3):
                    sum = sum + img[k][l] * kernel[m][n]
                    n = n + 1
                n = 0
                m = m + 1
            row.append(sum)
            sum = 0
        ConvolutedImg.append(row)
        row = []
    # TODO: implement this function.
    #raise NotImplementedError
    print("convoluted")
    print(np.shape(ConvolutedImg))
    return ConvolutedImg
Exemplo n.º 19
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calucates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    # TODO: implement this function.
    # raise NotImplementedError

    rows = (len(img))
    cols = (len(img[0]))
    """flipping kernel"""
    kernel = utils.flip2d(kernel)
    """padding the image"""
    img = utils.zero_pad(img, 1, 1)
    """convolution"""

    img_conv = []

    for i in range(rows):
        each_row = []
        for j in range(cols):

            dot_product = 0
            for m in range(i, i + len(kernel)):
                for n in range(j, j + len(kernel[0])):

                    dot_product += img[m][n] * kernel[m - i][n - j]
            each_row.append(dot_product)
        img_conv.append(each_row)

    return img_conv
Exemplo n.º 20
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel. """
    row = len(img)
    col = len(img[0])
    flipped_kernel = utils.flip2d(kernel)
    padded_img = utils.zero_pad(img, 1, 1)
    rowpad = len(padded_img)
    colpad = len(padded_img[0])

    img_conv = np.zeros(shape=(rowpad, colpad))
    subImg = np.zeros(shape=(3, 3))

    for i in range(0, rowpad-2):
        for j in range(0, colpad-2):
            subImg = imageSubPart(padded_img, i, j)
            newval = filterSobel(subImg, flipped_kernel)
            """Write normalize call"""
            img_conv[i, j] = newval

    return img_conv
Exemplo n.º 21
0
def detect_edges(img, kernel, norm=True):
    """Detects edges using a given kernel.

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel used to detect edges.
        norm (bool): whether to normalize the image or not.

    Returns:
        img_edge: nested list (int), image containing detected edges.
    """
    # TODO: detect edges using convolve2d and normalize the image containing detected edges using normalize.
#    img_edges = normalize(img)
    img_edges = utils.flip2d(convolve2d(img,kernel))
    if norm == True:
        img_edges = normalize(img_edges)
#    detect_edges = convolve2d(img,kernel)
#    img_edges = normalize(detect_edges)
#    raise NotImplementedError
    return img_edges
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calucates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    kernel = utils.flip2d(kernel, axis=None)
    px = int(len(kernel) / 2)
    py = int(len(kernel[0]) / 2)
    img = utils.zero_pad(img, px, py)
    m = len(kernel)
    n = len(kernel[0])
    x = len(img)
    y = len(img[0])
    x = x - m + 1
    y = y - n + 1
    int_img = []
    for i in range(x):
        for j in range(y):
            a = [temp[j:j + n] for temp in img[i:i + m]]
            int_img.append(a)
    final = []
    for k in int_img:
        b = utils.elementwise_mul(k, kernel)
        total = 0
        for abc in b:
            for xyz in abc:
                total += xyz
        final.append(total)
    img_conv = [final[i:i + y] for i in range(0, len(final), y)]
    return img_conv
Exemplo n.º 23
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calucates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    # TODO: implement this function.
    # raise NotImplementedError

    d_img = copy.deepcopy(img)

    # Flip the Kernel
    f_ker = utils.flip2d(kernel)

    # Add padding of 1 for a 3x3 template
    p_img = utils.zero_pad(img, pwx=1, pwy=1)

    # Cropping a 3x3 template and performing element wise multiplication.
    # Taking the sum of the multiplied values and inserting the sum in the middle most cell of the image.
    print("length:", len(img))
    print("height:", len(img[0]))

    for r in range(len(img)):
        for c in range(len(img[0])):
            c_img = utils.crop(p_img, r, r + 3, c, c + 3)
            m_img = utils.elementwise_mul(c_img, kernel)
            sum_val = sum([i for s in m_img for i in s])
            d_img[r][c] = sum_val

    return d_img
Exemplo n.º 24
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the either the img or the kernel.
        (2) pads the img or the flipped img.
            this step handles pixels along the border of the img,
            and makes sure that the output img is of the same size as the input image.
        (3) applies the flipped kernel to the image or the kernel to the flipped image,
            using nested for loop.

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), image.
    """
    # TODO: implement this function.

    flipped_kernel = utils.flip2d(kernel)

    padded_img = utils.zero_pad(img, 1, 1)

    temp = []
    convolved_img = []

    for i in range(len(img)):
        for j in range(len(img[i])):
            cropped_img = utils.crop(padded_img, i, i+3, j, j+3)

            mul_op = utils.elementwise_mul(cropped_img, flipped_kernel)

            value = sum([sum(a) for a in mul_op])
            temp.append(value)
        convolved_img.append(temp)
        temp = []

    # raise NotImplementedError
    return convolved_img
Exemplo n.º 25
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the either the img or the kernel.
        (2) pads the img or the flipped img.
            this step handles pixels along the border of the img,
            and makes sure that the output img is of the same size as the input image.
        (3) applies the flipped kernel to the image or the kernel to the flipped image,
            using nested for loop.

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), image.
    """
    # TODO: implement this function.

    flipped_k = utils.flip2d(kernel, axis=None)
    img_h = len(img)
    img_w = len(img[0])
    kernel_row = len(kernel)
    kernel_column = len(kernel[0])  #kernel size is 3,given in line 30-35
    img_padded = utils.zero_pad(img, 1, 1)
    img_conv = [[0 for row in range(img_w)] for column in range(img_h)]

    for i in range(1, img_h - 2):
        for j in range(1, img_w - 2):
            sum = 0
            for m in range(kernel_row):
                for n in range(kernel_column):
                    sum = sum + (img_padded[i + m][j + n] * flipped_k[m][n])
            img_conv[i + 1][j + 1] = sum
            #Center of the kernel here is (i+1)and (j+1)

    # raise NotImplementedError
    return img_conv
Exemplo n.º 26
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calucates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    # TODO: implement this function.

    img_h = len(img)
    img_w = len(img[0])
    padded_img = utils.zero_pad(img, 1, 1)  # Pads img with zero at the border.
    new_img = [
        [0 for x in range(img_w)] for y in range(img_h)
    ]  # Create a new two-dimensional list to store the calculated values
    kernel = utils.flip2d(kernel)  # flips the kernel
    kernel_h = len(kernel)
    kernel_w = len(kernel[0])

    for m in range(img_h):
        for n in range(img_w):
            s = 0
            for x in range(kernel_h):
                for y in range(kernel_w):
                    s = s + kernel[x][y] * padded_img[m + x][n + y]
            new_img[m][n] = s

    return new_img

    raise NotImplementedError
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the either the img or the kernel.
        (2) pads the img or the flipped img.
            this step handles pixels along the border of the img,
            and makes sure that the output img is of the same size as the input image.
        (3) applies the flipped kernel to the image or the kernel to the flipped image,
            using nested for loop.

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), image.
    """
    # TODO: implement this function.

    #flippedAndPadded_img=u.zero_pad(u.flip_x(img), 1, 1)
    #length=len(flippedAndPadded_img)-len(kernel)+1
    #print("Length is"+str(length))
    #result=np.zeros((length, length))
    #for i in range(length):
    #   for j in range(length):
    #       result[i][j]=multiply_add(u.crop(flippedAndPadded_img,i,i+3,j,j+3),kernel)

    kernel = u.flip2d(kernel)
    zeropadded_Image = u.zero_pad(img, 1, 1)

    img_conv = copy.deepcopy(img)
    for m, row in enumerate(img):
        for i, pixel in enumerate(row):
            cp = u.crop(zeropadded_Image, m, m + 3, i, i + 3)
            mulValue = u.elementwise_mul(cp, kernel)
            img_conv[m][i] = task2.addAllElements(mulValue)

    return img_conv
Exemplo n.º 28
0
def convolve2d(img, kernel):
    """
    Convolves a given image and a given kernel.

    Steps:
        (1) flips the either the img or the kernel.
        (2) pads the img or the flipped img.
            this step handles pixels along the border of the img,
            and makes sure that the output img is of the same size as the input image.
        (3) applies the flipped kernel to the image or the kernel to the flipped image,
            using nested for loop.

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), image.
    """
    # Image dimensions
    m, n = len(img), len(img[0])

    # Filter dimensions
    k, l = len(kernel), len(kernel[0])

    flipped_filter = utils.flip2d(kernel)

    img_padded = utils.zero_pad(img, 1, 1)

    img_conv = [[0 for _ in range(n)] for _ in range(m)]

    for i in range(m):
        for j in range(n):
            img_ = utils.crop(img_padded, i, i + k, j, j + l)
            mul = utils.elementwise_mul(img_, flipped_filter)
            img_conv[i][j] = sum([sum(x) for x in mul]) * 1.0

    return img_conv
Exemplo n.º 29
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calucates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    # Flip Kernel
    flipped_kernel = utils.flip2d(kernel)

    # Pad image
    kernelx = len(kernel)
    kernely = len(kernel[0])
    pad_amt_x = int(kernelx / 2)
    pad_amt_y = int(kernely / 2)
    padded_img = utils.zero_pad(img, pad_amt_x, pad_amt_y)

    # Convolve image with kernel
    convolved_img = copy.deepcopy(img)
    for i in range(len(img)):
        for j in range(len(img[0])):
            weighted_sum = 0
            for ki in range(kernelx):
                for kj in range(kernely):
                    weighted_sum += flipped_kernel[ki][kj] * padded_img[i +
                                                                        ki][j +
                                                                            kj]
            convolved_img[i][j] = weighted_sum
    return convolved_img
Exemplo n.º 30
0
def convolve2d(img, kernel):
    """Convolves a given image and a given kernel.

    Steps:
        (1) flips the kernel
        (2) pads the image # IMPORTANT
            this step handles pixels along the border of the image, and ensures that the output image is of the same size as the input image
        (3) calucates the convolved image using nested for loop

    Args:
        img: nested list (int), image.
        kernel: nested list (int), kernel.

    Returns:
        img_conv: nested list (int), convolved image.
    """
    # TODO: implement this function.
    # raise NotImplementedError

    imgSizeX = len(img)
    imgSizeY = len(img[0])
    kernelSizeX = len(kernel)
    kernelSizeY = len(kernel[0])
    paddingSizeX = kernelSizeX//2
    paddingSizeY = kernelSizeY//2

    flippedKernel = utils.flip2d(kernel)

    paddedImg = utils.zero_pad(img, paddingSizeX, paddingSizeY)
    convolvedImg = [[0 for x in range(imgSizeY)] for y in range(imgSizeX)]

    for i in range(imgSizeX):
        for j in range(imgSizeY):
            for u in range(kernelSizeX):
                for v in range(kernelSizeY):
                    convolvedImg[i][j] += flippedKernel[u][v]*paddedImg[i+u][j+v]

    return convolvedImg