Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

**The code must be on google Colab, if not please mention it in the solution** The text code: # DO NOT CHANGE ANYTHING IN THIS

**The code must be on google Colab, if not please mention it in the solution**

image text in transcribedimage text in transcribedimage text in transcribedimage text in transcribedimage text in transcribed

The text code:

# DO NOT CHANGE ANYTHING IN THIS CELL

import numpy as np

from typing import Tuple, List

def create_array(size: int, stripe_len: int = 3):

img = np.zeros((size, size), dtype=np.uint8)

for i in range(img.shape[0]):

count = np.random.randint(1, 5)

for _ in range(count):

first_idx = np.random.randint(0, size)

img[i, first_idx:first_idx+stripe_len] = np.random.randint(0, 255)

return img

----------------------------------

# Implement the functions in this cell.

def run_length_encode(arr: np.ndarray) -> List[List[Tuple[int]]]:

"""Encodes given image using run-length algorithm.

Args:

arr (np.ndarray): Grayscale image with shape (m, n)

Returns:

List[List[Tuple[int]]]: Encoded image. Each row of pixels

are represented as list of tuples, containing pixel intensity and

length of that pixel intensity. Each row encoding should be stored

in a list. Output list should match m (arr.shape[0]).

For each row of pixels, return a list of tuples in a list

ex. [(pixel_intensity0, len0), (pixel_intensity1, len1), ...]

Example input (as a numpy array)

[[1, 1, 1, 0, 0], # Row 1

[2, 2, 0, 1, 1], # Row 2

[6, 6, 6, 0, 1]] # Row 3

Example output

[[(1, 3), (0, 2)], # Row 1

[(2, 2), (0, 1), (1, 2)], # Row 2

[(6, 3), (0, 1), (1, 1)]] # Row 3

"""

###### YOUR CODE ######

pass

def run_length_decode(encoding: List[List[Tuple[int]]]) -> np.ndarray:

"""Create and return the original array from the encoded array, without any loss.

Args:

encoding (List[List[Tuple[int]]]): Encoding output from run_length_encode function.

Where each row of pixels are represented as list of tuples, containing pixel intensity and

length of that pixel intensity and row encodings are stored

in a list.

Returns:

np.ndarray: Decoded image.

"""

###### YOUR CODE ######

pass

def run_length_encode_RGB(arr: np.ndarray) -> List[List[List[Tuple[int]]]]:

"""Applies run_length_encode to an RGB image, with 3 channels.

Args:

arr (np.ndarray): RGB image with shape (3, m, n)

Returns:

List[List[List[Tuple[int]]]]: List of encoded channels. Length of

the output should be 3.

"""

###### YOUR CODE ######

pass

def run_length_decode_RGB(encodings: List[List[List[Tuple[int]]]]) -> np.ndarray:

"""Reconstructs the original image without any loss, using run length algorithm

and encoding of the image.

Args:

encodings (List[List[List[Tuple[int]]]]): List of encoded channels. Length of

the encodings should be 3.

Returns:

np.ndarray: Reconstructed image with shape (3, m, n).

"""

###### YOUR CODE ######

pass

-------------------------

# Calculate compression ratio and data redundancy in this cell.

# You may want to take a look at the lecture slides to remember the formulas.

------------------------------

# DO NOT CHANGE ANYTHING IN THIS CELL

# This cell must run without any errors.

np.random.seed(14)

tests = [10, 30, 50]

for val in tests:

# Grayscale

arr1 = create_array(val)

# RGB

arr2 = np.zeros((3, val, val))

arr2[0, :, :] = create_array(val)

arr2[1, :, :] = create_array(val)

arr2[2, :, :] = create_array(val)

encoded_arr1 = run_length_encode(arr1)

decoded_arr1 = run_length_decode(encoded_arr1)

assert (decoded_arr1 == arr1).all() # Decoded array should be the same as original

encoded_arr2 = run_length_encode_RGB(arr2)

decoded_arr2 = run_length_decode_RGB(encoded_arr2)

assert (decoded_arr2 == arr2).all() # Decoded array should be the same as original

-------------------------------------

## Part 2

------------

import cv2

import numpy as np

def show_image(img: np.ndarray, window_name: str = ""):

# Modify this function if you are using Colab.

cv2.imshow(window_name, img)

cv2.waitKey(0)

cv2.destroyAllWindows()

images = []

for filename in ["house.png", "nothouse.png", "square.png", "triangle.png", "rotated_house.png"]:

images.append(cv2.imread(filename))

show_image(images[-1], filename + f" with shape {images[-1].shape}")

\#\# Part 1 \#\#\# Instructions - Overview the theory of run-length encoding algorithm from your lecture slides. - Implement run-length encoding algorithm for grayscale and RGB images. - Write a function to calculate the ** compression ratio** function should take original and encoded image as inputs. - Calculate the number of bits to represent original image and the encoded image. - ***nly consider numbers** in the encoding, not the memory size of lists or tuples. - Write the function to calculate **data redundancy** using the compression ratio. - Only change the parts where you see the indicator \#\#\#\#\# YOuR CODE \#\#\#\#\#. - You can find requirements for the specific functions in the function ** docstrings** - Try your compression function with a bigger array (eg. shape (1000,1000), calculate w* compression ratio and data redundancy*** \#-DO - NOT - CHANGE - ANYTHING - IN - THIS - CELL import - numpy as np from-typing - import-Tuple, - List def-create_array (size:-int, stripe_len:-int = = 3): img = np.zeros (( size, size ), dtype=np. uint8 ) for i in-range (img - shape [] ): count = = np. random. randint (1,5) for _ in-range(count): first_idx = np.random.randint (, size ) img [i, first_idx:first_idx+stripe_len] = np.random.randint (,255) \#-Calculate-compression-ratio-and-data-redundancy -in-this cell. AYou-may - want - to take-a - look - at - the - lecture - slides - to - remember-the formulas. \#- DO - NOT - CHANGE - ANYTHING - IN - THIS - CELL A. This - cell-must-run-without-any - errors. np.random.seed (14) tests =[10,30,50] for val in tests: - \#-Grayscale arp1 = create_array (val) \#\#-Part 2 \#\#\# Instructions "rotated_house.png" images. - Make the images same size. Show them side by side. - Write a function named " rect_or_triangle" to determine the shape of objects. (triangle, square) - Input to the function must be a single image represented as numpy a array. - Determine and apply necessary preprocessing steps (thresholding, noise removal, edge detection etc.) - Determine the shapes in the image utilizing the contours. - Hints: "cv2.findContours", "cv2.approxPolyDP" - The function should be able to detect multiple objects in a given image. - Output of the function must be list of strings, containing the name of the objects in the image. - eg. If the image contains 2 triangles and 3 squares: ["triangle", "square", "square", "triangle", "square"] - Write a function named "is house" to determine if a given image contains a house drawing or not. - Function must be able to detect rotated houses (" rotated_house.png ) - Input should be an image and output should be a boolean value. "True" if image contains a house, "False" otherwise

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions

Question

How to reverse a Armstrong number by using double linked list ?

Answered: 1 week ago

Question

1. Why do people tell lies on their CVs?

Answered: 1 week ago

Question

2. What is the difference between an embellishment and a lie?

Answered: 1 week ago