diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..18e6aa1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.idea +vscode/ +__pycache__/ \ No newline at end of file diff --git a/assignements/S1_algotools.py b/assignements/S1_algotools.py new file mode 100644 index 0000000..41a9a74 --- /dev/null +++ b/assignements/S1_algotools.py @@ -0,0 +1,318 @@ +# -*- coding: utf-8 -*- + +import numpy as np +import cv2 +import random + +""" +Session 1 Averaging + +""" +""" +Questions +What happens if Som initialization is forgotten ? + It will return an error + +What can you expect if all the values are below zero ? + It will return an error because it's impossible to divide by negative value + +Translate this algorithm in the python3.x language within script of name: + +""" + +def average_above_zero(tab): + ''' + This function give the average of positive values + Parameters: + tab: table of positive number + Returns: average + Raises: error if no positive values in tab + ''' + som = 0 + n = 0 + for i in tab: + if i > 0: + som = som + i + n = n + 1 + if n > 0: + moy = som / n + else: + raise ValueError('impossible de diviser par zero') + return moy + +print('\nAverage above 0 : {0}'.format(average_above_zero([10, 2]))+ "\n") + + +""" +Session 1 Table maximum value +Propose changes on the previous algorithm to get the maximum value of +a table. + +""" + +def max_value_without_index(tab): + ''' + This function return the highest value finded in a list + Parameters: + tab: list of number + Returns: max value + ''' + Max = 0 + for i in tab: + if i > Max: + Max = i + return Max + +print('Max value without index : {0}'.format(max_value_without_index([1,2,3,10]))+ "\n") + +""" + +Improve the previous changes by capturing the index of the last maximum value. + +""" + +def max_value(Tab): + ''' + This function return the highest value finded in a list + Parameters: + Tab: list of number + Returns: max value and his index + ''' + Max = 0 + N = 0 + Index = 0 + for i in Tab: + if i > Max: + Max = i + Index = N + N += 1 + + return (Max, Index) + + +print('Max value with index : {0}'.format(max_value([8, 3, 15])) + "\n") + +""" +Session 1 Reverse a table + +""" + +def reverse_table(tab): + ''' + This function reverse a table + Parameters: + Tab: table of number + Returns: the reversed table + ''' + + listlen = len(tab) + for i in range(listlen // 2): + tmp = tab[i] + endid = listlen - i - 1 + tab[i] = tab[endid] + tab[endid] = tmp + return tab + +print('Reverse table : {0}'.format(reverse_table([1, 2, 3, 4, 5, 6, 7, 8]))+ "\n") + + +""" +Session 1 Bounding box + +""" +H = 1000 +W = 1000 +n = np.zeros((H, W), dtype=np.uint8) +n[45:200, 70:91] = 1 + +def find_top_y(matrix): + for y in range(matrix.shape[0]): + if np.sum(matrix[y, :]): + return y + raise ValueError("no non null value found") + + +def find_top_x(matrix): + for x in range(matrix.shape[1]): + if np.sum(matrix[:, x]): + return x + raise ValueError("no non null value found") + + +def find_down_y(matrix): + for y in range(matrix.shape[0])[::-1]: + if np.sum(matrix[y, :]): + return y + raise ValueError("no non null value found") + + +def find_down_x(matrix): + for x in range(matrix.shape[1])[::-1]: + if np.sum(matrix[:, x]): + return x + raise ValueError("no non null value found") + + +def roi_bbox(image): + ''' + This function return a numpy array with the coord of a bounding box + Parameters: + image: numpy array + Returns: numpy array with 4 coordinates + ''' + return np.array([find_top_x(image), find_top_y(image), find_down_x(image), find_down_y(image)]) + +print('Bounding Box : {0}'.format(roi_bbox(n))+ "\n") + + +""" +Session 1 Random array filling + +""" + +def fill_a_rand_cell(table): + coord = (random.randint(0, table.shape[0] - 1), random.randint(0, table.shape[1] - 1)) + if table[coord] == "": + table[coord] = "X" + else: + table = fill_a_rand_cell(table) + return table + +n = np.full((20, 20), [""], dtype=str) + + +def random_fill_sparse(table, K): + ''' + This function return a numpy array with random cross in the array + Parameters: + table: an empty table + K: number of cross + Returns: the table with crosses inside + ''' + numberofcase = table.shape[0] * table.shape[1] + if numberofcase > K: + for x in range(K): + table = fill_a_rand_cell(table) + else: + raise ValueError("too much cross for the table") + return table + +print('Random fill sparse : \n {0}'.format(random_fill_sparse(n, 10))+ "\n") + +""" + +#Session 1 Remove whitespace in string + +""" + +def remove_whitespace(str): + ''' + This function return a string without whitespace + Parameters: + table: str string + Returns: the string without whitespace + ''' + if len(str) == 0: + raise ValueError('expected a non empty string') + + strReturn="" + for i in str: + if i != ' ': + strReturn += i + + return(strReturn) + +print('Remove white space : {0}'.format(remove_whitespace("A L G O I S G O O D"))+ "\n") + + +""" +Session 1 Random item selection + +""" + +def shuffle(tab): + ''' + This function randomize index of values in table + tab: a table + Returns: the string randomized + ''' + listlen = len(tab) + for i in range(listlen): + tmp=tab[i] + pos=random.randint(0,listlen-1) + tab[i] = tab[pos] + tab[pos]=tmp + + return tab + +print('Shuffle list : {0}'.format(shuffle([1,"hello",7,10]))+ "\n") + + +""" +Session 1 Selection Sort + +""" + +def sort_selective(list): + ''' + This function sort value in ascending order + Parameters: + table: table of integer + Returns: the table sorted ascendingly + ''' + + for i in range(len(list)): + min_index = i + for j in range(i+1, len(list)): + if list[min_index] > list[j]: + min_index = j + + temp = list[i] + list[i] = list[min_index] + list[min_index] = temp + + return list + +print('Selective Sort : {0}'.format(sort_selective([10,15,7,1,3,3,9]))+ "\n") + +""" +Questions : + b- Yes, the more the vector will be longer more the number of iternation will be important + c- As many as there is number in the list + d- As many as there is number in the list + e- The number of item squared + f- it's a difficulty of list squared + +""" + +""" +Session 1 Bubble Sort + +""" +def sort_bubble(list): + ''' + This function sort value in ascending order + Parameters: + table: table of integer + Returns: the table sorted ascendingly + ''' + + for passnum in range(len(list)-1,0,-1): + for i in range(passnum): + if list[i]>list[i+1]: + temp = list[i] + list[i] = list[i+1] + list[i+1] = temp + return list + +print('Bubble Sort : {0}'.format(sort_bubble([10,15,7,1,3,3,9]))+ "\n") + +""" +Questions : + b- Yes, the more the vector will be longer more the number of permutation will be important + c- As many as permutation is needed + d- As many needed until the value of every entry is lower than the next entry + e- As many as there is iteration + f- The list squared + +""" \ No newline at end of file diff --git a/assignements/S1_dice.py b/assignements/S1_dice.py new file mode 100644 index 0000000..b9fb386 --- /dev/null +++ b/assignements/S1_dice.py @@ -0,0 +1,77 @@ +import random as random + +def shuffle (): + user_score = 0 + comp_score = 0 + winner = '' + temp2 = 0 + + print('------------------------------------------------------\n Bienvenue dans le meilleur jeu de dés de l\'unvivers \n------------------------------------------------------') + + while(winner == ''): + print("Score Joueur : " + str(user_score) + "\nScore PC : " + str(comp_score)) + temp = user_turn() + temp2 += temp + if(temp != 0 and temp != -1): + user_score += temp + print('---------- SCORE TOTAL JOUEUR : ' + str(user_score) + ' ----------') + if(user_score >= 100): + winner = "Joueur" + + if(temp == 0 or temp == -1): + if(temp == 0): + user_score -= temp2 + temp_comp = comp_turn() + comp_score += temp_comp + temp2 = 0 + if(comp_score >= 100): + winner = "PC" + + print("------------------------------------------------------\n Le gagnant de la partie est : " + str(winner) + ' \n------------------------------------------------------') + + +def user_turn(): + point = -1 + roll = 0 + play = input("Voulez vous lancer le dé ? (y or otherkey)") + + if (play == "y"): + point = 0 + roll = roll_dice() + if(roll == 1): + point = 0 + print("Vous avez perdu vos points pour ce tour car vous avez fait 1") + else: + point += roll + print("Score du tour : " + str(point)) + + return point + + +def comp_turn(): + point = 0 + roll = 0 + + print("---------------- Tour du Pc : ----------------") + + while(roll != 1): + roll = roll_dice() + print("Le pc à fait : " + str(roll)) + if(roll == 1): + print("Le PC a fait 1 et a perdu ces points pour ce tour") + point = 0 + else: + point += roll + + print("---------------- Score PC : " + str(point) + ' ---------------------') + + if(point > roll_dice() * 6): + break + + return point + + +def roll_dice (): + return int(random.randint(1,6)) + +shuffle() \ No newline at end of file diff --git a/assignements/S3_imgproc_tools.py b/assignements/S3_imgproc_tools.py new file mode 100644 index 0000000..8e3b86c --- /dev/null +++ b/assignements/S3_imgproc_tools.py @@ -0,0 +1,90 @@ +import cv2 +import numpy as np + +def invert_colors_manual_old(input_img): + ''' + + This function reverse the color of an image + Parameters: + input_img: an image + Returns: a reversed image + + ''' + img_out = np.zeros(input_img.shape, dtype=np.uint8) + for row in range(input_img.shape[0]): + for col in range(input_img.shape[1]): + for channel in range(input_img.shape[2]): + img_out[row,col,channel]=255-input_img[row,col,channel] + + return img_out + +def invert_colors_manual(input_img): + ''' + + This function reverse the color of an image + Parameters: + input_img: an image + Returns: a reversed image + + ''' + if input_img.dtype!=np.dtype(np.uint8): + raise TypeError('expected uint8 typed nd array') + return 255-input_img + + +def invert_colors_numpy(input_img): + ''' + + This function reverse the color of an image + Parameters: + input_img: an image + Returns: a reversed image + + ''' + return np.invert(input_img) + +def invert_colors_opencv(input_img): + ''' + + This function reverse the color of an image + Parameters: + input_img: an image + Returns: a reversed image + + ''' + return cv2.bitwise_not(input_img) + +img_gray=cv2.imread("trou_noir.jpg",0) +img_bgr=cv2.imread("trou_noir.jpg",1) +img_bgr_reversed = invert_colors_opencv(cv2.imread("trou_noir.jpg",1)) + +cv2.imshow("Gray levels image", img_gray) +cv2.imshow("BGR image", img_bgr) +cv2.imshow("BGR image inverted", img_bgr_reversed) +cv2.waitKey() + + +''' +Image Thresholging +''' + +def threshold_image_manual(img:np.ndarray) : + ''' + + This function will only rely on raw python with loop without the use of + any external library. It takes as input a loaded image and returns the + transformed image. + + ''' + + threshold_value = 128 + if img.dtype!=np.dtype(np.uint8): + raise TypeError ('expected uint8typs nd array') + return img>threshold_value + +img=cv2.imread("trou_noir.jpg",0) +img_thresholded=threshold_image_manual(img) + +img_threshold_disp=img_thresholded.astype(np.uint8)*255 +cv2.imshow('seuilled image', img_threshold_disp) +cv2.waitKey() diff --git a/assignements/queue_publish_read.py b/assignements/queue_publish_read.py new file mode 100644 index 0000000..17cc27f --- /dev/null +++ b/assignements/queue_publish_read.py @@ -0,0 +1,73 @@ +import argparse +import pika + +count = 0 + +import myKeysCloudAMQP +import os + +amqp_url= myKeysCloudAMQP.cloud_amqp_key +url = os.environ.get('CLOUDAMQP_URL',amqp_url) +params = pika.URLParameters(url) + + +def publish(message,concurencebool): + """ + this function upload a message on a queue + Params: + message: a string that will be uploaded + """ + + default_message="Hey" + if message != "" and message != None : + default_message = message + + connection = pika.BlockingConnection(params) + channel=connection.channel() + channel.queue_declare(queue='hello') + if concurencebool : + channel.basic_publish(exchange='', + routing_key='hello', + body=str(default_message), + properties=pika.BasicProperties(delivery_mode=2)) + print("Pouet ") + else: + channel.basic_publish(exchange='', + routing_key='hello', + body=str(default_message)) + print("[x] Sent "+str(default_message)) + connection.close() + +def read(): + """ + this fuction wait and consume a message snded on a queue + """ + def callback(ch,method,properties,body): + print(" [x] Received %r" % body) + global count + count +=1 + print("number of received event : " + str(count)) + print(amqp_url) + connection = pika.BlockingConnection(params) + channel=connection.channel() + channel.queue_declare(queue='hello') + + channel.basic_consume(queue='hello', + on_message_callback = callback, + auto_ack=True) + print(' [*] Waiting for messages. o exit press CTRL+C') + channel.start_consuming() + + +parser = argparse.ArgumentParser() +parser.add_argument('-read', action='store_true') +parser.add_argument('-m') +parser.add_argument('-concurrency', action='store_true') +args = parser.parse_args() +if args.read : + read() +else: + publish(args.m,args.concurrency) + + + """ test """ \ No newline at end of file diff --git a/assignements/simple_queue_publish.py b/assignements/simple_queue_publish.py new file mode 100644 index 0000000..0ed9d7e --- /dev/null +++ b/assignements/simple_queue_publish.py @@ -0,0 +1,18 @@ +import pika +import myKeysCloudAMQP +import os + +amqp_url= myKeysCloudAMQP.cloud_amqp_key +url = os.environ.get('CLOUDAMQP_URL',amqp_url) +params = pika.URLParameters(url) +params.socket_timeout = 5 + + +connection = pika.BlockingConnection(params) +channel = connection.channel() +channel.queue_declare(queue='hello') + +channel.basic_publish(exchange='', + routing_key='hello', + body='Hello World!') +print(" [x] Sent 'Hello World!'") \ No newline at end of file diff --git a/assignements/simple_queue_read.py b/assignements/simple_queue_read.py new file mode 100644 index 0000000..a3726d7 --- /dev/null +++ b/assignements/simple_queue_read.py @@ -0,0 +1,26 @@ +import pika +import myKeysCloudAMQP +import os + +amqp_url= myKeysCloudAMQP.cloud_amqp_key +url = os.environ.get('CLOUDAMQP_URL',amqp_url) +params = pika.URLParameters(url) + +count = 0 +connection = pika.BlockingConnection(params) +channel = connection.channel() +channel.queue_declare(queue='hello') +channel.basic_qos(prefetch_count=1) + + +def callback (ch, method, properties, body): + print("[x] Received %r" % body) + global count + count += 1 + print("[x] Message Processed, acknowledging, nb message sent: "+str(count)+" (o delete message from the queue)") + +channel.basic_consume(queue='hello', + on_message_callback=callback, + auto_ack=True) +channel.start_consuming() + diff --git a/assignements/test_S2.py b/assignements/test_S2.py new file mode 100644 index 0000000..bc45249 --- /dev/null +++ b/assignements/test_S2.py @@ -0,0 +1,142 @@ +import pytest +import cv2 +import numpy as np +import S1_algotools as s1 + +""" + Test Average_above_zero + +""" + +def test_average_above_zero(): + assert s1.average_above_zero([5, 7]) == 6 + +def test_average_above_zero_not_a_list(): + with pytest.raises(TypeError): + s1.average_above_zero(6) + +def test_average_above_zero_empty_list(): + with pytest.raises(ValueError): + s1.average_above_zero([]) + +def test_averrage_above_zero_negative_input(): + with pytest.raises(ValueError): + s1.average_above_zero([-1,-1]) == 6 + + +""" + Test Max value + +""" +def test_max_value(): + assert s1.max_value([1,7,3,-6,5,2] ) == (7,1) + +def test_max_value_not_a_list(): + with pytest.raises(TypeError): + s1.max_value(3) + +def test_max_value_not_a_number(): + with pytest.raises(TypeError): + s1.max_value('a') + + +""" + Test Reverse table + +""" + +def test_reverse_table(): + assert s1.reverse_table([1,2,3,4,5,6,7]) == [7,6,5,4,3,2,1] + +def test_reverse_table_value_not_a_number(): + with pytest.raises(TypeError): + s1.max_value('a') + +def test_reverse_table_not_a_list(): + with pytest.raises(TypeError): + s1.reverse_table(3) + +""" + Test Bounding Box +""" + +def test_roi_bbox(): + H=1000 + W=1000 + n = np.zeros((H,W),dtype=np.uint8) + n[45:200,70:91] = 1 + assert np.prod(s1.roi_bbox(n).all() == np.array([70,45,90,199]).all()) + +def test_roi_bbox_not_an_array(): + with pytest.raises(TypeError): + s1.roi_bbox() + +def test_roi_bbox_modification(): + H=200 + W=800 + d = np.zeros((H,W),dtype=np.uint8) + d[45:123,54:70] = 1 + assert not np.prod(s1.roi_bbox(d) == np.array([70,45,90,199])) + +""" + Test Random fill sparse +""" + +def test_random_fill_sparse(): + n = np.full((10,10),[""],dtype=str) + val = 3 + assert np.where(s1.random_fill_sparse(n,val)=='X')[0].shape[0]==val + + +def test_random_fill_sparse_too_much_cross(): + n = np.full((10,10),[""],dtype=str) + val = 10000 + with pytest.raises(ValueError): + s1.random_fill_sparse(n,val) + +""" + Test Remove whitespace +""" + +def test_remove_whitespace(): + assert s1.remove_whitespace('Hey Coucou') == 'HeyCoucou' + +def test_remove_whitespace_without_space(): + assert s1.remove_whitespace('HeyCoucou') == 'HeyCoucou' + +def test_remove_whitespace_not_a_char(): + with pytest.raises(TypeError): + s1.remove_whitespace(1) + +def test_remove_whitespace_empty_string(): + with pytest.raises(ValueError): + s1.remove_whitespace('') + +""" + Test Selective sort +""" + +def test_sort_selective(): + assert s1.sort_selective([4,9,1,5]) == [1,4,5,9] + +def test_sort_selective_is_empty(): + with pytest.raises(TypeError): + assert s1.sort_selective() + +def test_sort_selective_is_false(): + assert s1.sort_selective([3,2,1]) != [1,3,2] + +""" + Test Bubble sort +""" + +def test_sort_bubble(): + assert s1.sort_bubble([4,9,1,5]) == [1,4,5,9] + +def test_sort_selective_not_a_number(): + with pytest.raises(TypeError): + assert s1.sort_selective('a') + +def test_sort_selective_failure(): + with pytest.raises(TypeError): + assert s1.sort_selective(1) \ No newline at end of file diff --git a/assignements/test_S3.py b/assignements/test_S3.py new file mode 100644 index 0000000..d29ef0e --- /dev/null +++ b/assignements/test_S3.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +""" +Created on Tue Sep 29 10:52:59 2020 + +@author: ceriatik +""" + +import pytest +import S3_imgproc_tools as S3 +import numpy as np + +def test_invert_colors_manual_tuNone(): + with pytest.raises(AttributeError): + S3.invert_colors_manual(None) + +def test_invert_colors_manual_tuArray(): + with pytest.raises(AttributeError): + S3.invert_colors_manual(1) + +def test_invert_colors_manual_tuuint8(): + with pytest.raises(TypeError): + S3.invert_colors_manual(np.zeros(2,2), dtype=np.float32) + +def test_innv_color_manual_Array(): + with pytest.raises(AttributeError): + S3.invert_colors_manual(1) + +def test_innv_color_manual(): + img_in = np.array([[[0,255,0], [0,255,0], [0,255,0]], + [[0,255,128], [0,255,128], [0,255,128]], + [[0,128,255], [0,128,255], [0,128,255]]],dtype=np.uint8) + img_out = np.array([[[255,0,255], [255,0,255], [255,0,255]], + [[255,0,127], [255,0,127], [255,0,127]], + [[255,127,0], [255,127,0], [255,127,0]]],dtype=np.uint8) + assert np.prod(S3.invert_colors_manual(img_in) == np.array(img_out)) + +def test_invert_colors_opencv_is_empty(): + with pytest.raises(TypeError): + S3.invert_colors_opencv() + +def test_invert_colors_numpy_no_img_out(): + img_in = np.array([[[0,255,0], [0,255,0], [0,255,0]], + [[0,255,128], [0,255,128], [0,255,128]], + [[0,128,255], [0,128,255], [0,128,255]]],dtype=np.uint8) + img_out = np.array([[[255,0,255], [255,0,255], [255,0,255]], + [[255,0,127], [255,0,127], [255,0,127]], + [[255,127,0], [255,127,0], [255,127,0]]],dtype=np.uint8) + with pytest.raises(TypeError): + np.prod(S3.invert_colors_manual(img_in) == np.array()) \ No newline at end of file diff --git a/trou_noir.jpg b/trou_noir.jpg new file mode 100644 index 0000000..4d3f759 Binary files /dev/null and b/trou_noir.jpg differ