<jupyter_start><jupyter_text>Computer Vision: Assignment 1  | [<NAME>](https://github.com/AmrMKayid)| [<NAME>](https://github.com/AbdullahKady) || :---: | :---: | | **37-15594** | **37-16401** || **T10** | **T10** |<jupyter_code>%reload_ext autoreload
%autoreload 2
%matplotlib inline<jupyter_output><empty_output><jupyter_text>Problem 1Implement a function to increase the contrast of any gray-scale image according to the transformation given below and compute the contrast using the co-occurrence matrix measure given in lectures. The function should take as inputs the gray-scale image in addition to the parameters A, B, C and D. The function should output the transformed image. Apply your function to the “Ocean.bmp”image. Deliverables:    - Your code.    - A .bmp file for the transformed image with         - (a) A=30, B=20, C=180 and D=230 and         - (b) A=70, B=20, C=140 and D=240.    - Name the files “Ocean_a.bmp” and “Ocean_b.bmp”.    - A text file containing the contrast value for both images. Name the file “contrast.txt”.<jupyter_code>import numpy as np
import matplotlib.pyplot as plt

from PIL import Image
ocean_image = Image.open('Ocean.bmp')
plt.imshow(ocean_image, cmap="gray")
ocean_image, ocean_image.format, ocean_image.size, ocean_image.mode
ocean_image_np = np.array(ocean_image)
ocean_image_np, ocean_image_np.shape
def get_straight_line_eq(x1, y1, x2, y2):
    """
    The general equation of a straight line is y = mx + c
    where m is the gradient, and c is the intercept on the y-axis. 
    """
    m = ((y2 - y1) / (x2 - x1))
    c = y1 - (m * x1)
    return m, c
def change_contrast(img, a, b, c, d):
    """
    Method that change the contrast according to the a,b,c,d values
    """
    m1, c1 = get_straight_line_eq(0, 0, a, b)
    m2, c2 = get_straight_line_eq(a, b, c, d)
    m3, c3 = get_straight_line_eq(c, d, 255, 255)
    
    first_mask = ((img >= 0) & (img <= a))
    second_mask = ((img > a) & (img <= c))
    third_mask = ((img > c) & (img <= 255))
    
    img = np.where(first_mask, (m1 * img) + c1, img)
    img = np.where(second_mask, (m2 * img) + c2, img)
    img = np.where(third_mask, (m3 * img) + c3, img)
    
    return img.astype(int)
ocean_a_np = change_contrast(ocean_image_np, 30, 20, 180, 230)
ocean_a = Image.fromarray(ocean_a_np.astype('uint8'))
plt.imshow(ocean_a, cmap="gray")
ocean_a.save("Ocean_a.bmp")
ocean_b_np = change_contrast(ocean_image_np, 70, 20, 140, 240)
ocean_b = Image.fromarray(ocean_b_np.astype('uint8'))
plt.imshow(ocean_b, cmap="gray")
ocean_b.save("Ocean_b.bmp")
def get_co_occurrence_matrix(img):
    """
    Co-occurrence Matrix Algorithm:
    """
    
    img_np = np.array(img)
    co_occurence_matrix = np.zeros((256, 256))

    for row in range(0, img_np.shape[0] - 1):
        for col in range(0, img_np.shape[1]):

            north_value = img_np[row, col]
            south_value = img_np[row + 1, col]
            co_occurence_matrix[north_value, south_value] += 1

    return co_occurence_matrix
def get_contrast_from_co_occurence_matrix(img):
    contrast = 0
    co_occurence_matrix = get_co_occurrence_matrix(img)

    for row in range(0, co_occurence_matrix.shape[0]):
        for col in range(0, co_occurence_matrix.shape[1]):
            contrast += co_occurence_matrix[row, col] * ((row - col) ** 2)
    return contrast
ocean_image_contrast = get_contrast_from_co_occurence_matrix(ocean_image)
f'Contrast Of (Original Ocean) Image: {ocean_image_contrast}'
ocean_a_image_contrast = get_contrast_from_co_occurence_matrix(ocean_a)
f'Contrast Of (Ocean_a) Image: {ocean_a_image_contrast}'
ocean_b_image_contrast = get_contrast_from_co_occurence_matrix(ocean_b)
f'Contrast Of (Ocean_b) Image: {ocean_b_image_contrast}'
contrast_file = open("contrast.txt", "w")
out = (f'Contrast Of (Ocean_a) Image: {ocean_a_image_contrast}\n' + 
       f'Contrast Of (Ocean_b) Image: {ocean_b_image_contrast}')
contrast_file.write(out)
contrast_file.close()
out<jupyter_output><empty_output><jupyter_text>Problem 2 **a)** Implement the integral image algorithm that can obtain the integral image for any gray-scale image. Apply your function to the image “cameraman.tif”. Your function should take the image as an input and should output the integral image.Deliverables:    - Your code.    - The integral image obtained for the “cameraman.tif” image. Name the file “Camera_Integ.jpg”<jupyter_code>np.cumsum?
def integral_image_algorithm(img, normalized=True):    
    f = np.array(img)
    s = np.array(img).astype("uint32")
    
    for row in range(0, s.shape[0]):
        for col in range(1, s.shape[1]):
            s[row, col] = s[row, col - 1] + f[row, col]
            
    ii_img = np.array(s)
    for row in range(1, s.shape[0]):
        for col in range(0, s.shape[1]):
            ii_img[row, col] = ii_img[row - 1, col] + s[row, col]
            
    if normalized:
        ii_img = (ii_img - np.min(ii_img)) / (np.max(ii_img) - np.min(ii_img)) * 255
    
    return ii_img
