informatique (tronc commun des prépas scientifiques) · Chapitre 8 · Exercice de TD
Valider une bibliothèque d'images
Matrices de pixels et images · niveau 3 (difficile)
Énoncé
Concevoir un programme de test pour s'assurer du bon fonctionnement des transformations (négatif, miroir, rotation, réduction et convolution) sans modifier l'image d'origine.
Corrigé
import random
def image_aleatoire():
n, p = random.randint(1, 8), random.randint(1, 8)
return [[random.randint(0, 255) for _ in range(p)] for _ in range(n)]
def copie(img):
return [ligne[:] for ligne in img]
# 1. Tests unitaires sur une matrice témoin asymétrique 2x3
T = [[1, 2, 3], [4, 5, 6]]
assert negatif(T) == [[254, 253, 252], [251, 250, 249]]
assert miroir(T) == [[3, 2, 1], [6, 5, 4]]
assert rotation_horaire(T) == [[4, 1], [5, 2], [6, 3]]
assert reduction([[1, 3], [5, 7]], 2) == [[4]]
# 2. Tests de propriétés algébriques sur 500 configurations aléatoires
random.seed(8)
for _ in range(500):
img = image_aleatoire()
img_backup = copie(img)
assert miroir(miroir(img)) == img
assert negatif(negatif(img)) == img
r = rotation_horaire(img)
assert (len(r), len(r[0])) == (len(img[0]), len(img))
assert rotation_horaire(rotation_horaire(rotation_horaire(rotation_horaire(img)))) == img
# Vérification de l'absence d'effets de bord sur l'image source
convolution(img, [[1/9]*3]*3)
assert img == img_backup