from umage import load, save, show_image def grayscale(img_mat): """Transform an image into gray :img_mat: image en entree :returns: grayscale de limage em entree """ new_matrix = list() for row in range(len(img_mat)): new_matrix.append(list()) for column in img_mat[row]: _r, _g, _b = column gray = round(0.2125 * _r + 0.7154 * _g + 0.0721 * _b) new_matrix[row].append((gray, gray, gray)) return new_matrix def convolution(img_mat, mat): """effectue le passage d'une matrice de convolution sur une image grise TODO: image de couleurs :img_mat: image en entree :mat: matrice de convolution :returns: image retouchee """ new_matrix = list() for row in range(len(img_mat)): new_matrix.append(list()) for column in range(len(img_mat[row])): # _gray = img_mat[row][column][0] _sum = 0 for mat_row in range(len(mat)): for mat_column in range(len(mat[mat_row])): diff_row = mat_row - len(mat)//2 diff_col = mat_column - len(mat[mat_column])//2 if dans_image(img_mat, row+diff_row, column+ diff_col): _sum += mat[mat_row][mat_column] * img_mat[row + diff_row][column + diff_col][0] new_matrix[row].append((_sum, _sum, _sum)) return new_matrix def dans_image(img_mat, row, col): if row < len(img_mat)-1 and row > 0 and col < len(img_mat[0])-1 and col > 0: return True return False if __name__ == "__main__": unit = [ [0, 1, 0], [0, 0, 0], [0, 0, 0]] convolution1 = [ [-1, -1, -1], [-1, 8, -1], [-1, -1, -1]] convolution2 = [ [-1, -1, -1], [-1, 9, -1], [-1, -1, -1]] convolution3 = [ [-2, 0, 0], [ 0, 1, 0], [ 0, 0, 2]] img = load('./myimg.jpg') new_image = grayscale(img) convolution(new_image, convolution2) save(new_image, 'gray') save(convolution(new_image, convolution1), 'convo1') save(convolution(new_image, convolution2), 'convo2') save(convolution(new_image, convolution3), 'convo3')