def ii_img_using_numpy(img, normalized=True):    
    ii_img = np.array(img)
    for i in range(ii_img.ndim):
        ii_img = ii_img.cumsum(axis=i)
    if normalized:
        ii_img = (ii_img - np.min(ii_img)) / (np.max(ii_img) - np.min(ii_img)) * 255
    return ii_img
cameraman_img = Image.open("Cameraman_noise.bmp")
ii_img = integral_image_algorithm(cameraman_img)
plt.imshow(ii_img, cmap="gray"); ii_img
ii_img_using_np = ii_img_using_numpy(cameraman_img)
plt.imshow(ii_img_using_np, cmap="gray"); ii_img_using_np
ii_image = Image.fromarray(ii_img.astype('uint8'))
ii_image.save("Camera_Integ.jpg")<jupyter_output><empty_output><jupyter_text>**b)** Implement an average filter for noise removal that uses the function you wrote in (a). Apply your function to the image “cameraman.tif”. Your function should take the image as an input in addition to the size of the filter (s x s). The function should output the filtered image.Deliverables:    - Your code.    - The filtered image obtained for a filter size of 3 x 3. Name the file “Camera_Filt_3.jpg”    - The filtered image obtained for a filter size of 5 x 5. Name the file “Camera_Filt_5.jpg”<jupyter_code>np.pad?
def avg_filter(img, kernal_size=3):
    ii_img = integral_image_algorithm(img, normalized=False)
    
    offset = kernal_size // 2
    pad = kernal_size // 2 + 1
    padded_ii_img = np.pad(ii_img, pad_width=pad)
    output_img = np.zeros(ii_img.shape)
    
    for row in range(ii_img.shape[0] - offset):
        for col in range(ii_img.shape[1] - offset):
            bottom_right = padded_ii_img[row + offset][col + offset] 
            top_left = padded_ii_img[row - offset - 1][col - offset - 1]
            top_right = padded_ii_img[row - offset - 1][col + offset]
            bottom_left = padded_ii_img[row + offset][col - offset - 1]
#             print(bottom_right, top_left, top_right, bottom_left)
            output_img[row][col] = ((bottom_right + top_left) - ( top_right + bottom_left)) // (kernal_size**2)
    
    return output_img
cameraman_img = Image.open("Cameraman_noise.bmp")
plt.imshow(cameraman_img, cmap="gray")
avg_filtered_img_3_by_3 = avg_filter(cameraman_img, kernal_size=3)
plt.imshow(avg_filtered_img_3_by_3, cmap="gray")
Camera_Filt_3 = Image.fromarray(avg_filtered_img_3_by_3.astype('uint8'))
Camera_Filt_3.save("Camera_Filt_3.jpg")
avg_filtered_img_5_by_5 = avg_filter(cameraman_img, kernal_size=5)
plt.imshow(avg_filtered_img_5_by_5, cmap="gray")
Camera_Filt_5 = Image.fromarray(avg_filtered_img_5_by_5.astype('uint8'))
Camera_Filt_5.save("Camera_Filt_5.jpg")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12128810875016498, 'fraction_numerical': 0.023096212221195723, 'mean_word_length': 3.914396887159533, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 22, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '598676', 'license': 'MIT', 'n_tokens_mistral': 2954, 'n_tokens_neox': 2789, 'n_words': 677, 'path': 'Assignment1/assignment1.ipynb', 'repo_name': 'AmrMKayid/computer-vision', 'size': '7592'}